CREATE TABLE user_friends ( user_id_1 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, user_id_2 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (user_id_1, user_id_2), CONSTRAINT chk_different_users CHECK (user_id_1 <> user_id_2), -- Ensures (1,2) and (2,1) are treated as the same unique pair to prevent duplicate friendships CONSTRAINT unique_friendship UNIQUE (LEAST(user_id_1, user_id_2), GREATEST(user_id_1, user_id_2)) );
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The issue with your table definition is that PostgreSQL doesn't support using functions like LEAST() and GREATEST() directly in a UNIQUE constraint definition. This will throw a syntax error when you try to create the table.
Here are two ways to fix this:
Option 1: Use a unique index instead of a constraint
sql
CREATE TABLE user_friends (
user_id_1 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
user_id_2 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id_1, user_id_2),
CONSTRAINT chk_different_users CHECK (user_id_1 <> user_id_2)
);
-- Create a unique index to prevent duplicate friendships
CREATE UNIQUE INDEX idx_unique_friendship
ON user_friends (LEAST(user_id_1, user_id_2), GREATEST(user_id_1, user_id_2));
Option 2: Enforce ordering with a check constraint
sql
CREATE TABLE user_friends (
user_id_1 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
user_id_2 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id_1, user_id_2),
-- Ensure user_id_1 is always less than user_id_2
CONSTRAINT chk_ordered_users CHECK (user_id_1 < user_id_2)
);
With Option 2, you would need to ensure that when inserting friendships, you always put the smaller ID in user_id_1 and the larger ID in user_id_2. This approach is simpler but requires your application logic to handle the ordering.
Option 1 is more flexible as it allows inserting friendships in either order (1,2) or (2,1), while Option 2 requires consistent ordering but has a simpler schema. Choose based on your application's needs.