Skip to content
Advertisement

What’s the best way to “append” to a list of strings stored in a JSONB column in a table PostgreSQL such that duplicates are not stored

Say there is a table employee

One of the rows has the following information in the tags column

Currently to update the column with additional values I perform the following query

However this adds duplicates to the cell and makes it look like

which is less than desirable for my use case. Currently to circumvent this I’ve handled duplicates in post-processing at the application layer.

Is there an efficient way to remove duplicates like “TagA” at runtime?

Advertisement

Answer

You can use jsonb_agg with distinct in a subquery:

See fiddle.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement