SQL performance tuning
Handling data is a big part of every application, and doing it in the wrong way can be costly. In this article, I’ll give you some tips that I learned along the way, that can make your applications quicker.
Besides that, and probably more importantly, I’ll show you how you can set up a small database in your local machine where you can practice and improve your SQL skills.
Northwind
To showcase some of these tips, we are going to need a database. Northwind is a simple database often used by people who want to learn SQL and that’s what we are going to use.
The dataset consists of 13 tables that can be seen below:
Later in this article, I’ll show how you can install this database on your local machine, using SQL Management Studio, to play around with it yourself.
SQL Query Stress
To figure out what’s the best way to perform a certain query, first we need to find a way to compare metrics for different SQL statements.
There are a lot of tools that can be used, but in this article I’ll use the tool SQL Query Stress.
The image above shows the SQL Query Stress tool, that can be used to set up tests for a given statement.
Parameters like “Number of iterations”, “Number of threads”, etc. can be adjusted to run the tests.
As a performance indicator, the parameter Client Seconds/Iteration (avg) which “displays the average runtime over all iterations, as recorded on the client” will be the metric to compare the different scenarios.
Every statement has the “OPTION (RECOMPILE)” keyword to make sure the execution plan is rebuilt on every iteration.
Tips
1. Fetch only the attributes needed
This one is kind of obvious but still worth mentioning.
When you are fetching data from the database, make sure to return only the attributes that are needed. Most of the time, it’s not necessary to return every field from a table.
As we can see, there’s a huge difference between the two approaches, and the difference will be even bigger for tables with more attributes and with more records.
2. Fetch only the records needed
Also kind of obvious, but also worth mentioning, is that you should only return the records needed.
For instance, let’s pretend we want to check if an Order was already made in France. For this we need to fetch Orders where the Country is France, but it’s not needed to return every order.
To achieve this, we only need to check if there is at least one record that meets these criteria, so we can use the TOP(1) keyword.
Here there’s also a big difference between the 2 options.
In the first option, the query will find every record where the ShipCountry is ‘France’, but in the second option, the query will stop when it finds the first record that meets those criteria.
So, again, the difference will increase with the number of records in the table.
3. Take advantage of the NOT EXISTS
When there’s a need to return records from a table that do not have a match in some other table, there are two ways to go: join the tables and check if the Id is null or use the NOT EXISTS.
In this example, we will get the customers without any order using these two options.
Again, a huge difference between the 2 options.
The first option will join every Customer with the Orders, and then filter out the records where the OrderId is not null.
The second option will fetch every customer and then checks if there is a match with the Orders table.
The EXISTS operator is used to test for the existence of any record in a subquery. It returns true if there’s at least one record, and false if there isn’t.
We can see that in the execution plan, the first query needs to read all the rows in the Orders table. However, that’s not the case in the second query, with only 91 reads.
For more info, the SQL Server Management Studio has the “Include Actual Execution Plan” option that can be turned on.
There you can see the execution plan as details for every operation.
Later in this article you can find a detailed section explaining what is the execution plan and how can you see it in SQL Server Management Studio.
4. Avoid using DISTINCT
The DISTINCT keyword is used in SQL to remove duplicate rows in a SQL statement. However, better than removing duplicated records is not having them in the first place.
By using the DISTINCT, the database is comparing all rows and removing the duplicated ones. So, it means that you are wasting memory and CPU usage not only by fetching data that you don’t need, but also by finding out which rows are duplicated and then removing them.
Usually, when a SQL statement has a DISTINCT, it is because there’s an incorrect join fetching more data than needed, or a filter that’s not correct.
Get Pedro Marques’s stories in your inbox
Join Medium for free to get updates from this writer.
So, when we want to get all customers that already made an order. We can do this by joining the Customer and the Order tables, but this means that we will get a record for each order that the Customer has created, which is not really what we need.
To avoid this, we can use the EXISTS keyword again. This way, we will only fetch the Customers and then filter out the ones without and order.
Comparing the execution plan here is also interesting, as we can clearly see that in the first option, 106240 rows are scanned which is the number of Orders in the database. So, as this number increases, so will increase the amount of time to perform this query.
5. Know when to index
Indexes are used to find rows with a certain value in a faster way. Without an index, the SQL Server needs to read the first row and then go through the entire table to find the relevant rows. If the table has an index for the columns in question, the SQL Server can quickly determine the position to seek to in the middle of the data file without having to look at all the data, just like a dictionary.
To test how indexes affect the performance of a query, this time we’ll run the same query, but the first time without an index in the column filtered.
As we can see there’s a huge difference between the 2 options. The use of the index makes the second option a lot faster.
However, not everything is sunshine and rainbows. When an index is added to the table, the CRUD actions always take more time, so there is always a trade-off in speed between the GET and CRUD operations.
As a rule of thumb, fields that are consistently joined or filtered should be indexed.
You can find more information about indexes here.
6. Use wildcards wisely
While building our applications, we often need to filter records based on a user input. To do this filter we can use the wildcard (%) to look for records that have the input string in a specific position and we can also search without the wildcard, to look for a field that is exactly the same as the input string.
In this test we will analyze how the use of the wildcard affects the performance of a query in an indexed and in a non-indexed field.
For each case, it will be compared a statement without wildcard, with a wildcard in the beginning of the string, a wildcard at the end of the string, and wildcards at the beginning and end of the string.
a) Non-indexed field
b) Indexed field
With these results we can conclude that:
a. The fastest options are 1 (without wildcard) and 3 (wildcard at the end), with a small difference between them.
b. Using the wildcard in the beginning of the string impacts severely the performance.
c. The index has no impact when there is only a wildcard in the beginning (option 2).
So, before adding a wildcard to the beginning of the search input make sure you really need it!
Execution Plan
To be able to execute queries, the Database Engine must analyze the statement to determine the most efficient way to access the required data.
The output of the Query Optimizer is a query execution plan.
A query execution plan is:
- The sequence in which the source tables are accessed.
- The methods used to extract data from each table.
- The methods used to compute calculations, and how to filter, aggregate, and sort data from each table.
SQL Server Management Studio has three options to display execution plans:
- The Estimated Execution Plan is the compiled plan, as produced by the Query Optimizer based on estimations. This is the query plan that is stored in the plan cache.
- The Actual Execution Plan is the compiled plan plus its execution context. It becomes available after the query execution has been completed. This includes actual runtime information such as execution warnings, or in newer versions of the Database Engine, the elapsed and CPU time used during execution.
- The Live Query Statistics is the compiled plan plus its execution context. It is available for in-flight query executions, and updated every second. This includes runtime information such as the actual number of rows flowing through the operators, elapsed time, and the estimated query progress.
This is a very useful tool to find out what are the most costly operations of your query and what you can do to improve them.
Set up the database
To do these tests I created a database in my local machine and installed the Northwind database.
If you’re interested in doing the same you just need to follow the steps of this YouTube video and just like that, there is a database running in your local machine.
After that, connect to the database created. The Server Name should be: “(localdb)\{name}”.
Then, you can create a database by right clicking Databases -> New Database.
A pop up should open where you can specify the name of the database. I’ll choose the name “Northwind”.
For the final step, just click “New Query”, copy the text of the file “instnwnd (Azure SQL Database).sql” in the GitHub repository and click “Execute”.
Make sure that the Database selected is the one you created. “Northwind” in my case.
And voilà… you have the Northwind database installed.
Final Notes
Keep in mind that the results will vary for different databases and for different subsets of data.
The goal of this article is not only to give you a list of dos and don’ts, but to show you how you can set up a small database to improve your SQL skills and how you can test and analyze the performance of different SQL statements.
Any questions or comments? Please feel free to reach out to me!










