"In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys." (https://www.postgresql.org/docs/current/datatype-json.html)
Notes
The query finds columns of base tables that have json type instead of jsonb type.
Type
Problem detection (Each row in the result could represent a flaw in the design)
In case of base table columns one can change the type of the column with an ALTER TABLE statement. If there are views that depend on the column, then these have to be dropped and later recreated.
Data Source
INFORMATION_SCHEMA only
SQL Query
SELECT table_schema, table_name, table_type, column_name
FROM INFORMATION_SCHEMA.columns INNER JOIN INFORMATION_SCHEMA.tables USING (table_schema, table_name)
WHERE data_type='json' AND
table_schema NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL)
AND table_type='BASE TABLE'
ORDER BY table_schema, table_name, ordinal_position;
SQL statements that help generate fixes for the identified problem.
SQL Query to Generate Fix
Description
WITH json_columns AS (SELECT table_schema, table_name, column_name, ordinal_position
FROM INFORMATION_SCHEMA.columns INNER JOIN INFORMATION_SCHEMA.tables USING (table_schema, table_name)
WHERE data_type='json' AND table_type='BASE TABLE' AND
table_schema NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL))
SELECT format('ALTER TABLE %1$I.%2$I ALTER COLUMN %3$I SET DATA TYPE JSONB;', table_schema, table_name, column_name) AS statements
FROM json_columns
ORDER BY table_schema, table_name, ordinal_position;
Change the type of the base table column.
Collections
This query belongs to the following collections:
Name
Description
Find problems automatically
Queries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .
Categories
This query is classified under the following categories:
Name
Description
Data types
Queries of this category provide information about the data types and their usage.
Hierarchical data
Queries of this catergory provide information about storing hierarchical data in the database.