SHV chat bench

Postgres Query for JSON Type in TableColumn Objects

  • system:

    You are ChatGPT, a large language model trained by OpenAI. Follow the user's instructions carefully. Respond using markdown.

  • user:

    I have a postgres table named "TableDefinitions" with a jsonb column named "schema" that contains an array TableColumn objects.

    interface TableColumn {
      id: string
      name: string
      type: string
      sort?: "asc" | "desc"
      order?: number
      hidden?: boolean
      permissions?: TableColumnPermissions[]

    I need a sql query that will return all of the tables that match type = "json" in the schema json array.

  • assistant:

    To select all records where the type field inside the TableColumn object is equal to 'json', Postgres JSON functions can be used to traverse the nested elements. Let's assume that the TableColumn objects are stored inside an array in the schema column.

    Here's an example of a SQL query:

    SELECT *
    FROM "TableDefinitions"
        SELECT 1
        FROM jsonb_array_elements("schema") AS "TableColumn"
        WHERE "TableColumn"->>'type' = 'json'


    • jsonb_array_elements("schema"): The jsonb_array_elements function is used to expand each item within the 'schema' array, allowing us to access the properties of each 'TableColumn' object.
    • "TableColumn"->>'type': The '->>' operator extracts a JSON field as TEXT. So "TableColumn"->>'type' gives us the value of the 'type' field in text format.
    • WHERE "TableColumn"->>'type' = 'json': This will filter all 'TableColumn' rows where 'type' is set to 'json'. If at least one row matches this condition, the EXISTS clause returns true and the parent TableDefinitions row is selected in the main query.

    Make sure that your Postgres version is >= 9.3, as JSON support was added starting from this version. Going forward, ensure also that you store your JSON field in jsonb format, which is binary and allows indexing, unlike the json format.

    Remember to replace "TableDefinitions" and "schema" with their actual case if your table or column names are case sensitive. In PostgreSQL, unquoted names are case-insensitive.