LoginSignup
9
4

More than 5 years have passed since last update.

PostgreSQLのJSONB型のときにJSON内部の値でソートする方法

Last updated at Posted at 2018-01-31

条件

productsテーブルの、product_typesカラムがJSONBであるとき、product_types内にあるJSONが、


[{"name": "awesome", "line_number": 1}]

という形式のとき、この line_number でソートする。product_types内のJSONが配列以外の場合も考慮する。

SQL

SELECT id, product_types
FROM products
ORDER BY
    CASE
        WHEN jsonb_typeof(product_types) = 'array'
        THEN jsonb_array_elements(product_types)->>'line_number'
        ELSE NULL
    END ASC;
9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4