Thursday 12 July 2018

MySQL CASE Expression?

MySQL CASE Expression?

Summary: in this tutorial, we will show you how to use MySQL CASE expression to construct conditional queries.

Introduction to MySQL CASE expression

MySQL CASE expression is a flow control structure that allows you to construct conditions inside a query such as SELECT or WHERE clause. MySQL provides you with two forms of the CASE expressions.
The following illustrates the first form of the CASE expression.
If the value is equal to compare_value e.g., compare_value_1compare_value_2, etc., then the CASEexpression returns the corresponding result i.e., result_1result_2 . In case the value does not match any compare_value, the CASE expression returns the result specified in the ELSE clause.
The second form of the CASE expression is as follows:
In the second form, the CASE expression returns the result such as result_1result_2, etc., if the condition is true. If all conditions are false, then the result in the ELSE part is returned. If the ELSEpart is omitted, the CASE expression returns NULL .
The CASE expression returns the result whose data type depends on the context where it is used. For example, if the CASE expression is used in string context, it returns the result as a string. If the CASEexpression is used in a numeric context, it returns the result as an integer, a decimal, or a real value.

MySQL CASE function examples

Let’s take a look at the customers table in the sample database.

Suppose you want to sort the customers by state, and if the state is NULL, you want to use the country as the sorting criterion instead. To achieve this, you can use the first form of the CASE expression as follows:

In this example, we used the CASE expression in the ORDER BY clause to determine the field, state or country, which we want to sort.
In the next example, we will use the orders table in the sample database to demonstrate the second form of the CASE expression.
orders table
If you want to see the number of sales orders by their statuses e.g., the number of shipped orders, on-hold orders, etc., you can use the second form of the CASE expression as follows:
The result of the query is as follows:

In the SELECT statement, if the status is equal to shippedon hold, etc., the CASE expression returns 1, otherwise, it returns 0. We used the SUM function to calculate the total of the sales orders for each status.
In this tutorial, we have shown you how to use the MySQL CASE expression in SELECT statements to construct conditional queries.

0 comments:

Post a Comment