This article is half-done without your Comment! *** Please share your thoughts via Comment ***
If we want to store range of data, we have very good options RANGE DATATYPE in PostgreSQL.
In one of our reporting servers, require to store a range of date bases on unique log code.
Means, one unique code cannot be duplicated with the same range of dates.
We can store a range of dates using TSRANGE DATATYPE, but I have to also add one constraint which checks the unique combination of value and range.
Here, I have taken an example of the Student table where the combination of Stud Name and Duration should be unique.
Try to Create below Student table:
1 2 3 4 5 6 7 |
CREATE TABLE tbl_Students ( StudID INTEGER ,StudName CHARACTER VARYING ,Duration TSRANGE ,EXCLUDE USING GIST (StudName WITH=, Duration WITH &&) ); |
1 2 |
ERROR: data type character varying has no default operator class for access method "gist" HINT: You must specify an operator class for the index or define a default operator class for the data |
1 |
CREATE EXTENSION btree_gist; |
1 2 3 4 5 6 |
INSERT INTO tbl_Students VALUES (1,'Anvesh','[2000-01-01, 2005-01-01)') ,(2,'Roy','[2001-01-01, 2006-01-01)') ,(3,'Eric','[2002-01-01, 2007-01-01)') ,(4,'Jenny','[2000-01-01, 2005-01-01)'); |
1 2 3 |
INSERT INTO tbl_Students VALUES (5,'Anvesh','[2000-01-01, 2005-01-01)'); |
1 |
ERROR: conflicting key value violates exclusion constraint "tbl_students_studname_duration_excl" |