MySQL Error:
1007, Database Exists
What does this error mean?
MySQL returns error 1007 (ER_DB_CREATE_EXISTS) when a CREATE DATABASE statement targets a database name that already exists on the server. The server rejects the statement outright — no partial creation, no merge with the existing database. In data pipelines, this typically surfaces during environment provisioning: a dbt run-operation pre-hook, an ADF Script activity, or a Terraform mysql_database resource tries to create a staging or warehouse database that was already created by a previous run or left behind after an incomplete teardown. The symptom in your pipeline logs is a hard failure with SQLSTATE HY000 and error code 1007; any downstream steps that depend on the database being freshly created (table migrations, seed loads) will not execute.
Common causes
- 1Migration or setup script runs CREATE DATABASE without the IF NOT EXISTS clause, causing a hard failure on re-runs.
- 2CI/CD pipeline provisions a test database but skips the DROP step between runs, so the database persists from the previous build.
- 3A previous deployment failed halfway — the database was created but table migrations did not complete, leaving a partially set-up database behind.
- 4Terraform or Pulumi mysql_database resource drifts out of sync with actual server state: the resource was removed from state but the database still exists on the server.
- 5Multiple branches or environments share the same MySQL instance and use the same database name without a per-branch suffix, so parallel pipelines collide.
How to fix it
- 1Step 1: Confirm the database exists: `SHOW DATABASES LIKE 'your_db';` — if it returns a row, error 1007 is expected.
- 2Step 2: Make creation idempotent: `CREATE DATABASE IF NOT EXISTS your_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;` — MySQL returns a warning (not an error) if the database exists.
- 3Step 3: If you need a clean database, drop first: `DROP DATABASE IF EXISTS your_db; CREATE DATABASE your_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;` — be aware this destroys all tables and data in that database.
- 4Step 4: Check who or what created the database: `SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = 'your_db';` — verify it matches expected charset/collation.
- 5Step 5: In dbt, wrap creation in a pre-hook: `pre-hook: "CREATE DATABASE IF NOT EXISTS {{ target.schema }};"` inside your dbt_project.yml so every dbt run is safe to re-execute.
- 6Step 6: In ADF, use a Lookup or Script activity with the IF NOT EXISTS variant, and set the activity dependency to 'on success' so downstream Copy activities only run when setup completes cleanly.
- 7Step 7: For Terraform, import the existing database into state: `terraform import mysql_database.your_db your_db` — this resolves the drift without dropping the database.
Example log output
ERROR 1007 (HY000) at line 1: Can't create database 'analytics_staging'; database exists