The trick with partial (partial) index

channel #postgresql we heard today a very interesting question (modified for readability):

I need to create a restriction (constraint) on the table. The restriction should validate uniqueness of two fields: string and Boolean. However, there is an additional requirement. There must be only one record with a certain string and value is TRUE. At the same time, there may be several records with a certain string, but a value of FALSE. For example, there may be several {"abc", false}, but only one string {"abc", true}.


Well, it would seem, what's the importance of this objective? It's just a very good example of using flexibility PostgreSQL, which has to its credit the mechanism of partial indexes (partial indices). 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 value violates unique constraint "baz_index"

All ingenious is simple. So what!
Article based on information from habrahabr.ru

Популярные сообщения из этого блога

Approval of WSUS updates: import, export, copy

The Hilbert curve vs. Z-order

Kaspersky Security Center — the fight for automation