Re: SQL question

From: Philip Warner <pjw(at)rhyme(dot)com(dot)au>
To: Carolyn Lu Wong <carolyn(at)kss(dot)net(dot)au>
Cc: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: SQL question
Date: 2000-07-17 04:11:52
Message-ID: 3.0.5.32.20000717141152.022dd100@mail.rhyme.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

At 13:41 17/07/00 +1000, Carolyn Lu Wong wrote:
>> Try
>> select count(*) from table1 where account_no = 1 and start_date_time is
>> null;
>>
>> and see if you get 0.
>
>Yes, i get 0 from running the above query, but it fails if i re-arrange
>the where clause to:
>
> select * from table1
> where start_date_time::date >= '01/01/2000'::date
> and start_date_time::date <= '01/01/2001'::date
> and account_no = 1;
>
>with the same error message.
>

I think that there is no guarantee of the order of evaluation of the
components of a predicate, but that putting 'account_no=1' early in the
statement means the row is excluded before it needs to evaluate the rest of
the statement. I don't think you should rely on this behaviour - it might
be classified as "it's a feature, not a bug". Maybe.

You probably need to tell me what NULLs in the start_date mean. If, eg,
they mean 'not started', then you could create a view:

create view started_things as select * from table1 where not start_date
is null;

then use:

select * from started_things
where start_date_time::date >= '01/01/2000'::date
and start_date_time::date <= '01/01/2001'::date
and account_no = 1;

AFAICT, this will still use nice indexes etc, but I could be wrong.

Another alternative would be to define a 'coalesce' function (I don't think
PG has one), which takes an arbitrary number of arguments and returns the
first non-null one. You could then say "where coalesce(start_date_time,
'1/1/1500')::date >= '01/01/2000'::date" etc, but then I think you will
lose the effectiveness of indexes.

Maybe someone else has a better idea...

----------------------------------------------------------------
Philip Warner | __---_____
Albatross Consulting Pty. Ltd. |----/ - \
(A.C.N. 008 659 498) | /(@) ______---_
Tel: (+61) 0500 83 82 81 | _________ \
Fax: (+61) 0500 83 82 82 | ___________ |
Http://www.rhyme.com.au | / \|
| --________--
PGP key available upon request, | /
and from pgp5.ai.mit.edu:11371 |/

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2000-07-17 05:48:48 Re: SQL question
Previous Message Carolyn Lu Wong 2000-07-17 03:41:38 Re: SQL question