I have a PostgreSQL table
CREATE TABLE my_table ( id serial NOT NULL, name text, actual boolean DEFAULT false, CONSTRAINT my_table_pkey PRIMARY KEY (id), );
How can I set a constraint that only one row can have actual
flag set to TRUE
?
Yep. And it would be possible to use a check constraint to ensure that only one row exists (using Celko's technique here sqlmonster.com/Uwe/Forum.aspx/ms-sql-server/3453/…)
Exclusion Constraints. Exclusion constraints ensure that if any two rows are compared on the specified columns or expressions using the specified operators, at least one of these operator comparisons will return false or null.
PostgreSQL automatically creates a unique index when a unique constraint or primary key is defined for a table. The index covers the columns that make up the primary key or unique constraint (a multicolumn index, if appropriate), and is the mechanism that enforces the constraint.
The syntax for creating a unique constraint using an ALTER TABLE statement in PostgreSQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.
You can create a unique index on that column only for true values:
create unique index on my_table (actual) where actual = true;
SQLFiddle: http://sqlfiddle.com/#!15/91f62/1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With