Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order of operations [duplicate]

If I run the following SQL query

SELECT * 
FROM A
LEFT JOIN B
ON A.foo=B.foo
WHERE A.date = "Yesterday"

Does the WHERE statement get evaluated before or after the JOIN?

If after, what would be a better way to write this statement so that returns only rows in A from "Yesterday" are joined to B?

like image 852
tinkertime Avatar asked May 18 '09 21:05

tinkertime


People also ask

What is the correct order of operations in SQL?

Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.

Does order of operations matter in SQL?

The order of execution can significantly affect the resulting value. Operators have the precedence levels shown in the following table.

How do you double order in SQL?

After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.

How do you prevent duplicates in SQL query?

The go to solution for removing duplicate rows from your result sets is to include the distinct keyword in your select statement. It tells the query engine to remove duplicates to produce a result set in which every row is unique.


2 Answers

It depends on the database.

On SQL Server, run: SET SHOWPLAN_ALL ON then run the query, you will get an idea of what happens when it runs.

like image 70
KM. Avatar answered Oct 12 '22 11:10

KM.


Your idea of "evaluation" is not correct as SQL is a declarative language.

BTW you can see the query execution plan. In MySQL prefix your query with keyword describe to see the execution plan.

like image 23
Tahir Akhtar Avatar answered Oct 12 '22 12:10

Tahir Akhtar