PostgreSQL Tutorial
Data Types
Querying & Filtering Data
Managing Tables
Modifying Data
Conditionals
Control Flow
Transactions & Constraints
Working with JOINS & Schemas
Roles & Permissions
Working with Sets
Subquery & CTEs
User-defined Functions
Important In-Built Functions
PostgreSQL PL/pgSQL
Variables & Constants
Stored Procedures
Working with Triggers
Working with Views & Indexes
Errors & Exception Handling
In PostgreSQL, JSON support was introduced in version 9.2, enabling users to store, query, and manipulate JSON data directly in the database. PostgreSQL provides two distinct data types for storing JSON data:
JSON
: Stores JSON data as plain text, verifying the input on insert/update. It doesn't offer a strong guarantee about preserving exact whitespace and ordering of keys.
JSONB
: Introduced in PostgreSQL 9.4, this binary format stores JSON data in a decomposed binary form. This format allows for faster searches and operations but takes slightly more storage space. It doesn't preserve white space, key order, or duplicate keys, but it does support indexing.
JSON Functions and Operators: PostgreSQL provides numerous built-in functions and operators to extract, modify, and create JSON data.
Indexing: You can build indexes on JSONB
columns using the Generalized Search Tree (Gin) index type, which speeds up search operations.
Validation: When inserting or updating data in a JSON
or JSONB
column, PostgreSQL ensures that the data is a valid JSON format.
Inserting JSON Data:
INSERT INTO your_table(json_column) VALUES ('{"key": "value"}');
Querying JSON Data:
Using the ->
operator to get JSON object at the specified key:
SELECT json_column->'key' FROM your_table;
Using the ->>
operator to get the JSON object at the specified key as text:
SELECT json_column->>'key' FROM your_table;
Searching Within JSON Data:
To find rows containing a specific key or value in a JSONB
column:
SELECT * FROM your_table WHERE json_column @> '{"key": "value"}';
Indexing JSON Data:
Create a Gin index on a JSONB
column:
CREATE INDEX index_name ON your_table USING gin(json_column);
If you need to perform many search operations on your JSON data, prefer the JSONB
type as it supports indexing, which can speed up queries significantly.
If you're only storing and retrieving JSON data and not performing many operations on it, the JSON
type might suffice.
Consider using native relational data structures in PostgreSQL unless you have a specific need for schema-less or dynamic attributes provided by the JSON format. Using native relational structures can provide better performance and more straightforward query patterns in many cases.
Take advantage of PostgreSQL's rich set of JSON functions and operators when working with JSON data. They can make querying and manipulating JSON data more efficient and expressive.
In summary, PostgreSQL's support for JSON data types provides flexibility in storing and querying semi-structured and dynamic data while still leveraging the advantages of a relational database.
How to create and use JSON columns in PostgreSQL:
CREATE TABLE example_table ( id SERIAL PRIMARY KEY, json_data JSON );
Inserting JSON data into PostgreSQL tables:
INSERT
statement.INSERT INTO example_table (json_data) VALUES ('{"key": "value"}');
Querying JSON data in PostgreSQL:
->
operator to query JSON data.SELECT json_data->'key' FROM example_table;
Using JSONB vs. JSON in PostgreSQL:
JSON
and JSONB
data types based on your needs. JSONB
is more efficient for indexing and querying.CREATE TABLE example_table ( id SERIAL PRIMARY KEY, json_data JSONB );
JSON functions and operators in PostgreSQL:
SELECT json_data->'key' AS extracted_value FROM example_table;
Aggregating data with JSON functions in PostgreSQL:
json_agg
.SELECT department_id, json_agg(employee_name) AS employees FROM employees GROUP BY department_id;
Modifying JSON data in PostgreSQL:
||
operator.UPDATE example_table SET json_data = json_data || '{"new_key": "new_value"}';
Querying nested JSON structures in PostgreSQL:
->
operator multiple times.SELECT json_data->'key'->'nested_key' FROM example_table;
Handling NULL values in JSON columns in PostgreSQL:
COALESCE
function to handle NULL values in JSON columns.SELECT COALESCE(json_data->'key', '{"default": "value"}') FROM example_table;
Comparing JSON values in PostgreSQL:
->>
for comparing JSON values.SELECT * FROM example_table WHERE json_data->>'key' = 'value';
Using JSON columns with foreign key relationships in PostgreSQL:
CREATE TABLE employees ( id SERIAL PRIMARY KEY, department_id INTEGER REFERENCES departments(department_id), employee_data JSON );
Using JSON columns in WHERE and HAVING clauses in PostgreSQL:
WHERE
and HAVING
clauses.SELECT * FROM example_table WHERE json_data->>'key' = 'value';
JSON and JOIN operations in PostgreSQL:
SELECT employees.employee_name, departments.department_name FROM employees JOIN departments ON employees.employee_data->>'department_id' = departments.department_id::TEXT;
Converting JSON to other data types in PostgreSQL:
SELECT (json_data->>'numeric_key')::NUMERIC FROM example_table;
Extracting data from JSON arrays and objects in PostgreSQL:
->
and ->>
operators.SELECT json_data->'array_key'->>0 FROM example_table;
Managing duplicates in JSON columns in PostgreSQL:
SELECT DISTINCT json_data->>'key' FROM example_table;
Working with JSONB indexes in PostgreSQL:
JSONB
columns for improved performance.CREATE INDEX idx_jsonb_key ON example_table USING GIN (json_data);