Re: Do it exist?

From: Rod Taylor <rbt(at)rbt(dot)ca>
To: Hal Davison <hal(at)faams(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Do it exist?
Date: 2003-08-17 02:47:22
Message-ID: 1061088440.39706.93.camel@jester
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

> In another language I would do:
> find first Order where Order.Order_num = "1111".
> if avaialble Order then it_exists = true.
>
> In PostgreSQL ?:
> SELECT DISTINCT Order_num from Order_header where Order_num = '1111';
>
> Is this close? If so, how to raise flage that row exists?
>
>
> How we do somthing like this in SQL?

Since you don't care about a value, just pull TRUE and use LIMIT to
restrict to a single entry (much faster than DISTINCT, but not as
portable).

SELECT TRUE FROM Order_header where Order_num = '1111' LIMIT 1;

Do a count of the number of rows returned. 1 row means it exists, 0
rows means it does not exist.

It seems to me like you intend to insert a row with that number shortly
after? You should be aware that this process will introduce a race
condition (may not exist during test, but does exist shortly after
during insert).

If Order_num is Distinct on that table (or another), just try the
insert. If it fails, increment the number and try again. If you don't
mind gaps in the numbers, then a sequence will fare much better (easier
and faster).

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Richard Huxton 2003-08-17 10:32:58 Expression transformation curiosity
Previous Message Ian Barwick 2003-08-16 16:56:57 Re: Optional join