I read the wordpress codex and professional wordpress. It seems both use something like

if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {

to determine if the table exists. Is there any reason why CREATE TABLE IF NOT EXISTS ( ... ) is not used? It will check and create the table in 1 query, won't it be better? Or am I missing something?


If you use "IF NOT EXISTS" then the dbdelta script will not upgrade your database with delta's appeared after the initial creation of the database.

(assuming you want to re-use the same sql script)

at least... that is what i think

| improve this answer | |

DISCLAIMER : I'm not a WordPress Guru, only a MySQL DBA

If you want to user a different query, try this

SELECT COUNT(1) FROM information_schema.tables WHERE table_schema='dbname' AND table_name='tbname';

It will either return 0 (if table does not exist) or 1 (if table does exist)

| improve this answer | |

Try this one:

global $wpdb;
$table_name = $wpdb->base_prefix.'custom_prices';
$query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

if ( ! $wpdb->get_var( $query ) == $table_name ) {
    // go go
| improve this answer | |
  • 1
    Please edit your answer, and add an explanation: why could that solve the problem? – fuxia Apr 12 '19 at 15:47

Not sure how or why this works, but I can do:

if (in_array('snippets', $wpdb->tables)) {
  // do something if wp_snippets exists
| improve this answer | |
  • 2
    this only works for core tables as I find while testing – Manchumahara Mar 7 '19 at 8:02
  • it worked for me for detecting Code Snippets plugin's table. – iSWORD Mar 7 '19 at 10:32

Use get_var function from wpdb class with an exception handling:

try {
    $wpdb->get_var( 'SELECT COUNT(*) FROM ' . $wpdb->prefix . 'translator' );
} catch (Exception $e) {
} finally {

Reference: SELECT a Variable

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.