File: json_operators.sql

package info (click to toggle)
sqlfluff 3.5.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 34,000 kB
  • sloc: python: 106,131; sql: 34,188; makefile: 52; sh: 8
file content (38 lines) | stat: -rw-r--r-- 1,306 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
-- SQL from issue #2033
SELECT COALESCE(doc#>>'{fields}','') AS field
FROM mytable
WHERE doc ->> 'some_field' = 'some_value';

-- Get JSON array element (indexed from zero, negative integers count from the end)
SELECT '[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2;
-- Get JSON object field by key
SELECT '{"a": {"b":"foo"}}'::json->'a';
-- Get JSON array element as text
SELECT '[1,2,3]'::json->>2;
-- Get JSON object field as text
SELECT '{"a":1,"b":2}'::json->>'b';
-- Get JSON object at the specified path
SELECT '{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}';
-- Get JSON object at the specified path as text
SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}';

SELECT
    '{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb,
    '{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb,
    '{"a":1, "b":2}'::jsonb ? 'b',
    '{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'd'],
    '["a", "b", "c"]'::jsonb ?& array['a', 'b'],
    '["a", {"b":1}]'::jsonb #- '{1,b}',
    '{"a":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)',
    '{"a":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2';

SELECT json_object('code' VALUE 'P123', 'title': 'Jaws');

SELECT json_object(
        'word': CASE
            WHEN str = '1' THEN 'One'
            WHEN str = '2' THEN 'Two'
            ELSE 'Unknown'
        END
    ) AS json_column
FROM first_table;