- Aggregate functions
- AVERAGE function
- BETWEEN operator
- CASE expression
- CAST() function
- COALESCE() function
- Comment
- Common table expression
- Constraints
- CONVERT function
- Cursor
- Data types
- Date functions
- DELETE statement
- DROP TABLE statement
- EXISTS operator
- HAVING clause
- IF statement
- Index
- IS NOT NULL condition
- IS NULL condition
- Joins
- LAG function
- LENGTH() function
- LIKE operator
- MERGE statement
- Normalization
- Not equal
- Operators
- ORDER BY clause
- Partition
- Pivot table
- Regex
- REPLACE function
- ROUND function
- SELECT DISTINCT clause
- SELECT statement
- Set operators
- Stored procedure
- String functions
- Subquery
- Substring
- Temporary table
- Transaction
- Trigger
- TRUNCATE TABLE
- UPDATE statement
- Views
- WHERE clause
- Window functions
SQL
SQL IF Statement: Syntax, Usage, and Examples
The SQL IF statement lets you apply conditional logic to your queries and procedures. It helps you control what happens based on whether a condition is true or false. Whether you're updating data, controlling flow in stored procedures, or handling logic in a query, the IF statement SQL syntax gives you more flexibility.
How to Use the SQL IF Statement
The basic structure of the SQL IF statement depends on the context. You’ll find different variations based on whether you're writing a standalone statement, using IF in a stored procedure, or embedding it in a SELECT clause with CASE
.
IF Statement in Stored Procedures (MySQL or SQL Server)
IF condition THEN
-- do something
ELSE
-- do something else
END IF;
IF...ELSE Syntax (T-SQL - SQL Server)
IF condition
BEGIN
-- true block
END
ELSE
BEGIN
-- false block
END
You can also use the SQL IF THEN statement in control-flow scenarios to execute blocks of code selectively.
Conditional Logic in Queries (via CASE)
Standard SQL doesn’t support standalone IF in queries. Instead, you use CASE
to add conditional logic inside a SELECT statement.
SELECT name,
CASE
WHEN age >= 18 THEN 'Adult'
ELSE 'Minor'
END AS category
FROM users;
This approach allows you to mimic the behavior of an if else statement SQL query inside SELECT.
When to Use the SQL IF Statement
In Stored Procedures
Use the SQL IF statement when writing stored procedures or functions to execute specific blocks of code.
IF @role = 'admin'
PRINT 'Access granted';
ELSE
PRINT 'Access denied';
This logic can be expanded to include multiple layers of decision-making.
When Performing Data Validation
Validate inputs before executing operations.
IF EXISTS (SELECT * FROM users WHERE email = @email)
BEGIN
PRINT 'User already exists';
END
ELSE
BEGIN
-- Insert new user
END
This helps protect your database from duplicate or unwanted data.
Inside SQL Queries Using CASE
You can simulate the SQL IF statement using CASE
to return values conditionally.
SELECT order_id,
CASE
WHEN total > 100 THEN 'High Value'
ELSE 'Standard'
END AS order_type
FROM orders;
The SQL IF THEN statement behavior is built into the CASE structure, giving you logic within result sets.
Examples of the SQL IF Statement
Using IF to Perform Conditional Inserts
In a stored procedure:
IF NOT EXISTS (SELECT * FROM products WHERE sku = '12345')
BEGIN
INSERT INTO products (sku, name)
VALUES ('12345', 'Wireless Mouse');
END
You check for a condition, and only act if it’s not met.
Using IF ELSE to Control Flow
IF @count > 10
BEGIN
PRINT 'Too many records';
END
ELSE
BEGIN
PRINT 'Record count acceptable';
END
This classic if else logic lets your SQL scripts react to different scenarios.
SQL Query with IF Statement via CASE
SELECT id, score,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
ELSE 'C'
END AS grade
FROM student_scores;
This is one of the most common uses of conditional logic directly inside SELECT statements.
Learn More About IF Statement in SQL
Nesting IF Statements
You can nest SQL IF statements to handle complex logic:
IF @status = 'pending'
BEGIN
IF @balance >= 100
BEGIN
UPDATE accounts SET status = 'approved' WHERE id = @id;
END
ELSE
BEGIN
PRINT 'Insufficient balance';
END
END
This lets you handle multiple conditions step-by-step.
SQL IF THEN Statement vs CASE
The SQL IF THEN statement works well for procedural logic—like branching inside stored procedures or functions. The CASE
expression, on the other hand, works inside SQL queries.
When to use IF:
- In procedural SQL (stored procedures, functions)
- For branching execution (e.g. run or skip blocks of code)
When to use CASE:
- Inside SELECT, UPDATE, or ORDER BY clauses
- For returning conditional values
Use CASE for Output Formatting
Let’s say you want to add a label based on a price range:
SELECT name, price,
CASE
WHEN price < 50 THEN 'Budget'
WHEN price BETWEEN 50 AND 100 THEN 'Mid-range'
ELSE 'Premium'
END AS price_category
FROM products;
This turns numerical data into something more readable and actionable.
IF in SQL Server vs IF in MySQL
In SQL Server:
- You use
BEGIN...END
to group multiple statements - Variables are declared with
@
In MySQL:
- Use
DELIMITER
to define stored procedures - Use
THEN
andEND IF;
instead ofBEGIN...END
The SQL IF statement syntax varies slightly across platforms, but the core idea remains consistent.
How to Combine Multiple Conditions
Use logical operators to test more than one condition:
IF @quantity > 10 AND @price < 50
BEGIN
UPDATE products SET discount = 0.1 WHERE id = @product_id;
END
You can build complex logic with AND
, OR
, and NOT
.
Simulating IF Statements Without Stored Procedures
Even if your environment doesn’t support stored procedures or blocks, you can simulate IF logic using CASE
, COALESCE
, or nested SELECT
statements.
SELECT
COALESCE(NULLIF(age, 0), 'Unknown') AS adjusted_age
FROM users;
While not technically an IF, this approach still adjusts values conditionally.
The SQL IF statement gives you fine-grained control over how your SQL code behaves. Whether you're running a stored procedure, applying logic inside a query, or validating inputs before performing updates, this feature makes your database scripts smarter and more adaptive.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.