Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DISTINCT ON column only for non null values

How should I declare a query to only use DISTINCT on not null values for certain column but still keep the records for which the column value is null, I'm trying to modify the following query:

I'm trying to modify the following query,

distinct

So, basically I want the second query to return all the messages grouped by parent_id when the parent_id column IS NOT NULL and return ALL the records when parent_id IS NULL.

I'm using PG 9.0.4 and Rails 3.1 - any help would be appreciated, thanks!

like image 905
jpemberthy Avatar asked Nov 23 '11 01:11

jpemberthy


1 Answers

   Select Distinct ON (parent_id) * 
   from messages 
   WHERE parent_id IS NOT NULL 
 UNION 
   Select * from messages where parent_id IS NULL
like image 185
Adithya Surampudi Avatar answered Oct 13 '22 06:10

Adithya Surampudi