Check if Table Exists in SQL

With SQL we can use various methods to check whether or not a table (or other object) exists in the database. The method we use will often depend on the RDBMS we’re using, as well as the task we’re trying to undertake.

There’s usually a reason we’re trying to check for the existence of a table, and often the syntax we use will be tied to that reason. For example the ...IF EXISTS clause is a handy addition to the DROP TABLE statement, and the ...IF NOT EXISTS clause can often be used with the CREATE TABLE statement.

Other times we may simply want to see if the table exists without performing any immediate actions against that table. In such cases, we would need to run code specifically to see if the table exists.

Below are examples of code we can use in each of the above scenarios.

Continue reading

DROP TABLE IF EXISTS in SQL

In SQL, we can use the DROP TABLE IF EXISTS statement to drop a table only if it exists.

While it may seem obvious that we can only drop a table if it exists (i.e. we can’t drop a table that doesn’t exist), there’s a good reason for using this statement.

The reason we put an IF EXISTS clause into a DROP TABLE statement is to prevent any errors that would occur if the table doesn’t exist.

Continue reading

PostgreSQL SHOW TABLES Equivalent (psql)

MySQL and MariaDB have a SHOW TABLES statement, which outputs a list of tables and views in a database. PostgreSQL doesn’t have a SHOW TABLES statement, but it does have a command that produces a similar result.

In Postgres, you can use the \dt command to show a list of tables. This is a psql command (psql is the interactive terminal for PostgreSQL).

Continue reading

SQL Server SHOW TABLES Equivalent

Every now and then I find myself typing SHOW TABLES in SQL Server, expecting to get a list of tables.

That would make perfect sense if I was using MySQL or MariaDB. But SQL Server/T-SQL doesn’t have a SHOW TABLES statement like MySQL or MariaDB, so it never works. And I keep forgetting. But fortunately, SQL Server does have alternatives.

Here are five options for getting a list of tables in SQL Server. These can be used whenever you’re trying to find that elusive SHOW TABLES statement in SQL Server.

Continue reading