stack stack - 7 months ago 11
SQL Question

How can I check field before selecting?

I have a table like this:

// Names
+----+--------+------------+
| id | name | visibility |
+----+--------+------------+
| 1 | Alex | 1 |
| 2 | Jack | 0 |
| 3 | Peter | 1 |
+----+--------+------------+


I want to select
name
, but I need to check its
visibility
before selecting. In other word, I want it returns name if visibility is
1
, and returns
null
if visibility is
0
. How can I do that in the query?

SELECT (check visibility here) AS name FROM Names WHERE id = :id;





I can do that by PHP like this:

if ($result['visibility'] == 1) {
$name = $result['name'];
} else {
$name = null;
}


But I want to do that by pure-sql.

vkp vkp
Answer

You can use if which is equivalent to a case expression in MySQL.

SELECT if(visibility=1,name,null) name FROM Names WHERE id = :id
Comments