P
P
pqgg7nwkd42020-11-03 19:37:26
PostgreSQL
pqgg7nwkd4, 2020-11-03 19:37:26

Is a conditional index without columns possible and useful?

Let's say we have a table with unsent messages. The table is large, and there are few unsent messages among them.
Is something like this possible:
`CREATE INDEX messages0 ON messages WHERE NOT is_sent`
I assume that the database, when querying `SELECT * FROM messages WHERE NOT is_sent`, should see such an index and make a query from it.

If this syntax is invalid, would it be
`CREATE INDEX messages0 ON messages USING btree (is_sent) WHERE NOT is_sent`

Or how to do it efficiently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2020-11-05
@pqgg7nwkd4

Syntactically, an index cannot have 0 columns. At least something will have to be added to the index.
The planner may choose to use a partial index if its prefix is ​​good enough to filter the selection, even if the fields in the index itself are not needed at all for this query. That is, for an Equal request, any of the following will do:
SELECT * FROM messages WHERE NOT is_sent

CREATE INDEX messages0 ON messages USING btree (is_sent) WHERE NOT is_sent
CREATE INDEX messages0 ON messages USING btree ((true)) WHERE NOT is_sent
CREATE INDEX messages0 ON messages USING btree (id) WHERE NOT is_sent

S
Swartalf, 2020-11-03
@Swartalf

should help, see examples here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question