0

I need to write an update script that will check to see if certain tables, indexes, etc. exist in the database, and if not, create them. I've been unable to figure out how to do these checks, as I keep getting Syntax Error at IF messages when I type them into a query window in PgAdmin.

Do I have to do something like write a stored procedure in the public schema that does these updates using Pl/pgSQL and execute it to make the updates? Hopefully, I can just write a script that I can run without creating extra database objects to get the job done.

1
  • What kind of updates and what are you trying to check? Commented Mar 12, 2012 at 21:30

2 Answers 2

3

If you are on PostgreSQL 9.1, you can use CREATE TABLE ... IF NOT EXISTS

On 9.0 you can wrap your IF condition code into a DO block: http://www.postgresql.org/docs/current/static/sql-do.html

For anything before that, you will have to write a function to achieve what you want.

Sign up to request clarification or add additional context in comments.

Comments

1

Have you looked into pg_tables?

select * from pg_tables;

This will return (among other things) the schemas and tables that exist in the database. Without knowing more of what you're looking for, this seems like a reasonable place to start.

1 Comment

Actually, yes, I have looked into pg_tables. I'm using queries against this table (and others) to determine which changes need to be made to the database schema. The problem was I didn't know how to get my logic to work, as Postgres doesn't support IF statements unless they're in some sort of function. The DO block statement lets me build those IF statements and execute them. That's what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.