Distinct on Postgresql JSON data column

The reason behind this, is that in PostgreSQL (up to 9.3) there is no equality operator defined for json (i.e. val1::json = val2::json will always throw this exception) — in 9.4 there will be one for the jsonb type.

One workaround is, you can cast your json field to text. But that won’t cover all json equalitions. f.ex. {"a":1,"b":2} should be equal to {"b":2,"a":1}, but won’t be equal if casted to text.

Another workaround is (if you have a primary key for that table — which should be) you can use the DISTINCT ON (<expressions>) form:

u.profiles.select("DISTINCT ON (profiles.id) profiles.*")

Note: One known caveat for DISTINCT ON:

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)