PostgreSQL Databases: CREATE DATABASE, DROP DATABASE & Connecting
Learn how to create, list, connect to, and drop databases in PostgreSQL, plus the role of the default postgres and template databases.
PostgreSQL Databases
Unlike MongoDB, PostgreSQL requires you to explicitly create a database before using it — there's no "lazy creation on first insert."
Listing Databases
\l
or, using pure SQL:
SELECT datname FROM pg_database;
Creating a Database
CREATE DATABASE shop;
Connecting to a Database
\c shop
-- You are now connected to database "shop" as user "postgres".
Dropping a Database
DROP DATABASE shop;
You can't drop the database you're currently connected to — connect to a different one (like postgres) first:
\c postgres
DROP DATABASE shop;
DROP DATABASE IF EXISTS shop; avoids an error if it's already gone.
Template Databases
Every new database is actually copied from a template. template1 is the default template — any object you create in template1 will appear in every future database you create. template0 is a pristine, unmodifiable fallback.
CREATE DATABASE shop TEMPLATE template0;
Advertisement728 x 90
Common Errors & Troubleshooting
ERROR: database "shop" is being accessed by other users— you (or another session) are still connected to it; run\c postgresto switch away, and close other open connections toshopbefore dropping it.ERROR: database "shop" already exists— useCREATE DATABASE IF NOT EXISTS— actually, PostgreSQL doesn't support that clause for databases; check\lfirst, or wrap the statement in application logic that catches the "already exists" error.- Forgetting which database you're connected to — run
\conninfoorSELECT current_database();any time you're unsure — accidentally runningDROP DATABASEagainst the wrong one is unrecoverable without a backup.
Key Takeaways
- Databases must be created explicitly with
CREATE DATABASE— there's no auto-creation. - You can't drop a database while connected to it; switch connections first.
- New databases are copies of
template1by default, which is why customizingtemplate1affects every database created afterward.
Advertisement320 x 100