database already exists
This error occurs when you try to create a database with a name that's already in use.
The database already exists error means the database name is already taken.
Understanding the Error
ERROR: database "myapp" already exists
A database with that name already exists on the server.
Common Causes
1. Running CREATE DATABASE Twice
SQL
2. Script Run Multiple Times
Migration or setup script executed more than once.
3. Name Conflict with Different Case
SQL
How to Fix It
Solution 1: Check If Database Exists First
SQL
Solution 2: Use IF NOT EXISTS
Note: PostgreSQL doesn't support CREATE DATABASE IF NOT EXISTS directly, but you can use:
SQL
Solution 3: Drop and Recreate
SQL
Solution 4: Use a Different Name
SQL
Solution 5: Shell Script Check
BASH
Solution 6: Use Conditional in Migrations
JAVASCRIPT
Best Practices
- Use environment-specific names (myapp_dev, myapp_test, myapp_prod)
- Check before creating in scripts
- Use idempotent migrations that can run multiple times safely
- Document database naming conventions
- Avoid dropping production databases in scripts