Re: Create table if not exists ... how ??

From: Said Ramirez <sramirez(at)vonage(dot)com>
To: Jennifer Trey <jennifer(dot)trey(at)gmail(dot)com>
Cc: Joe Conway <mail(at)joeconway(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Create table if not exists ... how ??
Date: 2010-07-19 17:53:58
Message-ID: 4C449136.4070007@vonage.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Assuming you know the schema name, you could always check the catalog table, something like
select count(*) from pg_tables where schemaname= 'foo' and tablename='bar'
If it returns, then you know a table by the name foo.bar exists. if not you can create it.
-Said

Jennifer Trey wrote:
> No.... I don't want to drop it ... there is valuable data in there! I only
> want to create it if it doesn't already exist... likely going to happen
> first time the application will run. I want to create the table then and
> populate. But not the next time.
>
> Should I just let Java throw and exception and catch it ? Write a function
> for this would be optimal, although I have no idea what the correct syntax
> is.
>
> Cheers, Jen
>
>
>
> On Mon, Jul 19, 2010 at 5:58 PM, Joe Conway <mail(at)joeconway(dot)com> wrote:
>
>> On 07/19/2010 09:33 AM, Jennifer Trey wrote:
>>> I can't figure out the correct syntax...
>>>
>>> I have this, but it just keeps complaining about the IF
>>>
>>> IF NOT EXISTS (SELECT table_name FROM information_schema.tables where
>>> table_name = 'post_codes')
>>>
>>> THEN
>>>
>>> CREATE TABLE post_codes
>> Probably better to do:
>>
>> DROP TABLE IF EXISTS post_codes;
>> CREATE TABLE post_codes(...);
>>
>> See:
>> http://www.postgresql.org/docs/8.4/interactive/sql-droptable.html
>>
>> HTH,
>>
>> Joe
>>
>> --
>> Joe Conway
>> credativ LLC: http://www.credativ.us
>> Linux, PostgreSQL, and general Open Source
>> Training, Service, Consulting, & 24x7 Support
>>
>>
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message EllisGL 2010-07-19 17:54:40 Re: NASA needs Postgres - Nagios help
Previous Message EllisGL 2010-07-19 17:48:00 Re: NASA needs Postgres - Nagios help