📜 ⬆️ ⬇️

Partial trick with partial index

On the channel #postgresql today there was one very interesting question (changed for readability):

I need to create a constraint (constraint) on the table. The constraint should check the uniqueness of two fields: string and boolean. However, there is an additional requirement. Only one record with a certain string and the value TRUE is allowed. At the same time, several entries are allowed with some string, but the value is FALSE. For example, there may be several {"abc", false}, but only one line {"abc", true}.


Well, it would seem, what is the importance of this task? It's just a very good example of using the flexibility of PostgreSQL , which has partial partial indices in its assets. The solution is simple and elegant:

CREATE TABLE foo (bar TEXT , bing BOOLEAN );
')
CREATE UNIQUE INDEX baz_index ON foobar (bar, bing) WHERE bing = 't' ;

INSERT INTO foobar VALUES ( '1' , 't' );
INSERT INTO foobar VALUES ( '2' , 't' );
INSERT INTO foobar VALUES ( '1' , 'f' );
INSERT INTO foobar VALUES ( '1' , 'f' );
INSERT INTO foobar VALUES ( '1' , 't' );
ERROR: duplicate key violin value constraint constraint "baz_index"

All ingenious is simple. So that!

Source: https://habr.com/ru/post/97378/


All Articles