Перейти к содержимому

Как работает case в sql

  • автор:

SQL CASE Expression

The CASE expression goes through conditions and returns 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.

CASE Syntax

Demo Database

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

OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40

SQL CASE Examples

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

Example

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

SQL CASE

Инструкция CASE проходит через условия и возвращает значение, когда выполняется первое условие (например, инструкция IF-THEN-ELSE). Таким образом , как только условие истинно, оно прекратит чтение и вернет результат. Если никакие условия не являются истинными, он возвращает значение в предложении ELSE.

Если нет никакой другой части и никакие условия не истинны, он возвращает NULL.

Синтаксис CASE

Демо база данных

Ниже приведен выбор из таблицы «OrderDetails» в образце базы данных Northwind:

OrderDetailID OrderID ProductID Quantity
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40

Примеры SQL CASE

Следующий SQL проходит через условия и возвращает значение при выполнении первого условия:

Пример

Следующий SQL будет заказывать клиентов по городам. Однако, если город равен нулю, тогда порядок по странам:

Пример

Мы только что запустили
SchoolsW3 видео

ВЫБОР ЦВЕТА

colorpicker

Сообщить об ошибке

Если вы хотите сообщить об ошибке или внести предложение, не стесняйтесь отправлять на электронное письмо:

Ваше предложение:

Спасибо Вам за то, что помогаете!

Ваше сообщение было отправлено в SchoolsW3.

ТОП Учебники
ТОП Справочники
ТОП Примеры
Получить сертификат

SchoolsW3 оптимизирован для бесплатного обучения, проверки и подготовки знаний. Примеры в редакторе упрощают и улучшают чтение и базовое понимание. Учебники, ссылки, примеры постоянно пересматриваются, чтобы избежать ошибок, но не возможно гарантировать полную правильность всего содержания. Некоторые страницы сайта могут быть не переведены на РУССКИЙ язык, можно отправить страницу как ошибку, так же можете самостоятельно заняться переводом. Используя данный сайт, вы соглашаетесь прочитать и принять Условия к использованию, Cookies и политика конфиденциальности.

Как работает case в sql

Функция CASE проверяет значение некоторого выражение, и в зависимости от результата проверки может возвращать тот или иной результат.

CASE принимает следующую форму:

Возьмем для примера следующую таблицу Products:

Выполним запрос к этой таблице и используем функцию CASE:

Здесь значения столбца ProductCount последовательно сравнивается со значениями после операторов WHEN. В зависимости от значения столбца ProductCount функция CASE будет возвращать одну из строк, которая идет после соответствующего оператора THEN. Для возвращаемого результата определен столбец EvaluateCount:

Функция CASE в T-SQL и MS SQL Server

Также функция CASE может принимать еще одну форму:

Например, применительно к таблице Products:

Фактически все то же самое, что и в предыдущем примере, только после CASE не указывается сравниваемое значение. А сами выражения сравнения стоят после оператора WHEN. И если выражение после оператора WHEN будет истинно, то возвращается значение, которое идет после соответствующего оператора THEN.

CASE WHEN в T-SQL и MS SQL Server

Функция IIF в зависимости от результата условного выражения возвращает одно из двух значений. Общая форма функции выглядит следующим образом:

Если условие в функции IIF истинно то возвращается значение_1, если ложно, то возвращается значение_2. Например:

SQL CASE

Summary: in this tutorial, you will learn how to use the SQL CASE expression to add the logic to the SQL statements.

Introduction to SQL CASE expression

The SQL CASE expression allows you to evaluate a list of conditions and returns one of the possible results. The CASE expression has two formats: simple CASE and searched CASE.

You can use the CASE expression in a clause or statement that allows a valid expression. For example, you can use the CASE expression in statements such as SELECT, DELETE, and UPDATE or in clauses such as SELECT, ORDER BY, and HAVING.

Simple CASE expression

The following illustrates the simple CASE expression:

The CASE expression compares an expression to a set of expression (when_expression_1, when_expression_2, when_expression_3, …) using the equality operator (=). If you want to use other comparison operators such as greater than (>), less than (<), etc., you use the searched CASE expression.

The CASE statement returns the result_1, result_2, or result_3 if the expression matches the corresponding expression in the WHEN clause.

If the expression does not match any expression in the WHEN clause, it returns the esle_result in the ELSE clause. The ELSE clause is optional.

If you omit the ELSE clause and the expression does not match any expression in the WHEN clause, the CASE expression returns NULL.

Simple CASE expression example

Let’s take a look at the employees table.

employees_table

Suppose the current year is 2000.

We can use the simple CASE expression to get the work anniversaries of employees by using the following statement:

SQL CASE simple CASE example

The YEAR function returns the year when the employee joined the company. We get the number of years that the employee has been with the company and by subtracting the year when the employee joined the company from the current year (2000).

We get the number of years that the employee has been with the company by subtracting the year when the employee joined the company from the current year (2000).

Then we compare the result with 1, 3, 5, 10, 15, 20, 25, 30 If the year of service equals one of these numbers, the CASE expression returns the work anniversary of the employee.

If the year of services of the employee does not match these numbers, the CASE expression returns NULL.

Searched CASE expression

The following shows the searched CASE expression.

The database system evaluates the boolean expression for each WHEN clause in the order specified in the CASE expression.

If the Boolean expression in each WHEN clause evaluates to true, the searched CASE statement returns the result in the corresponding THEN clause.

If no Boolean expression returns true, the CASE expression return the result else_result in the ELSE clause.

Like the simple CASE expression, the END clause is optional. If you omit the ELSE clause and no Boolean expression evaluates to true, the CASE expression returns a NULL value.

Search CASE expression example

The following illustrates the searched CASE expression example.

If the salary is less than 3000, the CASE expression returns “Low”. If the salary is between 3000 and 5000, it returns “average”. When the salary is greater than 5000, the CASE expression returns “High”.

SQL CASE searched CASE example

In this tutorial, we have introduced you to the SQL CASE statement that allows you to add the IF THEN ELSE logic to the SQL statements.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Car Rental HPN Inside the Terminal