# SQL CASE Statement

### The SQL CASE Statement

The CASE statement goes through conditions and return a value when the first condition is met (like an IF-THEN-ELSE statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

If there is no ELSE part and no conditions are true, it returns NULL.<br>

**CASE Syntax**

```
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
```

### Demo Database

Below is a selection from the "OrderDetails" table in the Northwind sample database:

![](https://826093633-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS8lPNzCGPR5-DLbGXv%2F-LScDwr8Gx1j8bekaeen%2F-LScEQ88nGSMw_-I8ZE8%2Fimage.png?alt=media\&token=3092ccd6-078d-4836-b5cc-fb2f978a879d)

**SQL CASE Examples**

The following SQL goes through conditions and returns a value when the first condition is met:<br>

```
SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN "The quantity is greater than 30"
    WHEN Quantity = 30 THEN "The quantity is 30"
    ELSE "The quantity is under 30"
END
FROM OrderDetails
```

The following SQL will order the customers by City. However, if City is NULL, then order by Country:

```
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);

```

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-sql.gitbook.io/sql-programming/sql-select/sql-case-statement.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
