Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT using 'CASE' in SQL

Tags:

sql

select

case

I have a set of one to one mappings A -> apple, B-> Banana and like that.. My table has a column with values as A,B,C..

Now I'm trying to use a select statement which will give me the direct result

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN FRUIT ='APPLE' 
     ELSE WHEN FRUIT ='B' THEN FRUIT ='BANANA'     
 FROM FRUIT_TABLE;

But I'm not getting the correct result, please help me..

like image 230
Vamshi Avatar asked Jan 23 '14 15:01

Vamshi


People also ask

Can you use SELECT in case SQL?

The CASE statement always goes in the SELECT clause. CASE must include the following components: WHEN , THEN , and END . ELSE is an optional component. You can make any conditional statement using any conditional operator (like WHERE ) between WHEN and THEN .

Can I use CASE in SELECT?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.

What is a SQL use CASE?

A SQL CASE statement evaluates and returns results based on particular values, predicates and conditions as per defined logic. For example, suppose you have a voters table with the following details: Voter ID. Name.


3 Answers

This is just the syntax of the case statement, it looks like this.

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END AS FRUIT
FROM FRUIT_TABLE;

As a reminder remember; no assignment is performed the value becomes the column contents. (If you wanted to assign that to a variable you would put it before the CASE statement).

like image 173
Hogan Avatar answered Sep 19 '22 04:09

Hogan


Change to:

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END
FROM FRUIT_TABLE;
like image 24
everton Avatar answered Sep 22 '22 04:09

everton


Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;
like image 41
peter.petrov Avatar answered Sep 22 '22 04:09

peter.petrov