Het hangt af van wat je precies wilt testen.
Information schema?
Om te achterhalen "of de tabel bestaat" (wie er ook vraagt), is het queryen van het information schema (information_schema.tables) strikt genomen onjuist, omdat (volgens de documentatie) alleen de tabellen en views worden getoond waar de huidige gebruiker toegang tot heeft. De query beantwoordt dus eigenlijk: Hoe controleer ik of een tabel (of view) bestaat én de huidige gebruiker er toegang tot heeft?
SELECT EXISTS ( SELECT FROM information_schema.tables WHERE table_schema = 'schema_name' AND table_name = 'table_name' ); Systeemcatalogen
Je vraag was: Hoe controleer ik of een tabel bestaat?
SELECT EXISTS ( SELECT FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'schema_name' AND c.relname = 'table_name' AND c.relkind = 'r' -- only tables ); Gebruik de systeemcatalogen pg_class en pg_namespace rechtstreeks, wat ook aanzienlijk sneller is. Voor deze specifieke vraag kun je ook de systeemview pg_tables gebruiken:
SELECT EXISTS ( SELECT FROM pg_tables WHERE schemaname = 'schema_name' AND tablename = 'table_name' ); Alternatief: cast naar regclass
SELECT 'schema_name.table_name'::regclass Dit gooit een uitzondering als de (optioneel schema-kwalificerende) tabel niet bestaat. Zonder schema-kwalificatie valt de cast standaard terug op de search_path.
to_regclass(rel_name) in Postgres 9.4+
Veel eenvoudiger nu:
SELECT to_regclass('schema_name.table_name'); Hetzelfde als de cast, maar het geeft ...
... null terug in plaats van een fout te gooien als de naam niet wordt gevonden