SQL Syntactical Execution Order
SQL Syntactical Execution Order
Syntactical and
Execution Order
02 codebasics.io
This article will guide you through these concepts using a simple analogy,
followed by a detailed technical explanation and practical examples.
Let's explore how SQL queries are written and executed in actual
database environments.
Logical Execution Order: This is the order in which the SQL engine
processes the query.
Example:
Consider the below table: Books
This dataset will be a bookstore inventory which lists various books, their
genres, prices, and sales data.
07 codebasics.io
SQL Query:
Let's formulate an SQL query to find the top 2 genres by their average price
where at least 100 units were sold in Kondapur, ensuring that the average
price is greater than $7.00 and ordering them by descending order.
Syntactical Order:
From Clause:
All entries from the Books table are considered.
09 codebasics.io
Where Clause:
Filters for 'Kondapur' and UnitsSold greater than 100.
Group By Clause:
Group by Genre.
Here we want to find top genres by their average price. Grouping is necessary
to calculate aggregate functions like AVG(Price) for each genre.
10 codebasics.io
Having Clause:
Filters groups where the average price is greater than $7.00:
Select Clause:
Selects Genre and the computed AVG(Price) (aliased as AveragePrice) for
the final output.
Order By Clause:
Orders the groups by AVG(Price) in descending order.
11 codebasics.io
Limit Clause:
Limits the result to the top 2 genres that meet the criteria.
E n a b l i n g C a r e e r s
SCAN TO JOIN
codebasics.io