SQL Execution Order (Logical Order):
- FROM:
- This clause specifies the tables (or other data sources) from which to retrieve data. It happens first because it determines which rows are available to the rest of the query.
- JOIN:
- If you're using
JOIN, it’s performed immediately afterFROM. The join operation combines data from multiple tables based on a condition.
- If you're using
- WHERE:
- Filters the rows returned by the
FROMandJOINclauses based on a condition. The rows are selected after the join operations.
- Filters the rows returned by the
- GROUP BY:
- Groups the rows based on the columns you specify. After filtering (
WHERE), SQL groups the data based on specified columns.
- Groups the rows based on the columns you specify. After filtering (
- HAVING:
- Similar to
WHERE, but it is used to filter groups created byGROUP BY. You would useHAVINGto filter out groups based on aggregated results, such asSUM,COUNT, etc.
- Similar to
- SELECT:
- Selects the columns to be displayed in the final output. The
SELECTclause is executed afterFROM,JOIN,WHERE, andGROUP BY(andHAVINGif used), because it operates on the filtered and grouped data.
- Selects the columns to be displayed in the final output. The
- DISTINCT:
- If you’re using
DISTINCT, it happens immediately afterSELECTto remove duplicate rows from the result set.
- If you’re using
- ORDER BY:
- The data is sorted based on the columns specified in the
ORDER BYclause. Sorting occurs afterSELECTandDISTINCT(if used), and it organizes the rows in ascending or descending order.
- The data is sorted based on the columns specified in the
- LIMIT / OFFSET:
- These clauses are used to restrict the number of rows returned. They occur last, after all sorting and selection of rows are done.
Example:
Thank you
No comments:
Post a Comment