DEV Community

Muhammad Ali Siddiqui
Muhammad Ali Siddiqui

Posted on

5 Small SQL Habits That Save You From Bad Queries

When I first started writing SQL queries, my only goal was getting the right output on the screen. As long as the query returned data without throwing an error, I moved on.

Over time, I realized that writing queries that work and writing queries that are safe and clean are two very different things. Here are five small habits that made a noticeable difference in how I write SQL:

1. Stop Using SELECT * Everywhere

It is tempting to grab every column when testing a query, especially on small tables. The problem is that pulling unnecessary columns slows things down as tables grow and makes your code harder to read later.

-- Instead of this:
SELECT * FROM users WHERE status = 'active';

-- Be specific:
SELECT id, username, email FROM users WHERE status = 'active';
Enter fullscreen mode Exit fullscreen mode

2. Write the WHERE Clause Before Running UPDATE or DELETE

One careless UPDATE or DELETE without a condition can wipe or overwrite an entire table in milliseconds. A simple habit that prevents this: write the SELECT query with your WHERE condition first to see which rows match, then switch it to UPDATE or DELETE.

-- Step 1: Check what you're about to touch
SELECT * FROM orders WHERE order_id = 1042;

-- Step 2: Run the actual change
DELETE FROM orders WHERE order_id = 1042;
Enter fullscreen mode Exit fullscreen mode

3. Be Intentional With INNER JOIN vs. LEFT JOIN

Early on, it is easy to slap a JOIN into a query and wonder why half the records disappeared. INNER JOIN only returns rows that match in both tables, while LEFT JOIN keeps everything from the left table even if there is no match on the right. Knowing which one you actually need saves hours of debugging missing records.

4. Always Use Parameterized Queries (Prepared Statements)

Never concatenate raw user input directly into an SQL string. Even in small practice apps, building the habit of using prepared statements keeps your queries clean and protects your database from SQL injection.

// Safe approach using prepared statements
$stmt =$pdo->prepare("SELECT id, email FROM users WHERE username = :username");
$stmt->execute(['username' =>$inputUsername]);
Enter fullscreen mode Exit fullscreen mode

5. Format Your Queries So Future-You Can Read Them

A 6-line query jammed into a single line is painful to debug. Putting keywords like SELECT, FROM, WHERE, and ORDER BY on their own lines takes two extra seconds and makes spotting mistakes way easier.

SELECT name, created_at
FROM customers
WHERE country = 'Pakistan'
ORDER BY created_at DESC;
Enter fullscreen mode Exit fullscreen mode

None of these are advanced database tricks, just small habits that keep things predictable as your tables and queries grow.

What is one SQL habit or mistake you learned the hard way?

Top comments (0)