How SQL Query works? SQL Query Execution Order for Tech Interview
Tags: sql, database, programming, development
Published: 2024-06-27 07:25:09

---
title: How SQL Query works? SQL Query Execution Order for Tech Interview
published: true
description: How SQL Query works? Understanding SQL Query Execution Order for Tech Interview
tags: sql,database, programming, development
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-06-25 06:32 +0000
---
*Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.*

![SQL query execution order](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fpaoxdz4bi2mys9q9bhd.png)


Hello guys, one of the common question on technical interviews about SQL is *how exactly SQL query work?* While this may seems simple, many programmers including experienced one fail to answer this with confidence. 

Many developer don't even know how the SQL commands are executed and in which order?

For them the SQL query is executed as they are written but that's not true, you can see from the above diagram that FROM and JOIN is executed before you can SELECT anything, which is again very rational if you think through.

Earlier, I have shared [**20 SQL queries from interviews**](https://medium.com/javarevisited/20-sql-queries-for-programming-interviews-a7b5a7ea8144) and [50 System design questions](https://dev.to/somadevtoo/top-50-system-design-interview-questions-for-2024-5dbk) and in this article, I am going to answer how exactly SQL query works under the hood, so stay tuned and continue reading.

And, if are preparing for tech interviews and you need more questions not just queries but also database and SQL related questions from other topics like indexes, joins, group by, aggregation, and window functions then you can also checkout these [**200+ SQL Interview Questions**](https://click.linksynergy.com/deeplink?id=CuIbQrBnhiw&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fsql-interview-questions%2F) .

This course is one of the specially designed course to prepare you for SQL interviews by answering popular questions. You can also get this for big discount now.


## How exactly SQL Query is executed?
Structured Query Language or SQL is the standard language for managing and manipulating relational databases. 

It provides a powerful and efficient way to interact with data, enabling developers, analysts, and data scientists to retrieve, insert, update, and delete information from databases.

While SQL queries are written in a declarative, human-readable format, there is a complex process that occurs behind the scenes to execute these queries and retrieve the desired results. 

In this article, we'll delve into the inner workings of SQL queries, breaking down the process step by step.

## 1\. Query Parsing and Tokenization
The journey of an SQL query begins with parsing and tokenization. When a user submits an SQL query, the database management system (DBMS) must first break down the query into individual tokens.

Tokens are the smallest units of the query and can include keywords ([SELECT](https://www.sqlrevisited.com/2023/09/2-10-ways-to-use-select-command-in-sql.html), FROM, [WHERE](https://www.sqlrevisited.com/2022/02/how-to-filter-data-in-sql-where-clause.html), etc.), table and column names, operators (=, >, <, etc.), and values. 

This process involves identifying the syntax and structure of the query to ensure it follows the rules of the SQL language.

![how SQL query are executed](https://miro.medium.com/v2/resize:fit:531/1*rDUNHtKwjghI-81ola7muw.jpeg)

------

## 2\. Query Optimization
Once the query is parsed and tokenized, the DBMS performs query optimization. This is a crucial step that aims to improve the efficiency of query execution.

The DBMS analyzes the query and explores various execution plans to determine the most efficient way to retrieve the requested data. 

It considers factors such as [indexes](https://javarevisited.blogspot.com/2022/12/12-database-sql-index-interview.html), table relationships, and available resources to create an execution plan that minimizes the time and resources needed to complete the query.

![how to do query optimization](https://miro.medium.com/v2/resize:fit:600/1*TQAtoOrrbmJwU5XH_t5nkw.jpeg)

----


### 3\. Execution Plan Generation
The chosen execution plan outlines the sequence of steps required to fulfill the query. 

It determines the order in which tables are accessed, the types of joins performed, and the filtering conditions applied.

The DBMS generates this plan based on statistical information about the data distribution and the database schema. 

The goal is to reduce the amount of data that needs to be processed and to optimize disk and memory usage.

On Microsoft SQL Server, a Query Execution plan looks like below:

![how Execution plan looks like](https://miro.medium.com/v2/resize:fit:700/1*uerMGYuzbDeC-nBq2noxtQ.png)

-------


### 4\. Data Retrieval and Joins
With the execution plan in place, the DBMS begins the process of data retrieval. If the query involves multiple tables, the DBMS performs join operations to combine the relevant data.

Joining tables efficiently requires comparing and matching rows based on specified conditions. Depending on the type of join ([inner join,](https://www.sqlrevisited.com/2022/02/how-to-use-left-right-inner-outer-full.html) [outer join](https://javarevisited.blogspot.com/2013/05/difference-between-left-and-right-outer-join-sql-mysql.html), etc.), the DBMS determines which rows from each table should be included in the result set.

[![How SQL join works](https://miro.medium.com/v2/resize:fit:700/1*l41t2NsS9lcKrPA5LMuUKA.jpeg)](https://javarevisited.blogspot.com/2020/05/self-join-example-sql-query-to-find-employee-more-than-managers-leetcode-solution.html)

-------


### 5\. Filtering and Sorting
After joining the necessary tables, the DBMS applies filtering conditions specified in the [WHERE clause](https://www.java67.com/2019/06/difference-between-where-and-having-in-sql.html). This involves evaluating each row to determine whether it meets the criteria set by the user.

Rows that do not satisfy the conditions are discarded, while those that pass the filter are retained for further processing.

Additionally, if the query includes an ORDER BY clause, the DBMS will sort the resulting rows based on the specified column(s). 

Sorting involves arranging the data in a specific order, such as ascending or descending, to produce the final ordered result set.

![When does filtering and sorting happens in SQL Query Execution](https://miro.medium.com/v2/resize:fit:600/1*13RTB003k26LCWdPMe2NcQ.png)

------


### 6\. Aggregation and Grouping
Aggregation functions such as [SUM](https://javarevisited.blogspot.com/2020/06/5-example-of-group-by-clause-in-sql.html#axzz6qnblZnVj), [COUNT](https://www.sqlrevisited.com/2023/09/10-ways-to-use-group-by-command-in-sql.html), AVG, MIN, and [MAX](https://www.java67.com/2013/04/10-frequently-asked-sql-query-interview-questions-answers-database.html) are commonly used in SQL queries to perform calculations on groups of data.

If the query includes a [GROUP BY clause](https://javarevisited.blogspot.com/2020/04/sql-group-by-and-having-example-write.html), the DBMS groups the rows based on the specified columns. It then applies the aggregation functions to each group separately, producing summary statistics or calculations for the grouped data.

![Aggregation and Grouping in sQL query](https://miro.medium.com/v2/resize:fit:700/1*rML0lZVnkkcSpkHyQ7-2Qw.png)

-------


### 7\. Result Set Generation
With all the necessary operations performed, the DBMS generates the final result set. This set of rows and columns represents the data that satisfies the user's query. T

he result set is then returned to the user or the application that initiated the query.

![when is result generated from SQL query](https://miro.medium.com/v2/resize:fit:700/1*Jh8sOlxM2fzndQAcHWypdQ.png)

------

### 8\. Index Utilization
Indexes play a vital role in optimizing the performance of SQL queries. An index is a data structure that provides a quick way to look up data based on specific columns.

When executing a query, the DBMS may utilize indexes to efficiently locate the relevant rows, reducing the need for full-table scans and improving query response times.

![Index Utilization in SQL query](https://miro.medium.com/v2/resize:fit:700/1*Vo4TralS4d0EOIhZjEM_2g.png)

-------


### 9\. Transaction Management
Transactional operations in SQL, such as INSERT, UPDATE, and DELETE, involve modifying data in the database. These operations are grouped into transactions, which ensure data consistency and integrity.

When a transaction is initiated, the DBMS may lock the affected rows or tables to prevent other transactions from accessing or modifying them concurrently.

Once the transaction is completed, the changes are either committed to the database or rolled back, depending on the success or failure of the transaction.

![Transaction Management in SQL ](https://miro.medium.com/v2/resize:fit:700/1*cxkAhlruxDl2DGU_NppEbQ.png)

-----


### 10\. Caching and Memory Management
Modern database systems employ various caching and memory management techniques to optimize query performance. 

Caching involves storing frequently accessed data in memory to reduce the need for disk reads, which are slower in comparison.

The DBMS may also use buffer pools to manage memory allocation for query execution and result set generation, further enhancing efficiency.

![Caching and Memory Management in SQL](https://miro.medium.com/v2/resize:fit:372/1*vkAEomGIqoUKZk9eaunY0Q.png)

------


## SQL Query Order? How SQL Query are executed under the hood?
It's also important to know and remember in which order various SQL commands like SELECT, FROM, COUNT, WHERE, HAVING, ORDER BY, JOIN etc are applied

SQL queries are processed in a specific order, and understanding this order is crucial for writing and optimizing queries effectively. The typical order of SQL query processing involves the following steps:

1.  **FROM:** The query begins by specifying the source tables or views from which the data will be retrieved. This clause defines the primary data source for the query.

2.  **JOIN:** If the query involves multiple tables, the JOIN clause is used to combine data from different tables based on specified conditions. Different types of joins (INNER JOIN, LEFT JOIN, RIGHT JOIN, etc.) determine how rows from each table are matched and included in the result set.

3.  **WHERE:** The WHERE clause is used to filter rows based on specific conditions. It restricts the data to only those rows that meet the specified criteria. Rows that do not satisfy the conditions are excluded from further processing.

4.  **GROUP BY:** If aggregation is required, the GROUP BY clause is used to group rows with similar values in specified columns. This step is often used in conjunction with aggregation functions like COUNT, SUM, AVG, etc. to perform calculations on grouped data.

5.  **HAVING:** The HAVING clause is used to filter the result set after the GROUP BY operation has been performed. It specifies conditions for filtering aggregated data. Similar to the WHERE clause, rows that do not meet the criteria are excluded from the final result.

6.  **SELECT:** The SELECT clause is used to specify the columns that should appear in the final result set. It determines which data will be retrieved and displayed in the query output.

7.  **DISTINCT:** The DISTINCT keyword, if used, removes duplicate rows from the result set, ensuring that only unique values are displayed.

8.  **ORDER BY:** The ORDER BY clause is used to sort the result set based on specified columns. It arranges the rows in ascending or descending order, as specified.

9.  **LIMIT/OFFSET or FETCH/FIRST:** Depending on the database system, you might use LIMIT (or FETCH or FIRST) and OFFSET clauses to control the number of rows returned and to implement pagination.

10. **UNION/INTERSECT/EXCEPT:** If needed, these set operations can be used to combine the results of multiple queries.

Here is a nice diagram from Medium which clearly explains how the SQL query looks like and how its executed by Query engine:

![SQL Query execution order](https://miro.medium.com/v2/resize:fit:700/1*xuiIosnz4WZc-sh7nftuYg.jpeg)

It's important to note that the actual order of execution may vary based on the specific database management system being used.** However, the logical processing order remains consistent across most SQL databases.

Additionally, modern query optimizer may rearrange some of these steps for performance reasons while ensuring that the final result remains accurate and consistent.

Understanding the order of SQL query processing not only help in technical interviews but also allows you to write efficient and effective queries, and it provides insights into query optimization and performance tuning. 

By structuring your queries with this order in mind, you can better control the flow of data and achieve the desired results.

### Conclusion
That's all about how SQL query are executed under the hood. SQL queries might seem like simple statements, but there is a complex process that unfolds behind the scenes to retrieve, manipulate, and manage data.

From parsing and optimization to execution plan generation and result set generation, every step is meticulously orchestrated to ensure efficient and accurate query processing.

Understanding **how SQL queries work under the hood** provides developers and database administrators with valuable insights into performance optimization and query tuning, ultimately leading to better utilization of database resources and improved application responsiveness.

And, if are preparing for tech interviews and you need more questions not just queries but also database and SQL related questions from other topics like indexes, joins, group by, aggregation, and window functions then you can also read [**Grokking the SQL Interview book**](https://javinpaul.gumroad.com/l/grokking-the-sql-interview) or join [**200+ SQL Interview Questions**](https://click.linksynergy.com/deeplink?id=CuIbQrBnhiw&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fsql-interview-questions%2F) .

Both are great resources to prepare you for SQL interviews by answering popular questions.

All the best !!