title: How to Distinct on particular column in JPA (Criteria Builder)
body: <p>I have written JPA code for Distinct in inner query, below is my JPA code</p>
  
  <pre><code>CriteriaBuilder cb = entityManager_gbl.getCriteriaBuilder();
  CriteriaQuery&lt;sourceTracking&gt; cq = cb.createQuery(sourceTracking.class);
  Root&lt;sourceTracking&gt; data1 = cq.from(sourceTracking.class);
  Subquery&lt;String&gt; subq=cq.subquery(String.class);
  Root&lt;sourceTracking&gt; sbf=subq.from(sourceTracking.class);
  subq.select(sbf.&lt;String&gt;get("message_id")).distinct(true);
  cq.where(data1.&lt;String&gt;get("tablekey").in(subq));
  cq.select(data1);
  </code></pre>
  
  <p>This code is generating SQL query is</p>
  
  <pre><code>select * 
  from source_tracking 
  where tablekey in (select distinct message_id from source_tracking )
  </code></pre>
  
  <p>But my requirement is here, distinct is applied to message_id, but fetching tablekey.  </p>
  
  <pre><code>select * 
  from source_tracking 
  where tablekey in (select distinct on (message_id) tablekey 
                     from source_tracking)
  </code></pre>