COALESCE in Postgres is a function that returns the first parameter not null. So I used coalesce in subqueries like:
SELECT COALESCE ( ( SELECT * FROM users WHERE... ORDER BY ...), ( SELECT * FROM users WHERE... ORDER BY ...), ( SELECT * FROM users WHERE... ORDER BY ...), ( SELECT * FROM users WHERE... ORDER BY ...) ); I change the where in any query and they contain lots of params and CASE, also different ORDER BY clauses. This is because I always want to return something but giving priorities.
What I noticed while issuing EXPLAIN ANALYZE is that any query is executed despite the first one actually returns NOT a null value. I would expect the engine to run only the first one query and not the following ones if it returns not null.
This way I could have a bad performance.
So am I doing any bad practice and is it better to run the queries separately for performance reason?
EDIT:
Sorry you where right I don’t select * but I select only one column. I didn’t post my code because I am not interested in my query but it’s a generic question to understand how the engine is working. So I reproduce a very simple fiddle here http://sqlfiddle.com/#!17/a8aa7/4
I may be wrong but I think it behaves as I was telling: it runs all the subqueries despite the first one already returns a not null value
EDIT 2: ok I read only now it says never executed. So the other two queries aren’t getting executed. What confused me was the fact they were included in the query plan.
Anyways it’s still important for my question. Is it better to run all the queries separately for performance reasons? Because it seems like that even if the first one returns a not null value the other two subqueries can slow down the performance
COALESCEis best used like thiscoalesce(new_salary, old_salary, 5000), which means, if the new_salary is null, use old_salary. If old_salary is null, use 5000.coalesce()with aselect *.coalesce()works on single values, not on all columns of a table. You might get better answers if you take a step back and explain the underlying problem you are trying to solve. Please edit your question (by clicking on the edit link below it) and add some sample data and the expected output based on that data as formatted text. See here for some tips on how to create nice looking text tables.