UNION したクエリで ORDER BY + CASE WHEN する

備忘録。

UNION したクエリで ORDER BY する。さらに ORDER BY 句で CASE WHEN するパターン。使い道があるかは分かりませんが。

SELECT * FROM (
  SELECT
    t.id AS t_id, t.name AS t_name, t.order AS t_order
  FROM
    table AS t
  WHERE
    ... (略)
  UNION
  SELECT
    t.id AS t_id, t.name AS t_name, t.order AS t_order
  FROM
    table AS t
  WHERE
    ... (略)
) AS uniontable
ORDER BY
  CASE WHEN uniontable.t_order IS NULL THEN 1 ELSE 0 END ASC, uniontable.t_order ASC,
  uniontable.t_id ASC