Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a conditional in a MySQL select statement?

Tags:

sql

mysql

I'm using MySQL, and I want to do a sort of ternary statement in my SQL like:

SELECT USER_ID, ((USER_ID = 1) ? 1 : 0) AS FIRST_USER   FROM USER 

The results would be similar to:

USER_ID | FIRST_USER 1       | 1 2       | 0 3       | 0 etc. 

How does one accomplish this?

like image 241
Langdon Avatar asked Oct 30 '09 04:10

Langdon


People also ask

Can we use if condition in MySQL query?

The MySQL IF() function is used for validating a condition. The IF() function returns a value if the condition is TRUE and another value if the condition is FALSE. The MySQL IF() function can return values that can be either numeric or strings depending upon the context in which the function is used.

How do I write a select statement in MySQL?

Introduction to MySQL SELECT statement First, specify one or more columns from which you want to select data after the SELECT keyword. If the select_list has multiple columns, you need to separate them by a comma ( , ). Second, specify the name of the table from which you want to select data after the FROM keyword.


1 Answers

SELECT USER_ID, (CASE USER_ID WHEN 1 THEN 1 ELSE 0 END) as FIRST_USER FROM USER 
like image 92
x2. Avatar answered Oct 12 '22 02:10

x2.