Postgres Query examples


1. Search inside json data that contains a key which is array.

e.g Json data stored in table (sports) column (json_data). The column "json_data" type is json

{
  "id": "112",
  "name": "testName",
  "sports": [
    {
      "id": "1",
      "sportName": "football"
    },
    {
      "id": "2",
      "sportName": "cricket"
    }
  ]
}

SQL Query :

SELECT * FROM   public.sports r, json_array_elements((r.json_data -> 'sports')::json) obj
WHERE  obj->>'sportName' = 'football' ;


2. Update sequence value in existing sequence


e.g "sports_id_seq" is a sequence name

SQL Query :

SELECT setval('sports_id_seq', 21, true);

3.Print message in a procedure or function


e.g When debugging we need to print some data use below statement

SQL Statement :

RAISE NOTICE ' sections %', column_value;
Output : sections 20