The order of execution of SQL clauses

When a SQL query is run, it doesn’t execute in the order it’s written. Here’s the correct order of execution:

  1. FROM and JOINs: The FROM clause, along with JOINs, sets the base datatable(s) and any joining of tables occurs at this stage.
  2. WHERE: Once we have the base data table, the WHERE clause filters this data based on the condition specified.
  3. GROUP BY: After the WHERE clause has filtered the data, GROUP BY will aggregate the data into groups as specified.
  4. HAVING: If the HAVING clause is present, it will filter the data after it has been grouped (this is the key difference between WHERE and HAVING - WHERE filters before grouping, HAVING filters after grouping).
  5. SELECT: The SELECT clause is executed next. It determines which columns of the filtered, grouped data will be in the final result set. It’s also where we specify any aggregate functions to be used.
  6. DISTINCT: If specified, DISTINCT will remove any duplicate rows from the result set specified by the SELECT clause.
  7. ORDER BY: Finally, the ORDER BY clause sorts the data based on the columns specified.

Here’s a visual representation:

1. FROM clause
2. WHERE clause
3. GROUP BY clause
4. HAVING clause
5. SELECT clause
6. DISTINCT clause
7. ORDER BY clause

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form