Sławosz
Sławosz

Reputation: 11687

Is there a method to apply kind of trinary operator on mysql query?

is there possible to do something like this in mysql: SELECT foo, bar, (created_at > '2012-12-12' ? 'actual': 'old') FROM table;, is there a function that allows me to do this?

Upvotes: 0

Views: 80

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180997

You can use either IF which is MySQL specific;

SELECT foo, bar, IF(created_at > '2012-12-12', 'actual', 'old') 
FROM table1

(SQLFiddle)

...or you can use CASE which is ANSI standard and works across pretty much any SQL dialect (Oracle/SQL Server/PostgreSQL/...)

SELECT foo, bar, CASE WHEN created_at > '2012-12-12'
                      THEN 'actual' 
                      ELSE 'old' 
                 END 
FROM table1

(SQLfiddle)

Upvotes: 1

Jim
Jim

Reputation: 22656

IF is a (slightly) more verbose way of doing what you want:

SELECT foo, bar, IF(created_at > '2012-12-12','actual','old') FROM table;

Upvotes: 1

Related Questions