MOCKSTACKS
EN
Questions And Answers

More Tutorials









postgreSQL JSON Support

Examples

Creating a pure JSON table


To create a pure JSON table you need to provide a single field with the type JSONB:

CREATE TABLE mytable (data JSONB NOT NULL);

You should also create a basic index:

CREATE INDEX mytable_idx ON mytable USING gin (data jsonb_path_ops);

At this point you can insert data in to the table and query it efficiently.

Querying complex JSON documents


Taking a complex JSON document in a table:

CREATE TABLE mytable (data JSONB NOT NULL);
CREATE INDEX mytable_idx ON mytable USING gin (data jsonb_path_ops);
INSERT INTO mytable VALUES($$
{
 "name": "Alice",
 "emails": [
 "alice1@test.com",
 "alice2@test.com"
 ],
 "events": [
 {
 "type": "birthday",
 "date": "1970-01-01"
 },
 {
 "type": "anniversary",
 "date": "2001-05-05"
 }
 ],
 "locations": {
 "home": {
 "city": "London",
 "country": "United Kingdom"
 },
"work": {
 "city": "Edinburgh",
 "country": "United Kingdom"
 }
 }
}
$$);

Query for a top-level element:

SELECT data->>'name' FROM mytable WHERE data @> '{"name":"Alice"}';

Query for a simple item in an array:

SELECT data->>'name' FROM mytable WHERE data @> '{"emails":["alice1@test.com"]}';

Query for an object in an array:

SELECT data->>'name' FROM mytable WHERE data @> '{"events":[{"type":"anniversary"}]}';

Query for a nested object:

SELECT data->>'name' FROM mytable WHERE data @> '{"locations":{"home":{"city":"London"}}}';


Conclusion

In this page (written and validated by ) you learned about postgreSQL JSON Support . What's Next? If you are interested in completing postgreSQL tutorial, your next topic will be learning about: postgreSQL Performance of compared.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.