Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison in MySQL SELECT

Does MySQL make it possible to do something like:

SELECT username, age, age>13 AS ageGT FROM users.

And get something like:

+--------+---+-----+
|username|age|ageGT|
+--------+---+-----+
|fred    |14 |true |
|bob     |12 |false|
+--------+---+-----+

?

This would be a huge help, thanks!

Clarification: I'm not looking for a WHERE clause, I want to select both cases, but have a column showing whether the clause evaluates true or false.

like image 201
JJJollyjim Avatar asked Sep 06 '25 03:09

JJJollyjim


1 Answers

You can do CASE WHEN age > 13 THEN 'true' ELSE 'false' END AS ageGT:

SELECT 
    username, 
    age, 
    CASE WHEN age > 13 THEN 'true' ELSE 'false' END AS ageGT
FROM users

Or more simply:

IF(age>13, 'true', 'false') AS ageGT

Read more on CASE Expressions and the IF() Function.

An important difference is that the CASE expression syntax is supported by all major DBMSs, whereas IF() is pretty much MySQL specific.

like image 157
Zane Bien Avatar answered Sep 07 '25 20:09

Zane Bien