If Else In SQL

Galaxy Glossary

How can I use conditional logic in SQL queries?

SQL's IF-THEN-ELSE statements allow you to execute different blocks of code based on conditions. This enables complex data manipulation and filtering. They are crucial for creating dynamic queries.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

SQL, while primarily known for its declarative nature, does offer conditional logic through the `CASE` statement. This statement allows you to evaluate conditions and return different values or execute different actions based on those evaluations. Unlike procedural languages like Python or Java, SQL's `CASE` statement doesn't have a direct equivalent to a traditional `if-then-else` structure. Instead, it provides a structured way to handle conditional logic within a query. This is particularly useful for filtering data, transforming values, or generating reports based on specific criteria. The `CASE` statement is a powerful tool for creating dynamic queries that adapt to various conditions. It's important to understand that `CASE` statements are evaluated sequentially, so the first matching condition determines the outcome.

Why If Else In SQL is important

Conditional logic in SQL is essential for creating dynamic queries that adapt to various conditions. It allows for more complex data manipulation and filtering, leading to more accurate and insightful reports.

Example Usage


-- Sample table
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    Name VARCHAR(50),
    Department VARCHAR(50),
    Salary INT
);

INSERT INTO Employees (EmployeeID, Name, Department, Salary) VALUES
(1, 'John Doe', 'Sales', 50000),
(2, 'Jane Smith', 'Marketing', 60000),
(3, 'Peter Jones', 'Sales', 45000),
(4, 'Mary Brown', 'Engineering', 70000);

-- Using CASE to categorize employees by salary
SELECT
    EmployeeID,
    Name,
    Department,
    CASE
        WHEN Salary >= 60000 THEN 'High Salary'
        WHEN Salary >= 50000 THEN 'Medium Salary'
        ELSE 'Low Salary'
    END AS SalaryCategory
FROM
    Employees;

Common Mistakes

Want to learn about other SQL terms?