SELECT statement:
1. FROM
- The source tables or joins between tables are identified.
- Any subqueries in the
FROMclause are executed first. - Temporary tables may be created to handle derived tables or subqueries.
2. WHERE
- Filters rows from the
FROMclause based on specified conditions. - This step excludes rows that do not meet the condition.
3. GROUP BY
- Groups rows into subsets based on column(s) specified.
- Aggregate functions (e.g.,
SUM,MAX,COUNT) operate on these groups.
4. HAVING
- Filters groups formed in the
GROUP BYclause based on specified conditions. - Similar to
WHERE, but operates on grouped data.
5. SELECT
- Projects columns or expressions to return the desired data.
- Includes computed columns and uses aggregate functions.
6. DISTINCT
- Eliminates duplicate rows in the result set, if specified.
7. ORDER BY
- Sorts the result set based on specified column(s) or expressions.
- Can be ascending (
ASC) or descending (DESC).
8. LIMIT / FETCH / TOP
- Restricts the number of rows returned to the client.
- Syntax depends on the database system (e.g.,
LIMITin MySQL,TOPin SQL Server).
Example Query Execution Breakdown
- FROM: Reads the
employeestable. - WHERE: Filters rows with
salary > 10000. - GROUP BY: Groups rows by the
departmentcolumn. - HAVING: Retains groups where
COUNT(*) > 10. - SELECT: Selects
departmentand the computedemployee_count. - ORDER BY: Sorts the result by
employee_countin descending order. - LIMIT: Returns the top 5 rows.