0

What is the best way to create an index as well as unique constraint on a schema like below?

Most of my queries will filter based on date column. If I create single column index on date and a unique constraint including both (date and key), I end up creating two indices as unique constraint also creates an index.

Is there a better way around this?

date key value
12-12-2021 a 3
12-12-2021 b 4
12-13-2021 a 3
12-13-2021 b 4
1
  • 1
    by creating a primary key on (date,key) will get you an index as well as uniqueness enforced. Queries thta use just date field filter would most likely be using a range scan, as its on the leading edge(first_column) of the index Commented Jan 1, 2022 at 3:57

1 Answer 1

1

It depends.

Most of my queries will filter based on date column.

That's not enough information. For equality filters, a PRIMARY KEY on (date, key) (with date as leading column!) will typically do just fine:

CREATE TABLE tbl (
  date  date
, key   text
, value int
, PRIMARY KEY (date, key)
);

Because ... see:

This also covers range filters on date, but it's less than ideal when combined with an equality filter on key, because ... see:

If your table is as simple as your example suggests and you typically include value in the SELECT list, consider a covering index (requires Postgres 11 or later) to get index-only scans:

...
, PRIMARY KEY (date, key) INCLUDE (value)

See:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.