Home >Database >Mysql Tutorial >How Can I Implement If-Then-Else Logic Using SQL's CASE Statement?

How Can I Implement If-Then-Else Logic Using SQL's CASE Statement?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 05:10:11355browse

How Can I Implement If-Then-Else Logic Using SQL's CASE Statement?

If-Then-Else Logic in SQL

SQL offers the ability to perform conditional logic using the CASE statement. While it may not provide direct syntax for if-then-else constructs, it enables you to define a series of conditions and corresponding actions.

Problem:

Suppose you want to select data from a table based on specific priorities:

  • If project has a record, return it.
  • If customer has a record, return it.
  • If company has a record, return it.

Solution Using CASE:

SELECT product, price
FROM table1
WHERE CASE
  WHEN EXISTS (SELECT 1 FROM table1 WHERE project = 1) THEN 1
  WHEN EXISTS (SELECT 1 FROM table1 WHERE customer = 2) THEN 2
  WHEN EXISTS (SELECT 1 FROM table1 WHERE company = 3) THEN 3
  ELSE NULL
END IS NOT NULL;

This query evaluates each condition sequentially. If project has a record, it returns the matching row; otherwise, it checks for customer and then company. Only rows that satisfy any of the conditions will be selected.

Example:

The following table contains some sample data:

product price project customer company
A 10 1 NULL NULL
B 20 NULL 2 NULL
C 30 NULL NULL 3

Executing the query will return the following results:

product price
A 10

Since there is a row with project = 1, the other conditions are ignored, and the row with product "A" is selected.

The above is the detailed content of How Can I Implement If-Then-Else Logic Using SQL's CASE Statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn