I have this table in Postgresql:
CREATE TABLE my_table
(
id bigint NOT NULL,
value bigint,
CONSTRAINT my_table_pkey PRIMARY KEY (id)
);
There are ~50000 rows in my_table.
The question is, why the query:
SELECT * FROM my_table WHERE id = COALESCE(null, id) and value = ?
is slower than this one:
SELECT * FROM my_table WHERE value = ?
Is there any solution, other than optimizing the query string in app-layer?
EDIT: Practically, the question is how to rewrite the query select * from my_table where id=coalesce(?, id) and value=?
to have worst case performance not less than that of select * from my_table where value=?
in Postgresql 9.0
id = COALESCE(null, id)
? The COALESCE will always returnid
becauseid
is defined asNOT NULL
andid = id
will always return true too. – Cornhuskingselect .... id=id ...
is also slow. Any idea why? – Cioffiselect * from my_table where id=coalesce(?, id) and value=?
, so while being fairly annoying, it not completely useless :) – Cioffi