SQL queries generally follow a specific order of clauses that define what data you want, where it comes from, and how it should be grouped, filtered, or sorted.
1. FROM – Specify the Table(s)
This tells SQL which table(s) to get data from.
SELECT name FROM employees;
2. WHERE – Filter Rows
This clause filters rows before any grouping or aggregation happens.
SELECT name FROM employees
WHERE department = 'Sales';
3. GROUP BY – Group Rows
Used to group rows with the same values in one or more columns, often for aggregation.
SELECT department, COUNT(*) FROM employees
GROUP BY department;
4. HAVING – Filter Groups
Filters the results after grouping (used with aggregate functions like SUM, AVG, COUNT, etc.).
SELECT department, COUNT(*) FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
5. SELECT – Choose Columns
Specifies which columns or expressions to return in the result set.
SELECT name, salary FROM employees;
6. ORDER BY – Sort the Results
Used to sort the final results, in ascending (ASC) or descending (DESC) order.
SELECT name, salary FROM employees
ORDER BY salary DESC;