Re: select IN problem

From: Andrew McMillan <andrew(at)catalyst(dot)net(dot)nz>
To: Doug Silver <dsilver(at)quantified(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: select IN problem
Date: 2002-02-22 21:55:21
Message-ID: 1014414921.3232.2399.camel@kant.mcmillan.net.nz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Sat, 2002-02-23 at 10:36, Doug Silver wrote:
> I've read the IN chapter in Bruce M.'s Postgresql book, but I still can't
> seem to get my select/IN to work. I have two tables, transactions and
> transactions_detail, with the transaction_id field as the reference in
> the transactions_detail table.
>
> # select transaction_id from transactions where enter_date> cast('2002-02-22' as date);
> transaction_id
> ----------------
> 2043
> 2044
> 2045
>
> purchases=# select transaction_id from transactions_detail where transaction_id>2042;
> transaction_id
> ----------------
> 2043
> 2044
> 2045
>
> purchases=# \d transactions_detail
> Table "transactions_detail"
> Attribute | Type | Modifier
> ----------------+-----------------------+----------
> transaction_id | smallint |
> products | character varying(20) |
> quantities | smallint |
>
> But the following query causes it to hang, after 10 seconds I finally stop
> it.
>
> purchases=# select transaction_id from transactions_detail where
> purchases=# transaction_id IN (
> purchases=# select transaction_id from transactions where enter_date> cast('2002-02-22' as date)
> purchases=# );
>
> Any suggestions?

SELECT td.transaction_id FROM transactions_detail td
WHERE EXISTS (SELECT transaction_id FROM transactions t
WHERE t.transaction_id = td.transaction_id
AND t.enter_date > CAST('2002-02-02' AS DATE );

Could well work better. The problem you are likely to be encountering
is that IN (...) will not use an index.

To see the query plans generated by the different SQL, use 'EXPLAIN <sql
command>' - it is _well_ worth coming to grips with what EXPLAIN can
tell you.

You could also be better with a plan that did a simple JOIN and
DISTINCT:

SELECT DISTINCT td.transaction_id
FROM transactions_detail td, transactions t
WHERE t.enter_date > '2002-02-02'
AND td.transaction_id = t.transaction_id;

Regards,
Andrew.
--
--------------------------------------------------------------------
Andrew @ Catalyst .Net.NZ Ltd, PO Box 11-053, Manners St, Wellington
WEB: http://catalyst.net.nz/ PHYS: Level 2, 150-154 Willis St
DDI: +64(4)916-7201 MOB: +64(21)635-694 OFFICE: +64(4)499-2267
Are you enrolled at http://schoolreunions.co.nz/ yet?

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Doug Silver 2002-02-22 21:57:26 Re: Question 7.1.3>>7.2
Previous Message Pam Wampler 2002-02-22 21:51:08 Question 7.1.3>>7.2