Query goal: | "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 about the query: | The query finds columns of base tables that have json type instead of jsonb type. |
Query type: | Problem detection (Each row in the result could represent a flaw in the design) |
Query reliability: | High (Few or no false-positive results) |
Query license: | MIT License |
Fixing suggestion: | 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: | Click on query to copy it
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 query | 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. |
Collection name | Collection 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 . |
Category name | Category 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. |