Best SQL Practices I Wish I Knew Earlier
When you first learn SQL, the goal is simple: get the query to return the right rows. If it runs, you move on. That works fine on a practice table with twenty records, and then one day you meet a table with a few million rows (or a teammate who has to read your 60-line query) and everything falls apart.
This is my first blog, so I wanted to start with something I actually use every time I write a query. These are the habits that make SQL easier to read, faster to run and harder to break. The examples use a simple Students and Orders style of data, and I’ve noted where SQL Server differs from other databases.
1. Make your queries easy to read
Databases don’t care about formatting, but people do, and that includes you three weeks from now. A few small rules go a long way:
- Write keywords in uppercase (
SELECT,FROM,WHERE) and put each major clause on its own line. - Use clear, consistent names.
student_idbeatssid, andordersbeatstbl1. - Pick one naming style (
snake_caseorPascalCase) and stick to it across the whole database. - Use short, meaningful table aliases like
sfor students, nota,b,c.
select a.name,b.total from students a join orders b on a.id=b.sid where b.total > 500 order by b.total descSELECT s.name,
o.total
FROM students AS s
JOIN orders AS o ON o.student_id = s.id
WHERE o.total > 500
ORDER BY o.total DESC;Same query, same result. Only one of them can be debugged at a glance.
2. Stop using SELECT *
SELECT * is tempting because it’s short. The problem is that it pulls every column, including the ones you never use, which means more data moving over the network and more work for the database. It also makes your code fragile: if someone adds or reorders a column later, your application can quietly break.
SELECT * FROM students;SELECT student_id, name, email
FROM students;Using SELECT * is fine when you’re just exploring a table in a console. Keep it out of anything you save or ship.
3. Write explicit JOINs
The old style of listing tables with commas and putting the join condition in WHERE still works, but it’s easy to forget a condition and end up with a cartesian product, where every row is paired with every other row. Explicit joins make the relationship obvious and keep join logic separate from filtering.
SELECT s.name, o.total
FROM students s, orders o
WHERE s.id = o.student_id
AND o.total > 500;SELECT s.name, o.total
FROM students AS s
INNER JOIN orders AS o ON o.student_id = s.id
WHERE o.total > 500;Also, pick the right join on purpose. INNER JOIN keeps only matches, while LEFT JOIN keeps every row from the left table even when there is no match. Mixing them up is one of the most common reasons for “missing” rows.
4. Filter early and keep your WHERE clause index-friendly
The less data you carry through a query, the faster it runs. Filter as early as you can, and be careful about how you write the filter. If you wrap an indexed column in a function, the database often can’t use the index and has to scan the whole table. People call a condition that can use an index “sargable”.
SELECT order_id
FROM orders
WHERE YEAR(order_date) = 2026;SELECT order_id
FROM orders
WHERE order_date >= '2026-01-01'
AND order_date < '2027-01-01';The same idea applies to LIKE. LIKE 'Par%' can use an index, but LIKE '%ras' usually can’t, because the database doesn’t know where to start looking.
5. Add indexes with intention
An index is like the index at the back of a textbook. It helps you jump to a topic quickly, but it also takes space and has to be updated every time the book changes. In database terms, indexes speed up reads and slow down INSERT, UPDATE and DELETE a little.
- Index columns you often use in
WHERE,JOINandORDER BY. - Foreign key columns are usually good candidates.
- Don’t index everything. Each extra index has a cost, and a column with very few distinct values (like a yes/no flag) rarely benefits.
- For queries that filter on two columns together, a composite index can work better than two separate ones. Column order matters.
CREATE INDEX idx_orders_student_date
ON orders (student_id, order_date);6. Use CTEs to untangle complicated queries
Deeply nested subqueries are hard to follow. A Common Table Expression (CTE), written with WITH, lets you give a name to an intermediate step and read the query from top to bottom, almost like a story.
WITH student_totals AS (
SELECT student_id,
SUM(total) AS total_spent
FROM orders
GROUP BY student_id
)
SELECT s.name,
st.total_spent
FROM student_totals AS st
JOIN students AS s ON s.id = st.student_id
WHERE st.total_spent > 5000
ORDER BY st.total_spent DESC;A CTE is mostly about readability. Don’t assume it makes a query faster on its own.
7. Handle NULLs on purpose
NULL doesn’t mean zero or empty. It means “unknown”, and that changes how comparisons behave. Anything compared to NULL with = gives unknown, not true, so those rows silently disappear.
SELECT name FROM students WHERE phone = NULL;SELECT name FROM students WHERE phone IS NULL;
-- Give NULLs a default when displaying or calculating
SELECT name, COALESCE(phone, 'Not provided') AS phone
FROM students;Also watch out for NOT IN with a subquery that can return NULL. One NULL in the list can make the whole condition return nothing. NOT EXISTS avoids that trap.
8. Never build queries by gluing strings together
If your application creates SQL by concatenating user input, you are inviting SQL injection, which is still one of the most common security problems in real applications. Use parameterized queries or prepared statements and let the driver handle the values.
String sql = "SELECT * FROM users WHERE email = '" + email + "'";String sql = "SELECT user_id, name FROM users WHERE email = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, email);
ResultSet rs = ps.executeQuery();With a parameter, whatever the user types is treated as data and never as part of the command.
9. Be careful with UPDATE and DELETE, and read the execution plan
We have all heard the horror story of running DELETE FROM orders; and forgetting the WHERE. A few habits make that kind of mistake much less likely:
- Write the
SELECTwith yourWHEREfirst, check the rows, then turn it into anUPDATEorDELETE. - Wrap risky changes in a transaction so you can roll back if the row count looks wrong.
- Take a backup before any large change on real data.
BEGIN TRANSACTION;
UPDATE orders
SET status = 'Cancelled'
WHERE order_id = 1042;
-- Check that exactly one row changed, then:
COMMIT;
-- If something looks wrong:
-- ROLLBACK;Finally, don’t guess why a query is slow. Look at the execution plan. In SQL Server Management Studio you can turn on “Include Actual Execution Plan”, and in MySQL or PostgreSQL you can put EXPLAIN in front of the query. If you see a full table scan on a big table, that is usually your cue to check the WHERE clause and the indexes.
SQL Server tip: to peek at a few rows while exploring, use SELECT TOP 10 .... MySQL and PostgreSQL use LIMIT 10 at the end instead.
A quick checklist before you hit Run
- Is the query formatted so someone else can read it?
- Am I selecting only the columns I need?
- Are my joins explicit, and are they the right type?
- Can the database use an index for my
WHEREclause? - Have I thought about
NULLvalues? - Is user input passed as parameters?
- For changes: did I test with
SELECTfirst and use a transaction?
You don’t need to master all of this in one day. Pick two or three habits, use them in your next project, and add more as they start to feel natural. I’m still learning too, and writing this down was a good way to make these rules stick.
If you have a favourite SQL tip I missed, I would love to hear it. Thanks for reading my first blog!