error mysql

MySQL Error 1146 - Table Doesn't Exist

Understanding MySQL error 1146 - the referenced table does not exist in the specified database.

What It Means

MySQL error 1146 (ER_NO_SUCH_TABLE) means “Table ‘database.table_name’ doesn’t exist.” A query referenced a table that cannot be found in the specified database. This commonly occurs when migrations haven’t been run or the table name is misspelled.

Common Causes

  • Database migrations have not been run
  • Typo in the table name
  • Case sensitivity (table names are case-sensitive on Linux)
  • Query references the wrong database
  • Table was dropped accidentally
  • Database was restored from a partial backup
  • ORM model doesn’t match the actual database schema

How to Fix

Check existing tables

-- List all tables in the current database
SHOW TABLES;

-- Search for a specific table
SHOW TABLES LIKE '%user%';

-- Check the full table name including database
SELECT TABLE_SCHEMA, TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_NAME LIKE '%user%';

Run migrations

# Django
python manage.py migrate

# Rails
rails db:migrate

# Laravel
php artisan migrate

# Sequelize (Node.js)
npx sequelize-cli db:migrate

# Prisma
npx prisma migrate deploy

# Knex.js
npx knex migrate:latest

Create the table manually

-- Create a basic table
CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE,
  name VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Fix case sensitivity

-- Linux MySQL is case-sensitive for table names
-- Check the lower_case_table_names setting
SHOW VARIABLES LIKE 'lower_case_table_names';

-- 0 = case-sensitive (Linux default)
-- 1 = case-insensitive (Windows/macOS default)

-- Ensure your queries match the exact table name
SELECT * FROM Users;   -- Wrong if table is 'users'
SELECT * FROM users;   -- Correct

Fix in application code

// Check that model table name matches the database
// Sequelize
const User = sequelize.define('User', {
  email: DataTypes.STRING,
}, {
  tableName: 'users',  // Explicitly set to match the database
});
# Django - check model Meta
class User(models.Model):
    email = models.EmailField()

    class Meta:
        db_table = 'users'  # Explicitly set the table name

Restore from backup

# Restore a specific table from a MySQL dump
mysql -u root -p mydb < backup.sql

# Or restore just one table
mysql -u root -p mydb -e "SOURCE /path/to/users_table.sql"
  • MySQL 1049 - Unknown database: The database itself doesn’t exist.
  • MySQL 1062 - Duplicate entry: Table exists but has a constraint violation.
  • MySQL 1215 - Cannot add foreign key: Related table structure issue.