# Boolean 欄位排序 ORDER BY 筆記

PostgreSQL Boolean 欄位可能的值會有 true, false, null ,所以在用 ORDER BY 排序上會有一些小地方要注意。

# ASC false 會在前面

ASC false, true, null

select * from account order by is_admin asc

# DESC null 會在前面

DESC null, true, false

# 如果想要 true 排在前面加上 NULLS LAST

select * from account order by is_admin desc NULLS LAST

# 如果想要將 null 視為 false 用 COALESCE 轉

select * from account order by COALESCE(is_admin, FALSE) desc, name ASC

# 參考資料

postgresql - SQL for sorting boolean column as true, null, false - Stack Overflow (opens new window)

Last Updated: 2022-8-30 21:59:57
贊助商連結
    贊助商連結
    (adsbygoogle = window.adsbygoogle || []).push({});