Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Create table if not exists" - how to check the schema, too?

Is there a (more or less) standard way to check not only whether a table named mytable exists, but also whether its schema is similar to what it should be? I'm experimenting with H2 database, and

CREATE TABLE IF NOT EXISTS mytable (....)

statements apparently only check for the table´s name. I would expect to get an exception if there's a table with the given name, but different schema.

like image 711
Joonas Pulakka Avatar asked Mar 19 '10 12:03

Joonas Pulakka


People also ask

How do you check if a table exists in a schema?

How to check whether a table (or view) exists, and the current user has access to it? SELECT EXISTS ( SELECT FROM information_schema. tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' ); The information schema is mainly useful to stay portable across major versions and across different RDBMS.


2 Answers

SELECT  *
FROM    INFORMATION_SCHEMA.TABLES
WHERE   TABLE_NAME      = 'TableName'
    AND TABLE_SCHEMA    = 'public'
like image 51
isapir Avatar answered Oct 24 '22 08:10

isapir


CREATE TABLE IF NOT EXISTS ... is not a standard SQL code.

The thing to do is to check if the table is already in the catalogue. For instance, in Java you may do something like: connection.getMetaData().getTables(connection.getCatalog(), null, null, null)

For more info see javadoc java.sql.Connection.

like image 43
Kru Avatar answered Oct 24 '22 08:10

Kru