Skip to main content
Uncategorized

How to write cleaner SQL queries

By januari 19, 2024maart 19th, 2024No Comments

In the world of database management, crafting efficient and readable SQL queries is an essential skill for developers and data professionals alike. Writing clean and optimized SQL queries enhances your applications’ performance and makes it easier for others to understand and maintain your code. In this post, we’ll be discussing a couple of tips that should help you write cleaner SQL queries.

Picture from AT-Automation

Better utilizing upper- and lowercase

When writing your queries, capitalizing keywords and functions is often a forgotten aspect. Since it doesn’t influence the working of the query. However, it can greatly improve the readability of your query for yourself or someone else. Using proper lowercase or underscores for naming schemas, tables or columns also aids in this aspect. For example, which one of these is easier to read:

Select CUSTOMERID
from Customers
WHERE age > 25;
SELECT customer_id
FROM customers
WHERE age > 25;

Take only what you need

Steer clear of the temptation to use SELECT * in your queries. While it might seem convenient, it can fetch more data than you actually need, slowing down your query and affecting performance. Be explicit about the columns you want by listing them individually. This not only boosts query speed but also adds a layer of clarity to your code, making it easier to maintain in the long run. So, resist the urge for the wildcard, and handpick the columns you truly require!

Using proper aliases

Using aliases is especially helpful when writing longer queries that use joins. While writing, you might shorten a table or a column to its first letter. While dealing with shorter queries, this might not seem that bad. But when writing complex queries including multiple joins, things will get messy. Especially after not seeing the query in a long time and dealing with different tables and columns. So either refrain from using aliases and write the column and table out. Or shorten them properly like employees AS emp.

Illuminate your SQL queries

Adding comments to your SQL queries is like leaving breadcrumbs for yourself and others. In a few brief lines, explain the logic, conditions, or any nuances in your code. It’s a small effort that pays off when someone else (or even future you) tries to unravel the intricacies of your database wizardry.

Auteur

Leave a Reply