SQL - 6 main clauses in SQL.

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;
  • employees is the table being queried.

 2. WHERE – Filter Rows

This clause filters rows before any grouping or aggregation happens.

SELECT name FROM employees
WHERE department = 'Sales';
  • Only rows where department = 'Sales' are selected.

 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;
  • Groups employees by department and counts how many are in each.

 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;
  • Only shows departments with more than 5 employees.

 5. SELECT – Choose Columns

Specifies which columns or expressions to return in the result set.

SELECT name, salary FROM employees;
  • You choose to return only name and salary.

 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;
  • Lists employees in highest to lowest salary order.