Community Documentation

MySQLism: avoid using IF() in SELECT use CASE()

Last updated June 21, 2010. Created by andypost on June 21, 2010.
Log in to edit this page.

Use CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END not IF()

Documentation

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
http://www.postgresql.org/docs/8.3/static/functions-conditional.html
http://www.sqlite.org/lang_expr.html

Example query

SELECT n.title, n.nid, n.type, n.sticky, n.created, n.uid, n.comment AS comment_mode, ncs.*, f.tid AS forum_tid, u.name, CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END AS last_comment_name FROM {node} n INNER JOIN {node_comment_statistics} ncs ON n.nid = ncs.nid INNER JOIN {forum} f ON n.vid = f.vid INNER JOIN {users} u ON n.uid = u.uid INNER JOIN {users} u2 ON ncs.last_comment_uid = u2.uid WHERE n.nid IN (:nids)

PS: as example issue #831070: PostgreSQL breaks on forums with IF() syntax.

Comments

Can confirm the more

Can confirm the more interdatabase possibility of CASE with Oracle databases. Oracle does not support IF () operator in SQL, only in PL/SQL (look for if syntax of PL/SQL IF here: http://www.techonthenet.com/oracle/loops/if_then.php)

About this page

Audience
Developers and coders

Develop for Drupal

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.
nobody click here