Execution Order of SQL Queries

In today’s post, I’ll explain the order in which the database engine performs operations. It’s not entirely obvious and doesn’t result from the syntax. Let’s imagine that we first write SELECT to choose columns. Then, we define which table we are retrieving data from by entering the FROM clause. Next, we start filtering using the WHERE clause. If we use aggregate functions, let’s not forget about GROUP BY, and if we want to sort our results, we add ORDER BY.

I’ve just described a fairly typical query. Now, we’ve set everything in the right order, but the question remains: in what order will the database read it? The database processes the query in a slightly different order. Just remember this once, as the order is always the same.

  1. FROM, JOIN – first, the server locates the data from which it will start retrieving.
  2. WHERE – the server filters the data, eliminating unnecessary parts.
  3. GROUP BY – then, it groups them.
  4. HAVING – groups are subsequently filtered.
  5. SELECT – at this step, the server selects the data we specified and calculates aggregate functions.
  6. ORDER BY – values are sorted.
  7. TOP – the final step is selecting the appropriate number of values.

Of course, keep in mind that not all expressions always appear in our query. Knowing the above order can help us better prepare for optimizing our queries.

Interesting article? Share further!

Leave A Comment