SQL
if clause
programming
SQL queries
conditional statements

How do I put an 'if clause' in an SQL string?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

When people ask for an "if clause" in SQL, they usually mean one of several different things. They might want a conditional value inside a query, an optional filter, procedural control flow in a stored routine, or dynamic SQL assembled in application code. SQL can handle all of those, but not with one single syntax.

Use CASE for Conditional Values in a Query

Inside a normal SELECT, UPDATE, ORDER BY, or similar statement, the standard SQL tool is CASE.

sql
1SELECT
2    order_id,
3    total_amount,
4    CASE
5        WHEN total_amount >= 500 THEN 'priority'
6        WHEN total_amount >= 100 THEN 'standard'
7        ELSE 'small'
8    END AS order_type
9FROM orders;

This is the portable, database-friendly equivalent of "if this, then that" inside an expression. If your condition is producing a value, CASE is usually the correct answer.

Optional Filters Can Often Stay in One Query

Sometimes the question is really about making a filter optional. In that case, you may not need multiple SQL strings at all. A parameter-aware predicate is often enough.

sql
1SELECT *
2FROM orders
3WHERE (:status IS NULL OR status = :status)
4  AND (:min_total IS NULL OR total_amount >= :min_total);

If :status is null, the first condition becomes a no-op. If it has a value, the filter becomes active. This pattern is useful when the overall shape of the query stays the same.

Dialect-Specific IF Exists, But CASE Is Safer

Some databases expose an IF function. MySQL is a common example:

sql
1SELECT
2    order_id,
3    IF(total_amount > 500, 'priority', 'normal') AS label
4FROM orders;

That can be convenient, but it is not portable SQL. If your code may ever move between engines, CASE is the safer choice because it is part of standard SQL.

Procedural IF Belongs in Stored Routines

If you are writing a stored procedure, function, or procedural block, some databases support real control-flow statements such as IF ... THEN ... ELSE. That is different from a plain query expression.

MySQL example:

sql
1DELIMITER //
2
3CREATE PROCEDURE classify_order(IN p_total DECIMAL(10,2))
4BEGIN
5    IF p_total >= 500 THEN
6        SELECT 'priority' AS order_type;
7    ELSE
8        SELECT 'normal' AS order_type;
9    END IF;
10END //
11
12DELIMITER ;

This syntax works in procedural SQL, not in the middle of an ordinary SELECT list. Mixing those two contexts is a common source of confusion.

Build Dynamic SQL in Application Code When the Query Shape Changes

If the condition changes which clauses exist at all, build the SQL string in application code, but always keep values parameterized.

python
1sql = "SELECT * FROM users WHERE 1=1"
2params = {}
3
4if status is not None:
5    sql += " AND status = :status"
6    params["status"] = status
7
8if min_age is not None:
9    sql += " AND age >= :min_age"
10    params["min_age"] = min_age

This is appropriate when entire joins, filters, or sort rules are optional. The key point is that the structure may be dynamic, but raw values should still go through parameters.

Never Concatenate User Input Into SQL

The dangerous version of dynamic SQL is direct string concatenation with untrusted values.

python
sql = "SELECT * FROM users WHERE name = '" + user_input + "'"

That creates SQL injection risk and can also break quoting, encoding, and null handling. Dynamic SQL is not the problem by itself. Unsafe value insertion is the problem.

Common Pitfalls

One common mistake is trying to use procedural IF syntax inside a normal query. For ordinary SQL expressions, CASE is the right construct.

Another mistake is using a database-specific IF function when portability matters. It works until the day the query moves to another engine.

Developers also often overbuild dynamic SQL for optional filters that could have stayed in a single parameterized statement.

Finally, never treat string concatenation as a shortcut for conditional logic. The moment raw input enters the SQL text, security and correctness problems follow.

Summary

  • Use CASE for conditional expressions inside normal SQL queries.
  • Use parameter-aware predicates when filters are optional but the query shape stays the same.
  • Use procedural IF only inside stored routines or procedural SQL blocks.
  • Build SQL dynamically in application code only when the query structure truly changes.
  • Parameterization is mandatory whenever external values influence the query.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.