-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_json_sql.sql
More file actions
78 lines (55 loc) · 2.01 KB
/
init_json_sql.sql
File metadata and controls
78 lines (55 loc) · 2.01 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
-- Create super user.
CREATE ROLE testuser LOGIN SUPERUSER PASSWORD 'testpassword';
-- Create table after check.
DROP TABLE IF EXISTS example;
CREATE TABLE example (
id INT,
json_col JSON,
json_array_col JSON,
jsonb_col JSONB,
jsonb_array_col JSONB
);
-- Insert values into table.
INSERT INTO example VALUES (1,
'[1,2,3]'::json,
'[{"id": 0, "name": "a"},{"id": 1, "name": "a"},{"id": 2, "name": "c"}]'::json,
'[1,2,3]'::jsonb,
'[{"id": 0, "name": "a"},{"id": 1, "name": "a"},{"id": 2, "name": "c"}]'::jsonb
);
-- queries
SELECT * FROM example;
-- insert via json
INSERT INTO example VALUES (2,
'[1,2,3]'::json,
'[{"id": 0, "name": "a"},{"id": 1, "name": "a"},{"id": 2, "name": "c"}]'::json,
'[1,2,3]'::jsonb,
'[{"id": 0, "name": "a"},{"id": 1, "name": "a"},{"id": 2, "name": "c"}]'::jsonb
);
INSERT INTO example
SELECT id, json_col, json_array_col, jsonb_col, jsonb_array_col
FROM json_populate_record (NULL::example,
'{
"id": 3,
"json_col": {"name": "bob", "age": 111},
"json_array_col": [{"id": 0, "name": "a"},{"id": 1, "name": "a"},{"id": 2, "name": "c"}],
"jsonb_col": {"name": "sarah", "age": 2222},
"jsonb_array_col": [{"id": 0, "name": "a"},{"id": 1, "name": "a"},{"id": 2, "name": "c"}]
}'
);
-- query into json array
SELECT arr -> 'id' AS json_id, arr -> 'name' AS json_name
FROM example e, json_array_elements(e.json_array_col) arr
WHERE (arr ->> 'id')::int > -1;
-- query json column
SELECT json_col::json ->> 2 FROM example;
SELECT json_col -> 'age' FROM example;
SELECT json_col -> 'age' AS json_age FROM example WHERE (json_col ->> 'age')::int = 111;
-- query into jsonb array
SELECT arr -> 'id' AS json_id, arr -> 'name' AS json_name
FROM example e, jsonb_array_elements(e.jsonb_array_col) arr
WHERE (arr ->> 'id')::int > -1;
-- query jsonb column
SELECT jsonb_col::json ->> 2 FROM example;
SELECT jsonb_col -> 'age' FROM example;
SELECT jsonb_col -> 'name' AS jsonb_name, jsonb_col -> 'age' AS jsonb_age
FROM example WHERE (jsonb_col ->> 'name') = 'sarah';