How to Write a Case Statement in SQL
Case Statements are a powerful tool that allow you to make decisions based on the data in your database. The CASE keyword is used to start the statement, followed by one or more WHEN clauses. Each WHEN clause contains a condition and a result. If the condition is true, then the result is returned. If no conditions are true, then the optional ELSE clause is used. If no ELSE clause is provided, then NULL is returned. The syntax for writing a Case Statement in SQL is as follows:
CASE
WHEN condition
THEN result
[ELSE result]
END
Examples
Let's look at a few examples of how to use a Case Statement in SQL. Suppose you have a table called users with the following data:
name | age |
---|---|
John | 25 |
Jane | 30 |
John | 25 |
Bob | 20 |
If you wanted to return the name of the oldest user, you could use the following query:
SELECT
CASE
WHEN age = 30 THEN name
ELSE 'No one'
END
FROM users;
This query would return the result Jane, since Jane is the only user with an age of 30.
Additional Info
Case Statements are a powerful tool for making decisions in your SQL queries. However, they are not supported by all databases. Be sure to check the documentation for your particular database to see if Case Statements are supported. 🤓