0

When I write PostgreSQL WHERE clause is the condition order have matter?

Imagine the table where ID column is indexed and the name is not.

Is these two queries will get same time to execute?

  1. SELECT * FROM users WHERE state = 0 AND id = 3;

  2. SELECT * FROM users WHERE id = 3 AND state = 0;

And despite on these simple queries. Does Postgres do same optimization for complex queries and when it does not?

Please provide prof links when answering.

Thank you.

3
  • the order does not matter - only grouping with parenthesis does. where clause should always be true or false - how can order chnage the result?.. (true AND true)=true, (true and flase)=false, there is no true1 AND true2 - they are interchangeble
    – Vao Tsun
    Nov 29, 2017 at 13:10
  • @VaoTsun: The result is not changed. The time to get this result have matter. In first case the index maybe is not used. Nov 29, 2017 at 13:18
  • optimyser decides itself (based on statistics) the order of evaluations - you can't hint him your order (at least not this easily)
    – Vao Tsun
    Nov 29, 2017 at 13:23

1 Answer 1

0

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-WHERE

where condition is any expression that evaluates to a result of type boolean. Any row that does not satisfy this condition will be eliminated from the output.

https://www.postgresql.org/docs/current/static/functions-logical.html

The operators AND and OR are commutative, that is, you can switch the left and right operand without affecting the result

regarding the "conditions evaluating control", there are some answers

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.