Re: order by date desc but NULLs last

From: Jean-Luc Lachance <jllachan(at)nsd(dot)ca>
To: "Ross J(dot) Reedstrom" <reedstrm(at)rice(dot)edu>
Cc: "A(dot)M(dot)" <agentm(at)cmu(dot)edu>, pgsql-sql(at)postgresql(dot)org
Subject: Re: order by date desc but NULLs last
Date: 2003-02-10 18:32:54
Message-ID: 3E47F056.DE8707E2@nsd.ca
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Why not try the obvious first?

order by gradedtime is null, gradedtime desc;

"Ross J. Reedstrom" wrote:
>
> On Sun, Feb 09, 2003 at 05:29:29PM -0500, A.M. wrote:
> > I have a simple query that sorts by descending date but the NULL dates
> > show up first. Is there a way I can sort so they come last without
> > sorting ascending?
> >
> > SELECT submittime,score,gradedtime FROM student_gradedmaterial WHERE
> > gradedmaterialid=3 and studentid=102 order by gradedtime desc;
> >
> > submittime | score | gradedtime
> > ---------------------+-------+----------------------------
> > 2003-01-30 22:56:38 | |
> > 2003-01-31 03:42:29 | 99 | 2003-02-06 14:21:43.043587
> >
> > but what I want is all the graded items first in gradedtime desc and
> > NULL afterwards. I do need to keep the NULL score rows. (So I get the
> > latest submitted grade for the assignment but also any ungraded
> > submission information.)
>
> You need to ORDER BY a _function_ of the gradedtime column, substituting
> an extreme value for NULL. Try this:
>
> SELECT submittime,score,gradedtime FROM student_gradedmaterial
> WHERE gradedmaterialid=3 and studentid=102 order by
> coalesce(gradedtime,'-infinity') desc;
>
> Ross
>
> ---------------------------(end of broadcast)---------------------------
> TIP 3: if posting/reading through Usenet, please send an appropriate
> subscribe-nomail command to majordomo(at)postgresql(dot)org so that your
> message can get through to the mailing list cleanly

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Ross J. Reedstrom 2003-02-10 18:52:44 Re: order by date desc but NULLs last
Previous Message Tom Lane 2003-02-10 18:21:25 Re: problems with date and interval queries.