lisovaccaro
lisovaccaro

Reputation: 33956

Mysql IF statement in SELECT clause?

I'm trying to include an IF on my SELECT statement, while defining a temporary column.

This is what I'm trying right now:

SELECT *, IF A > 0, A, 0.5 AS Popularity FROM Visits

How is it correctly done?

Upvotes: 1

Views: 516

Answers (3)

Alain
Alain

Reputation: 36954

You want to do :

SELECT *, IF (A > 0, A, 0.5) AS Popularity FROM Visits

Upvotes: 3

Fred Sobotka
Fred Sobotka

Reputation: 5332

An alternative that works in other DBMSes is

SELECT CASE WHEN ( a > 0 ) THEN a ELSE 0.5 END AS popularity FROM visits

Upvotes: 2

Marc B
Marc B

Reputation: 360682

You're using the IF syntax used in stored procedures. For SELECT use, it has to be the function version:

SELECT *, IF(A>0, A, 0.5) AS Popularity ...

Upvotes: 2

Related Questions