To check if a table exists with SQL in a MySQL database is pretty easy, thanks to the nifty SHOW TABLES command.
To find if a specific table exists, we simply extend the standard SHOW TABLES statement with a LIKE parameter, which allows us to search for a specific string or for a partial string using the standard % modifier. If the statement returns a non-empty result set, we know the table exists.
For example:
SHOW TABLES LIKE 'activity-log';
will return a empty result set if your database doesn’t have a table named ‘activity-log’ in it. Similarly,
SHOW TABLES LIKE '%activity-log';
will return a result set containing all tables that end with ‘activity-log’, e.g. ‘sms-activity-log’ and ‘email-activity-log’ as well as plain old ‘activity-log’ of course!
Nifty.
You might also enjoy:
-
To check if a column exists in a table with SQL using a MySQL database is pretty easy, thanks to the nifty SHOW COLUMNS command. To find if a specific co ...
-
When you start working with sizeable datasets and the like, things like database optimization become more and more important for you to pay attention to. ...
-
There exists in this world a nice little SQL statement know as the SELECT INTO statement, one that works beautifully well in most database systems for when ...
-
Annoyingly, I got saddled with a database for a system which contained a whole lot of "uncleaned data", in other words data with a lot of trailing and leadi ...
-
To delete a database from a MySQL server instance, we need to make a DROP DATABASE call against the server. First, fire up MySQL in your terminal and lo ...