top of page

SQL Best Practices for Writing Clean, Reliable Queries

  • Writer: Sarah
    Sarah
  • 4 days ago
  • 8 min read

Updated: 6 hours ago

Learn how to write SQL that’s easier to read, debug, and scale. This post covers clean formatting, effective naming, and consistent logic that helps you build queries other people (and your future self) can easily follow.


SQL Best Practices by Data With Sarah
Writing SQL that is clean and readable doesn't have to be difficult or take a lot of time. Following a few simple tips can make all the difference, and will become second nature to you.

Table of Contents:


Have you ever looked at someone else's SQL code and winced?


Same.


And I’ve definitely written my fair share of messy queries too.


But what is it that makes some SQL queries hard to read while others look so much clearer?


There are a few things, some of which you may already be doing without realizing it. Tutorials mention these tips here and there, but the cleanest and clearest queries (in my opinion) are the ones that follow a few stylistic rules.  It’s usually just little things, like how the query is written, named, spaced, and organized.


This is highly preferential, and none of this affects how your code runs. But once you start writing more complex queries, you’ll really start to appreciate well-structured SQL, and how much easier it becomes to follow and debug... and just nicer to look at.


What do these clean, aesthetically pleasing SQL queries have in common?


Many of these tips are adapted from Simon Holywell's SQL Style Guide. If you haven’t seen it before, the page is worth bookmarking.


I've been using SQL in my data analytics roles for a few years now, and I still take the extra few seconds to make my queries readable; not just for myself, but for my colleagues or anyone in the future who might need to tweak or troubleshoot it later. I've been on the other end of having to review people's queries, and I understand and appreciate readable SQL.


The goal is to make your queries clean, consistent, and easy for others to follow.


In this post, I’ve broken down some of Holywell's tips and explained them in simple terms, with examples you can use yourself.


So let's begin with some tips!


SQL Best Practices That Make Life Easier


  1. Use UPPERCASE for SQL Keywords


The main keywords like SELECT, FROM, and WHERE should be written in UPPERCASE. It helps them stand out from the rest of the code.


Here is an illustration:

Which one is easier to read?

SELECT customer_id, order_total
FROM orders
WHERE order_date >= '2024-01-01'

Or this one?


select customer_id, order_total from orders where order_date >= '2024-01-01'


  1. Use Lowercase for Table and Column Names


There are a few different naming styles used in programming languages, and it depends on what type of language you are using and what your organization uses:


  • snake_case → customer_name (recommended and most common style for SQL)

  • camelCase customerName

  • PascalCase → CustomerName

  • kebab-case → customer-name (not valid in SQL)


There is also an all-caps version version of snake case called "screaming snake case," but I have never seen this one in practice, at least not with SQL code. It also doesn't look very nice because it would blend in too much with the SQL keywords mentioned earlier.


Unless your company enforces a particular standard, stick with lowercase and use underscores to separate words (snake_case). It’s easier to read, avoids bugs, and works consistently across databases. This is the one I typically use in my queries, though I have seen PascalCase used quite frequently as well.


Avoid inconsistent naming styles like CamelCase or names with spaces. These can break queries or make your code harder to scan.


Why it matters: SQL is case-insensitive in some systems, but not all. Sticking to lowercase avoids confusion and keeps your code cleaner when collaborating.


  1. Don’t Quote Table and Column Names Unless You Have To


Quoting identifiers ("column" or [column]) can lead to compatibility issues. Avoid using quotes unless you're working with special characters or reserved keywords.


For example, SQL Server allows you to use [column] if your column name is Rank, for instance. So you would write the column as [Rank] to avoid any errors. But you can avoid that if you use better naming conventions.


Instead of this:

SELECT "Order"
FROM "Sales"

Write this:


SELECT order_status
FROM sales

  1. Avoid Reserved Words for Column or Table Names


Using words like select, order, or date can cause issues. In the cases where you have reserved keywords as column names, use aliases (explained in the next step). Pick something more specific like sales_date or order_status.


Instead of this:

SELECT date
FROM sales

Write this:

SELECT date AS sale_date
FROM sales

  1. Use Short, Clear Table Aliases


Aliasing is helpful when you have column names that are too long or aren't meaningful, and are regularly used with JOINs.


The rule of thumb when using aliases is to keep them short and relevant to the context.


Don’t use x or temp as your alias names, for example. Make sure your aliases are clear and useful.


Bad:

SELECT x.order_id, y.customer_name
FROM orders AS x
JOIN customers AS y
	ON x.customer_id = y.customer_id

Good:


SELECT o.order_id, c.customer_name
FROM orders AS o
JOIN customers AS c
	ON o.customer_id = c.customer_id

  1. Always Use "AS" with Column Aliases


This one isn't followed by everyone, but it should be. Especially when you use relational database management systems that color-code different keywords. When your queries are longer, it is much easier to point out joins when you can scan through the color-coded 'AS'.


For example:

SELECT customeridforthecompany AS cust_id

  1. Use Consistent Indentation and White Space


You can use spaces or indentations, it doesn't matter. Put each clause on a new line and indent selected columns to make them easier to scan.


Use white space strategically by adding line breaks between logical blocks, and don't cram everything together. Just like in writing, white space gives your code breathing room and you'll avoid having to squint to see the important parts.


Avoid long, horizontal scrolls that bury your logic.


Don't do this:

SELECT  customer_id,first_name,last_name FROM customers WHERE signup_date >= '2024-01-01'

Do this:

SELECT
	customer_id,
	first_name,
	last_name
FROM customers
WHERE signup_date >= '2024-01-01'

  1. Keep Lines Under 72 Characters


Related the point 7 above, long, run-on lines make code harder to read. Break them up if needed.


For example, if you have a long CASE or WHERE condition, separate them into separate lines instead of having one run-on line.


  1. Avoid SELECT *


This is a big one. Unless you know your table is small, it's best to select the columns you need. It’s better for performance and protects your query from breaking if there are changes in the table.


If you've ever accidently done a SELECT * on a large table and it runs more than a few seconds, that's a bad sign. So stick to specific columns when you can. You can also use LIMIT or TOP if needed to reduce the rows being called.


  1. Use WHERE for Filters, HAVING for Aggregates


This one confuses beginners, and you'll end up with query errors if you don't use them correctly.


Just remember that:

  • WHERE filters before aggregation.

  • HAVING filters after aggregation.


For example:


SELECT
	customer_name,
	COUNT(*) AS order_count
FROM orders
WHERE customer_name LIKE 'Earl%'
GROUP BY customer_name
HAVING COUNT(*) > 5

  1. Use EXISTS Instead of COUNT When Checking if Rows Exist


If you’re just checking if data exists, use EXISTS. It’s faster than counting. EXISTS may not be as intuitive to use, but it can help with performance.


Instead of this:

SELECT COUNT(*)
FROM orders
WHERE customer_id = 123

Try this:

SELECT 1
FROM orders
WHERE customer_id = 123
LIMIT 1

Or this:

SELECT 'Customer has orders'
FROM orders
WHERE EXISTS (
  SELECT 1
  FROM orders
  WHERE customer_id = 123
  LIMIT 1
)

  1. Replace NULLs with COALESCE Instead of CASE for Defaults


COALESCE() is simpler to write when you want to provide a default value.


Instead of this:

CASE
	WHEN phone_number IS NULL THEN 'N/A'
	ELSE phone_number
END

Try this:

COALESCE(phone_number, 'N/A')

  1. Use CTEs to Simplify Long Queries


This is another big one. A CTE (Common Table Expression) lets you break logic into readable chunks using WITH. Once you start using them, you'll find that readability improves and debugging is much easier.


For example:

WITH recent_orders AS (
	SELECT *
	FROM orders
	WHERE order_date >= '2024-01-01'
)

SELECT * FROM recent_orders WHERE order_total > 100

  1. Format CASE Statements Clearly


There are three main types of CASE statements:

  • Simple CASE: Compares the same field to multiple values.

CASE status
	WHEN 'A' THEN 'Active'
	WHEN 'I' THEN 'Inactive'
	ELSE 'Unknown'
END

  • Searched CASE: Lets you write different conditions.

CASE
	WHEN score >= 90 THEN 'Excellent'
	WHEN score >= 75 THEN 'Good'
	ELSE 'Needs Improvement'
END

  • Nested CASE: Use it sparingly as it can get complicated. Sometimes a CTE is a better choice.


  1. Comment When Logic Isn’t Obvious


Leave a quick comment to explain anything complex. It saves time later so you don't have to search for documentation elsewhere if a simple note in the query explains the logic.


For example:

-- Filter out internal test accounts
WHERE email NOT LIKE '%@test.com'

  1. Always Use ORDER BY When You Need Order


SQL doesn’t guarantee row order unless you explicitly ask for it. Don’t just assume the output will be sorted.


ORDER BY will automatically sort in ascending order, or you can specify descending order like this:


ORDER BY [column] DESC

  1. Write NULL Checks Properly


This one trips up a lot of beginners to SQL.


Don’t write: WHERE column = NULL, as you will get an error.

Use WHERE column IS NULL or WHERE column IS NOT NULL.


Clean SQL Pays Off


Writing clean SQL isn't just about the aesthetics, though it does help! You want to save yourself (and others) time, avoid confusion, and make your work easier to read, debug, and reuse. If you've ever seen a messy SQL query, you know how hard it can be to understand.

And readable queries mean you'll make fewer mistakes, and your queries will scale better as your data grows.


If you're just learning SQL, my tip is to start small. You don't need to use every best practice right away. Try a few, practice them regularly, and the rest will follow naturally. Pretty soon, it will become second nature to you.


Most of all, just have fun writing queries. SQL is a pretty cool language once you get the hang of it. So don't stress. Just keep these best practices in mind as you work, and you'll start writing cleaner, faster, and more understandable queries in not time.


👉 Want something you can reference while you're working? Grab my one-page SQL Best Practices Guide here:


What do you think?

Got your own formatting tip or pet peeve? Leave a comment or send me a message. I always like hearing how other analysts write their SQL.


If you found this helpful, share it with someone learning SQL or subscribe to my newsletter for more posts like this.

And come say hi on LinkedIn. I’d love to see what you’re working on.

1 Comment

Rated 0 out of 5 stars.
No ratings yet

Add a rating
Guest
3 days ago
Apart from using SELECT *, which I have a full article on, (https://medium.com/@ameikpe/why-you-should-not-use-select-from-table-in-sql-1b7017747b13) i am guilty of some of them. I typically write in lowercase so all my queries are in lowercase too.

Like

RECENT POSTS

Don't forget to subscribe!

Never miss a new post:

  • LinkedIn
  • Instagram
  • Facebook
  • X
  • Pinterest
may 6 logo.png

© 2025 Data with Sarah. All rights reserved.

bottom of page