SQL Else If

Galaxy Glossary

How do you implement conditional logic in SQL?

SQL doesn't have a direct `else if` statement like some programming languages. Instead, you use nested `CASE` statements or multiple `CASE` expressions to achieve the same result. This allows you to define multiple conditions and corresponding actions.
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, unlike some programming languages, doesn't have a direct `else if` construct. To implement conditional logic, you typically use the `CASE` statement. The `CASE` statement allows you to evaluate multiple conditions and return different results based on which condition is met. This is particularly useful for complex data transformations and filtering. A single `CASE` expression can handle multiple conditions, but for more complex scenarios, nested `CASE` statements are necessary. This approach is equivalent to the `else if` construct in other languages, enabling you to create sophisticated decision-making logic within your SQL queries. It's crucial to understand that the `CASE` statement evaluates conditions sequentially, returning the result of the first matching condition. If no condition matches, a default result (specified by the `ELSE` clause) can be returned.

Why SQL Else If is important

The ability to implement conditional logic is essential for data manipulation. `CASE` statements allow you to tailor your queries to specific needs, filtering data based on various criteria and transforming it into meaningful insights. This is crucial for reporting, analysis, and data-driven decision-making.

Example Usage


-- Sample table (Customers)
CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    City VARCHAR(50)
);

INSERT INTO Customers (CustomerID, FirstName, LastName, City) VALUES
(1, 'John', 'Doe', 'New York'),
(2, 'Jane', 'Doe', 'Los Angeles'),
(3, 'John', 'Doe', 'Chicago'),
(4, 'Peter', 'Pan', 'London'),
(5, 'Jane', 'Doe', 'Los Angeles');

-- Identify and delete duplicate rows based on FirstName and LastName
DELETE FROM Customers
WHERE CustomerID NOT IN (
    SELECT MIN(CustomerID)
    FROM Customers
    GROUP BY FirstName, LastName
    HAVING COUNT(*) > 1
);

SELECT * FROM Customers;

Common Mistakes

Want to learn about other SQL terms?