Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres greater than or null

Tags:

sql

postgresql

I am trying to efficiently use an index for the greater than or null query.

Example of a query would be:

select * from table where date > '2020-01-01' or date is null

What index if any do I need that postgres will be able to do this efficiently. I tried doing an index with

create index date on table (date asc nulls last)

but it does not seem to work and the best I am able to get is two bitmaps scans (one for greater than and one for null).

like image 366
Blaž Šnuderl Avatar asked Feb 19 '21 11:02

Blaž Šnuderl


People also ask

What does <> mean in Postgres?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.

How do I check for null in PostgreSQL?

SELECT * FROM employees WHERE first_number IS NULL; This PostgreSQL IS NULL example will return all records from the employees table where the first_name contains a NULL value.

Is null or empty Postgres?

Oracle reads empty strings as NULLs, while PostgreSQL treats them as empty. Concatenating NULL values with non-NULL characters results in that character in Oracle, but NULL in PostgreSQL. Oracle and PostgreSQL behave similarly in many cases, but one way they differ is in their treatment of NULLs and empty strings.

IS NOT NULL operator in PostgreSQL?

Here is an example of how to use the PostgreSQL IS NOT NULL condition in a SELECT statement: SELECT * FROM employees WHERE first_name IS NOT NULL; This PostgreSQL IS NOT NULL example will return all records from the employees table where the first_name does not contain a null value.


2 Answers

If you are able to rewrite your condition, you could replace the null value with a date that is guaranteed to be greater than the comparison value:

where coalesce(date, 'infinity') > date '2020-01-01'

Then create an index on that expression:

create index on the_table ( (coalesce(date, 'infinity')) )

See also PostgreSQL docs:

  • Date/Time Types, 8.5.1.4. Special Values for infinity value
  • Conditional Expressions, 9.18.2. COALESCE for coalesce function
like image 166
a_horse_with_no_name Avatar answered Oct 16 '22 18:10

a_horse_with_no_name


Does Postgres use the index correctly when you use union all?

select *
from table
where date > '2020-01-01' 
union all
select *
from table
where date is null;

The issue might be the inequality combined with the NULL comparison. If this is some sort of "end date", then you might consider using some far out future value such as 9999-01-01 or infinity.

like image 2
Gordon Linoff Avatar answered Oct 16 '22 17:10

Gordon Linoff