MySQL: How to Check if a Table Exists with SQL

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:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in MySQL and tagged , show tables, . Bookmark the permalink.
    blog comments powered by Disqus