Search code examples
sqljsonpostgresqljsonb

What would be the SQL query to delete an entry from postgres table using 2 identifiers?


The below JSON payload is an entry in one of the column of the postgres table. The query to delete one of the player is:

UPDATE site_content
   SET content =   
       content #- 
       COALESCE(('{playersContainer,players,' ||
                (SELECT i
                   FROM generate_series(0,
                                        jsonb_array_length(content - >
                                        'playersContainer' - >
                                        'players') - 1) AS i
                  WHERE (content - > 'playersContainer' - >
                                     'players' - > i - > 'id' = '"1"')
                 ) || '}'
                 )::text [ ],'{}');

What would be the query if we want to delete one of the value from the "ratings" list? For instance, we want to delete rating=1 of a player with id=1

JSON payload:

{
  "playersContainer": {
    "players": [
      {
        "id": "1",
        "name": "Nick",
        "teamName": "Shire Soldiers",
        "ratings": [
          1,
          5,
          6,
          9
        ],
        "assists": 17,
        "manOfTheMatches": 20,
        "cleanSheets": 1,
        "data": [
          3,
          2,
          3,
          5,
          6
        ],
        "totalGoals": 19
      }
    ]
  }
}

Solution

  • I already tested, the following code is working.

    update a1 set data =
        data #- '{playersContainer,players,0,ratings,0}'
    where ( 
    select  (data['playersContainer']['players'])[0]['id'] ? '1' from a1)
        is true;
    

    DB fiddle