Re: EXISTS - Mailing list pgsql-sql

From Craig Ringer
Subject Re: EXISTS
Date
Msg-id 48F44ED1.2010402@postnewspapers.com.au
Whole thread Raw
In response to EXISTS  (Denis Woodbury <denis@woodmic.net>)
List pgsql-sql
Denis Woodbury wrote:
> Hi,
> 
> I would like to know if this this type of statement can be used in
> Postgresql
> 
> IF NOT EXISTS (SELECT 1 FROM Table WHERE col1 = 'mystring' )
> BEGIN
> ...
> END

PostgreSQL doesn't have any sort of free block flow control; it doesn't 
have an IF statement or similar in SQL. You can usually just create a 
PL/PgSQL function to do what you want.

It'd occasionally be nice to be able to write PL/PgSQL bodies in-line in 
SQL code rather than explicitly creating then dropping a function when 
you do need to do something a bit weird (usually in admin/maintenance 
scripts) but the current approach does work fine.

It also helps that you can often achieve the required logic with plain, 
standard SQL. The CASE statement is particularly useful:

SELECT  CASE    WHEN col1 = 'mystring' THEN [expression or function call]  END
FROM Table;

--
Craig Ringer


pgsql-sql by date:

Previous
From: "Christopher Maier"
Date:
Subject: Re: Order of trigger execution: AFTER DELETE ON EACH ROW doesn't appear to be working properly
Next
From: Denis Woodbury
Date:
Subject: Re: EXISTS