DEV Community

WeenAIthDev
WeenAIthDev

Posted on

Understanding SQL query structure

This is basically SQL’s version of BODMAS/PEDMAS.

We write SQL one way…
but SQL executes it differently.

The golden rule:

F/JWGBHSOL/O
Enter fullscreen mode Exit fullscreen mode

Looks gibberish at first.
Actually very important.


How SQL Executes Queries

F/J → FROM / JOIN

Build the dataset.

  • FROM → grab the main table
  • JOIN → combine other tables

W → WHERE

First filter.

Removes rows that don’t match conditions.


GB → GROUP BY

Create groups from rows.

Turns row-level data into grouped data.


H → HAVING

Second filter.

But this time for groups, not rows.


S → SELECT

Pick the final columns/results to display.


O → ORDER BY

Sort the final output.


L/O → LIMIT / OFFSET

  • LIMIT → how many rows to show
  • OFFSET → how many rows to skip

Important Thing

We WRITE SQL like this:

SELECT  FROM  WHERE
Enter fullscreen mode Exit fullscreen mode

But SQL THINKS like this:

FROM  WHERE  GROUP BY  HAVING  SELECT  ORDER BY
Enter fullscreen mode Exit fullscreen mode

Understanding this makes SQL much less confusing.

Reference: SQL ORDER OF EXECUTION

Top comments (0)