Re: Novice SQL Question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Terry Lee Tucker <terry(at)esc1(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Novice SQL Question
Date: 2004-02-03 03:14:02
Message-ID: 10684.1075778042@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Terry Lee Tucker <terry(at)esc1(dot)com> writes:
> If I put this where I thought it should go as in:
> select distinct event_code,level from logs join stat on (stat.prime is not
> null) where order_num = 130680 order by event_date,event_time,event_secs;

> I get the following error:
> ERROR: For SELECT DISTINCT, ORDER BY expressions must appear in target list

Right. Think about what SELECT DISTINCT does: it combines all rows with
the same values of event_code and level into a single row. The group of
rows with a particular pair of event_code/level might contain many
different values of event_date etc. Which of these values should be
used to sort the combined row? The result just isn't well-defined in
general. You need to alter the query so that it completely defines
the result you want. One way to do that is suggested by the error
message: add the ORDER BY columns into the DISTINCT list. But that's
not necessarily the way that will get the result you want.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Russell Shaw 2004-02-03 06:28:15 Outer join
Previous Message Terry Lee Tucker 2004-02-02 23:00:32 Re: Novice SQL Question