Re: Checking for table existence

From: Roberto Mello <rmello(at)cc(dot)usu(dot)edu>
To: Julester <cubalibr(at)optonline(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Checking for table existence
Date: 2001-09-18 00:12:29
Message-ID: 20010917181229.A9170@cc.usu.edu
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Fri, Sep 14, 2001 at 06:58:29PM +0000, Julester wrote:
> Hi everyone. In my old SQL Server days, I used a command such as "IF
> exists(select name from sys_objects where name = 'xyztable')" to check if a
> table existed before creating it with a standard CREATE command. I looked
> in the PostgreSQL documentation, but for the life of me, I can't find an
> equivalent. I can view if the table exists by doing a select against the
> meta-data tables, but what about the IF statement ? Any help would be
> greatly appreciated. Thanks.

You can have psql output its internal queries and that will give you
some insight:

roberto(at)brasileiro:~/documents/pictures$ psql -e foobar
Welcome to psql, the PostgreSQL interactive terminal.
...
foobar=# \d blah
********* QUERY *********
SELECT relhasindex, relkind, relchecks, reltriggers, relhasrules
FROM pg_class WHERE relname='blah'
*************************

********* QUERY *********
SELECT a.attname, format_type(a.atttypid, a.atttypmod), a.attnotnull,
a.atthasdef, a.attnum
FROM pg_class c, pg_attribute a
WHERE c.relname = 'blah'
AND a.attnum > 0 AND a.attrelid = c.oid
ORDER BY a.attnum
*************************

********* QUERY *********
SELECT substring(d.adsrc for 128) FROM pg_attrdef d, pg_class c
WHERE c.relname = 'blah' AND c.oid = d.adrelid AND d.adnum = 1
*************************

Table "blah"
Attribute | Type | Modifier
-----------+--------------------------+---------------
something | timestamp with time zone | default 'now'
name | character(50)


-Roberto
--
+------------| Roberto Mello - http://www.brasileiro.net |------------+
Computer Science, Utah State University - http://www.usu.edu
USU Free Software & GNU/Linux Club - http://fslc.usu.edu
Space Dynamics Lab, Developer - http://www.sdl.usu.edu
OpenACS - Enterprise free web toolkit - http://openacs.org
Blood is thicker than water, and much tastier.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Lee Harr 2001-09-18 00:37:46 Re: How to see the definition of an existing table?
Previous Message Pasha 2001-09-17 18:49:12 Stored prosedure last run