URL: http://www.vitavoom.com/postgresql-docs/catalog-pg-class.html

I just learnt a better way to check if a PostgreSQL table exists. Before I did this to find out if table mytable is defined:


SELECT * FROM 'mytable' LIMIT 1;

But this had to be wrapped in exception catching application code because I was able to tell if the table existed if the select statement worked. That's the wrong and naive way. The correct way is to use pg_class and look at how many rows were returned:


SELECT relname FROM pg_class 
WHERE relname = 'mytable';

Why have I missed this before? No explanation?

A disadvantage with using pg_class is that it's not ISO standard, meaning that it's specific to PostgreSQL only. The first pattern will work on all relational databases.

Comments

Ian Bicking

In psql do "\set ECHO_HIDDEN t" and you can see all the queries it uses for the special backslash commands (like \d)

dd

For functionality similar to mysql SHOW TABLES use: select * from information_schema.tables where table_schema='public' and table_type='BASE TABLE' .

toruvinn

btw. there's a problem with temporary tables, cause they might not be visible (even though they exist). it's better to use:
SELECT 1 FROM pg_catalog.pg_class WHERE relkind = 'r' AND relname = 'name' AND pg_catalog.pg_table_is_visible(oid) LIMIT 1

Peter Bengtsson

Thanks!

Your email will never ever be published.

Previous:
Google blogs about their Maps April 19, 2005 Misc. links
Next:
Serious flaw in Bose headphones April 23, 2005 Music
Related by category:
set -ex - The most useful bash trick of the year August 31, 2014 Linux
brotli_static in Nginx November 8, 2024 Linux
Be very careful with your add_header in Nginx! You might make your site insecure February 11, 2018 Linux
Linux tip: du --max-depth=1 September 27, 2007 Linux
Related by keyword:
Adding client-to-server sync to PissueTracker March 20, 2025 React, JavaScript, Bun
Select all relations in PostgreSQL December 10, 2015 PostgreSQL
Chainable catches in a JavaScript promise November 5, 2015 Web development, JavaScript
Connecting with psycopg2 without a username and password February 24, 2011 Python