title: GROUP BY in Postgres - no equality for JSON data type?
body: <p>I have the following data in a matches table:</p>
  
  <pre><code>5;{"Id":1,"Teams":[{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
  6;{"Id":2,"Teams":[{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
  </code></pre>
  
  <p>I want to select each last distinct Team in the table by their name. i.e. I want a query that will return:</p>
  
  <pre><code>6;{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}
  6;{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}
  </code></pre>
  
  <p>So each team from last time that team appears in the table.<br>
  I have been using the following (from <a href="https://stackoverflow.com/a/18061451/3036134">here</a>):</p>
  
  <pre><code>WITH t AS (SELECT id, json_array_elements(match-&gt;'Teams') AS team FROM matches)
  SELECT MAX(id) AS max_id, team FROM t GROUP BY team-&gt;'Name';
  </code></pre>
  
  <p>But this returns:</p>
  
  <blockquote>
  <pre><code>ERROR: could not identify an equality operator for type json
  SQL state: 42883
  Character: 1680
  </code></pre>
  </blockquote>
  
  <p>I understand that Postgres <a href="https://stackoverflow.com/questions/23509740/distinct-on-postgresql-json-data-column">doesn't have equality for JSON</a>. I only need equality for the team's name (a string), the players on that team don't need to be compared.</p>
  
  <p>Can anyone suggest an alternative way to do this?<br>
  For reference:</p>
  
  <pre><code>SELECT id, json_array_elements(match-&gt;'Teams') AS team FROM matches
  </code></pre>
  
  <p>returns:</p>
  
  <pre><code>5;"{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]}"
  5;"{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}"
  6;"{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]}"
  6;"{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}"
  </code></pre>
  
  <p><strong>EDIT</strong>: I cast to <code>text</code> and following <a href="https://stackoverflow.com/a/19723716/3036134">this question</a>, I used <code>DISTINCT ON</code> instead of <code>GROUP BY</code>. Here's my full query:</p>
  
  <pre><code>WITH t AS (SELECT id, json_array_elements(match-&gt;'Teams') AS team
             FROM matches ORDER BY id DESC)
  SELECT DISTINCT ON (team-&gt;&gt;'Name') id, team FROM t;
  </code></pre>
  
  <p>Returns what I wanted above. Does anyone have a better solution?</p>