Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

Is there a way to check if a table exists without selecting and checking values from it?

That is, I know I can go SELECT testcol FROM testtable and check the count of fields returned, but it seems there must be a more direct / elegant way to do it.

1 Answer

0 votes
by (40.7k points)

Try this code:

SELECT 1 FROM testtable LIMIT 1;

You don't need to count anything.If there's no error, then the table exists.You can use INFORMATION_SCHEMA, if you want to be correct like this:

SELECT * 

FROM information_schema.tables

WHERE table_schema = 'yourdb' 

    AND table_name = 'testtable'

LIMIT 1;

Otherwise, you can also use SHOW TABLES like this :

SHOW TABLES LIKE 'yourtable';

If there is a row in the resultset, table exists.

Related questions

0 votes
1 answer
+2 votes
1 answer
0 votes
1 answer
asked May 4, 2020 in SQL by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Dec 4, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer

Browse Categories

...