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

Last updated on
8 September 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

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.

Help improve this page

Page status: No known problems

You can: