SQL SELECT Statement Execution Sequence Notes

Jul 26, 2024

Notes on SQL Select Statement Execution Sequence

Overview

  • Focus on the execution sequence of the SELECT statement in SQL.
  • Example involves retrieving department names and maximum salaries for departments with specific criteria.

Query Requirements

  • Display: Department name and maximum salary.
  • Conditions: Average salary for the department must be > 1200.
  • Sorting: Results should be sorted by department name.

Data Sources

  • Tables Involved: Employee and Departments.
  • Join Condition: Employee department number must match Departments department number.

SQL Clauses Used

  1. SELECT

    • Specify the columns to return (e.g., department name, maximum salary as 'Max').
  2. FROM

    • Identify source tables: Employee and Departments.
    • A JOIN condition is necessary for multiple tables.
  3. GROUP BY

    • Aggregate data, grouping by department name.
    • It divides data into groups based on department.
  4. HAVING

    • Set a condition to filter groups, where the average salary > 1200.
  5. ORDER BY

    • Sort results by department name (Dname).

Execution Sequence

  1. FROM Clause

    • DBMS retrieves data from the specified tables first.
    • Combines data into a temporary larger table based on JOIN conditions.
  2. WHERE Clause

    • Applies filters to the temporary table to exclude records that don't meet the conditions.
    • Only records that meet the conditions are retained.
  3. GROUP BY Clause

    • Groups remaining records according to department name (Dname).
    • DBMS can only access and manipulate data within these groups going forward.
  4. Aggregates Calculation

    • Calculate aggregate functions (e.g., MAX, AVG) for each group.
    • Each group retains references to its maximum and average values.
  5. HAVING Clause

    • Evaluates the condition for averages, removing groups that do not meet the criteria (> 1200).
  6. SELECT Clause

    • Confirms which data to return based on available data in the groups.
    • Returns department name and calculated maximum salary.
  7. ORDER BY Clause

    • Sorts the resulting dataset ascendingly by department name (Dname).
    • Ensures that the required data is accessible for sorting.

Important Notes

  • Data displayed must be available in the group created by GROUP BY.
  • Items in ORDER BY must also be present in the groups.
  • Additional filters can be added in the WHERE clause, alongside JOIN conditions.

Example of Result Set

  • Display result includes department names and maximum salaries which meet the specified conditions, sorted alphabetically.

  • Final Warning: Ensure any data you wish to display or sort by is accounted for in the GROUP BY clause when using aggregation operations.