Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Order of a SQL Query #161

Open
luantranminh opened this issue May 1, 2023 · 0 comments
Open

Order of a SQL Query #161

luantranminh opened this issue May 1, 2023 · 0 comments
Labels

Comments

@luantranminh
Copy link
Owner

https://dataschool.com/sql-optimization/order-of-a-sql-query/

Let’s take a look at a sample SQL query :

SELECT DISTINCT column, AGGREGATE(column)
FROM table1
JOIN table2
ON table1.column = table2.column
WHERE constraint_expression
GROUP BY column
HAVING constraint_expression
ORDER BY column ASC/DESC
LIMIT count;

Each part of the query is executed sequentially, so it’s important to understand the order of execution :

  1. FROM and JOIN: The FROM clause, and subsequent JOINs are first executed to determine the total working set of data that is being queried
  2. WHERE: Once we have the total working set of data, the WHERE constraints are applied to the individual rows, and rows that do not satisfy the constraint are discarded.
  3. GROUP BY: The remaining rows after the WHERE constraints are applied are then grouped based on common values in the column specified in the GROUP BY clause.
  4. HAVING: If the query has a GROUP BY clause, then the constraints in the HAVING clause are applied to the grouped rows, and the grouped rows that don’t satisfy the constraint are discarded.
  5. SELECT: Any expressions in the SELECT part of the query are finally computed.
  6. DISTINCT: Of the remaining rows, rows with duplicate values in the column marked as DISTINCT will be discarded.
  7. ORDER BY: If an order is specified by the ORDER BY clause, the rows are then sorted by the specified data in either ascending or descending order.
  8. LIMIT: Finally, the rows that fall outside the range specified by the LIMIT are discarded, leaving the final set of rows to be returned from the query.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant