Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL constraint - only one row can have flag set

Tags:

sql

postgresql

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?

like image 789
Lecko Avatar asked Jan 27 '15 09:01

Lecko


People also ask

Could I make a column in a table only allows one true value and all other rows should be false?

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/…)

What is exclusion constraint?

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.

What is unique index in Postgres?

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.

How do I change unique constraints in PostgreSQL?

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.


1 Answers

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

like image 91
a_horse_with_no_name Avatar answered Sep 29 '22 02:09

a_horse_with_no_name