Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CASE to select a field in SQL?

Tags:

sql

Based on if one field in the database is equal to something, I want to select the value of another field. I was thinking that I could use CASE THEN but I can't get it to return the value of a field.

Here is what I have tried so far:

SELECT LastName, CASE FirstName WHEN 'Ian' THEN JobNo END FROM Employees

JobNo is the name of the field which I want to get the value from.

like image 604
Poku Avatar asked Nov 10 '10 08:11

Poku


People also ask

How do you USE CASE statement in SQL?

The SQL CASE Statement The CASE statement 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.

How do you use a case expression in a SELECT statement?

The simple way to achieve this goal is to add a CASE expression to your SELECT statement. In this article, we'll introduce you to the syntax, formats, and uses of the CASE expression. The CASE expression is a conditional expression: it evaluates data and returns a result.

What is the difference between case and then in SQL?

The expression starts with the CASE keyword and ends with the END keyword. The names of specific columns or expressions are entered after the CASE keyword. The WHEN and THEN keywords define the logical conditions. After the WHEN clause, we see the condition or value to compare; the THEN determines the result if the condition is met.

What is a searched CASE in SQL Server?

The searched CASE expression is the most commonly-used format. But instead of comparing a column or expression against a defined set of values, a searched expression can compare multiple WHEN conditions and determine a result. This makes a searched CASE the better choice for more complicated logic. CASE WHEN conditions THEN when_result ...


3 Answers

try this

SELECT LastName, CASE  WHEN FirstName ='Ian' THEN JobNo else null END
FROM Employees
like image 114
Preet Sangha Avatar answered Sep 22 '22 23:09

Preet Sangha


you're missing the else statement in your case statement, once that's in there it should work

like this:

SELECT LastName, 
    CASE FirstName WHEN 'Ian' THEN JobNo ELSE -1 END
FROM Employees
like image 45
mjallday Avatar answered Sep 22 '22 23:09

mjallday


You need to define the ELSE:

SELECT LastName, CASE FirstName WHEN 'Ian' THEN JobNo ELSE FirstName END
FROM Employees

I've defaulted to return the FirstName, if you don't want that just replace with something else. Just make sure the datatypes are equivalent to avoid potential issues (I've assumed JobNo is a varchar ref code for purpose of demonstrating syntax).

like image 42
AdaTheDev Avatar answered Sep 22 '22 23:09

AdaTheDev