Skip site navigation (1) Skip section navigation (2)

Re: ORDER BY and NULLs

From: T E Schmitz <mailreg(at)numerixtechnology(dot)de>
To: Jean-Luc Lachance <jllachan(at)sympatico(dot)ca>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: ORDER BY and NULLs
Date: 2004-09-19 16:36:36
Message-ID: 414DB594.5000300@numerixtechnology.de (view raw or flat)
Thread:
Lists: pgsql-sql
Hello Jean-Luc,
You must've been reading my mind. I was just wondering what to do about 
indexing on that particular table. I read somewhere that an Index is not 
going to improve the performance of an ORDER BY if the sort column 
contains NULLs because NULLs aren't indexed?

For the sake of the example I had simplified matters a wee bit. What I 
really have is:

SELECT * FROM PRODUCT ORDER BY NAME, FROM, TO, FROM2, TO2

FROM, TO, FROM2, TO2 might be NULL. If FROM is NULL, TO will be NULL. If 
FROM2 is NULL, TO2 will be NULL.

How would you index this table?

Kind regards,
Tarlika

Jean-Luc Lachance wrote:

> select ... order by "FROM" is not null, "FROM";
> 
> If you have large amount of rows (with or without nulls) it is faster if 
> use a partial index.
> 
> create index ... on ...("FROM");
> create index ... on ...("FROM") where "FROM" is null;
> 
> 
> JLL
> 
> 
> terry(at)ashtonwoodshomes(dot)com wrote:
> 
>> Use the coalesce() function.  (coalesce returns the first non-null 
>> value in its list)
>>
>> Specifically
>>
>> ORDER BY coalesce("TO", 0), "FROM"
>>
>> If you have records in "TO" column whose values is LESS then 0, then 
>> you need to replace 0 with
>> something that sorts BEFORE the first most value that your TO result 
>> can return.
>>
>> Terry Fielder
>> Manager Software Development and Deployment
>> Great Gulf Homes / Ashton Woods Homes
>> terry(at)greatgulfhomes(dot)com
>> Fax: (416) 441-9085
>>
>>
>>
>>> -----Original Message-----
>>> From: pgsql-sql-owner(at)postgresql(dot)org
>>> [mailto:pgsql-sql-owner(at)postgresql(dot)org]On Behalf Of T E Schmitz
>>> Sent: Sunday, September 19, 2004 10:58 AM
>>> To: pgsql-sql(at)postgresql(dot)org
>>> Subject: [SQL] ORDER BY and NULLs
>>>
>>>
>>> Hello,
>>>
>>> I am using PostgreSQL 7.4.2 and as I understand NULL values
>>> always sort
>>> last.
>>>
>>> However, I have a table from which select using two numerical
>>> sort keys
>>> "FROM" and "TO". "TO" might be NULL and I would like to display those
>>> rows first (without sorting the column in descending order).
>>>
>>> Is there any way this can be achieved without inserting bogus values
>>> into that column?
>>>
>>> -- 
>>>
>>>
>>> Regards/Gruß,
>>>
>>> Tarlika Elisabeth Schmitz

In response to

Responses

pgsql-sql by date

Next:From: Andrew SullivanDate: 2004-09-19 16:57:48
Subject: Re: How to check postgres running or not ?
Previous:From: Tom LaneDate: 2004-09-19 16:25:00
Subject: Re: How to check postgres running or not ?

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group