Saturday , November 23 2024

CASE Statement in SQL Server(TSQL)

Certain conditions are checked with the WHEN Statement when using the CASE Statement, and certain results are returned if the condition is met. We can define more than one WHEN Statement in a CASE Statement. If no conditions are met in the WHEN Statement defined in the CASE Statement, then the operations in the ELSE Statement are performed.

Let’s make an example for a better understanding of the subject.

Create a table as follows and add a few records to this table.

With the help of the following script, we group the people in the People table according to their age.

In the first WHEN Statement, if the age is between 0 and 3, we include it in the “Baby” group.

In the second WHEN Statement, if the age is between 4 and 15, we include it in the “Child” group.

In the third WHEN Statement, if the age is between 16 and 30, we include it in the “Teen” group.

In the Fourth WHEN Statement, if the age is between 31 and 60, we include it in the “Middle Aged” group.

In the fifth WHEN Statement, we add it to the “Old” group if it is over 60 years old.

If the age of the people in the table is not within this range, we return the value as “No age range found.”.

Loading

About dbtut

We are a team with over 10 years of database management and BI experience. Our Expertises: Oracle, SQL Server, PostgreSQL, MySQL, MongoDB, Elasticsearch, Kibana, Grafana.

Leave a Reply

Your email address will not be published. Required fields are marked *