In Postgresql, force unique on combination of two columns
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a integer primary key generated always as identity
(or serial
if you use PG 9 or lower. serial
was soft-deprecated in PG 10).
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
Unique constraint for 2 columns that works both ways
You can create a unique index that always indexes the same order of values:
create unique index
on friends (least(requestor, requestee), greatest(requestor, requestee));
Postgresql enforce unique two-way combination of columns
A variation on Neil's solution which doesn't need an extension is:
create table friendz (
from_id int,
to_id int
);
create unique index ifriendz on friendz(greatest(from_id,to_id), least(from_id,to_id));
Neil's solution lets you use an arbitrary number of columns though.
We're both relying on using expressions to build the index which is documented
https://www.postgresql.org/docs/current/indexes-expressional.html
Unique constrain for values combination in Postgresql
You can't do this with a consraint. However, in Postgres, a partial unique index would do exactly what you want:
create unique index myindex on mytable(code) where (deleted = false);
You can also phrase this as:
create unique index myindex on mytable(code) where (not deleted);
Unique constraint on combination of two columns?
You can do this using an index on expressions:
create unique index unq_test_a_b on (test(least(a, b), greatest(a, b));
I don't think the unique
constraint allows expressions (and don't have a convenient Postgres to test on right now), but this is essentially the same thing.
Related Topics
How to Generate Date Series to Occupy Absent Dates in Google Biqquery
SQL Error: Ora-02291: Integrity Constraint
Select Rows with Maximum Column Value Group by Another Column
SQL Not Displaying Null Values on a Not Equals Query
Ora-01861: Literal Does Not Match Format String
How to Create a Table Alias in MySQL
Create a Delimitted String from a Query in Db2
What Is "Connect Timeout" in SQL Server Connection String
How to Combine Results of Two Queries into a Single Dataset
Inner Join VS Multiple Table Names in "From"
Writing a Subquery Using Zend Db
SQL Combine Two Columns in Select Statement
How to Compare Software Versions Using SQL Server
Why No Output When Plsql Anonymous Block Completes
How to Create Daylight Savings Time Start and End Function in SQL Server
Need a Row Count After Select Statement: What's the Optimal SQL Approach