Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need an else clause in a case expression?

Does one need to include an ELSE clause in a CASE expression?

For example, if I wanted to pull the names of animals that are cats and nothing ELSE, could I use this SELECT statement:

SELECT DISTINCT(CASE WHEN animal_type = 'cat' THEN animal_name END) AS cat_names

I know I could just put animal_type = 'cat' in my WHERE clause and then

SELECT DISTINCT cat_names, 

but I'd like to know the answer.

like image 204
cjacobso Avatar asked Sep 19 '14 14:09

cjacobso


People also ask

Do you need an else in CASE statement?

The CASE statement always goes in the SELECT clause. CASE must include the following components: WHEN , THEN , and END . ELSE is an optional component.

Can we use ELSE IN CASE statement in SQL?

The 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.

Can I have where clause in CASE statement?

Another way to use the Case Statement is within the WHERE clause. There, it may be utilized to alter the data fetched by a query based on a condition. Within that context, the Case Statement is ideally suited to both static queries, as well as dynamic ones, such as those that you would find inside a stored procedure.

Are case statements better than if else?

The first of which is that in most cases, case statements are slightly more efficient than a whole bunch of if statements. However the only real reason why case statements are better that will ever really affect you is that they are a lot easier to read.


1 Answers

You do not need an else clause. If one isn't specified, case will return null. In other words, it acts as though it has an else null clause.

like image 81
Mureinik Avatar answered Sep 21 '22 14:09

Mureinik