Creating a Database

Updated · 6 min read
easyPostgreSQL 18sqlcreate-databasedrop-databaseschema

A database is the container for a set of tables, and one PostgreSQL server can hold many of them. The Fee Tracker lives in its own database; a shop or a game would live in others, side by side on the same server. Inside a database, schemas group tables like folders. This lesson covers creating and dropping databases, using schemas, and connecting to the right database, including DROP DATABASE, a statement that can't run inside a transaction, so ROLLBACK can't undo it.

In One Minute

  • CREATE DATABASE name; makes a new, empty database on the server.
  • DROP DATABASE name; deletes a database and everything in it, permanently.
  • A schema is a folder inside a database; tables live in a schema, public by default.
  • In psql, \c name connects to a database; SQL runs in whichever database you're connected to.
  • Try it runs one database, so you can create schemas there but can't switch databases.

Server, Database, Schema, Table

PostgreSQL organizes everything in four levels:

LevelHoldsFee Tracker example
ServerMany databasesYour PostgreSQL installation
DatabaseMany schemasfeetracker
SchemaMany tables (and views, functions)public
TableRowspayments
One server holds databases; a database holds schemas; a schema holds tables

A query sees only the database it's connected to. To use tables from two databases at once, you'd connect to each; tables in two schemas of the same database, on the other hand, can be used together in one query.

CREATE DATABASE

SQL
CREATE DATABASE database_name;

On your own PostgreSQL, in psql, you create a database and connect to it like this (you did exactly this in Setting Up SQL):

text
postgres=# CREATE DATABASE feetracker;
CREATE DATABASE
postgres=# \c feetracker
You are now connected to database "feetracker" as user "you".
feetracker=#

\c is a psql command, not SQL, so graphical clients choose the database in their connection settings instead. Names follow the usual rules: lowercase letters, digits and underscores work everywhere without quotes. Other databases connect differently: MySQL and SQL Server use USE database_name; (MySQL only, SQL Server only), and SQLite creates a database simply by opening a new file.

DROP DATABASE

SQL
DROP DATABASE database_name;
DROP DATABASE IF EXISTS database_name;

DROP DATABASE deletes the database and every table, row and schema inside it. PostgreSQL won't drop the database you're connected to, so you connect to another one first, as in The Fee Tracker Database:

text
feetracker=# \c postgres
postgres=# DROP DATABASE feetracker;
DROP DATABASE

IF EXISTS turns "database doesn't exist" from an error into a notice, which is handy in setup scripts that may run twice.

Dropping a database deletes every schema, table and row in it

Schemas: Folders Inside a Database

A schema groups related tables inside one database. Every new database has a schema called public, and that's where the Fee Tracker's five tables live:

SQL▶ Try it
SELECT current_database() AS database, current_schema() AS schema;
Output
 database | schema
----------+--------
 postgres | public
(1 row)

(In Try it the database is called postgres; on your own server it would be feetracker.) Create a schema for old records, put a table in it, and refer to it as schema.table:

SQL▶ Try it
CREATE SCHEMA archive;
 
CREATE TABLE archive.old_payments (
  payment_id INTEGER,
  amount_usd NUMERIC(8,2)
);
 
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_schema IN ('public', 'archive')
ORDER BY table_schema, table_name;
Output
CREATE SCHEMA
 
CREATE TABLE
 
 table_schema |  table_name
--------------+--------------
 archive      | old_payments
 public       | cities
 public       | courses
 public       | enrollments
 public       | payments
 public       | students
(6 rows)

archive.old_payments sits beside the five public tables. Schemas let one database hold separate areas, such as public for everyday data, archive for history and reporting for summaries, with their own permissions. A name without a schema, such as payments, is looked up in the schemas on the search path, which is public unless you change it.

public holds the Fee Tracker tables; archive holds old_payments

In MySQL, "schema" and "database" mean the same thing; SQL Server and Oracle have schemas inside databases, like PostgreSQL. Tabs showing each database's version are coming to this course.

Common Mistakes

Running SQL in the wrong database. Tables created while connected to postgres end up there. Check the prompt (feetracker=#) or SELECT current_database();.

Dropping the database you're connected to. PostgreSQL refuses; connect to postgres first, and be sure you mean it.

Expecting ROLLBACK to undo DROP DATABASE. It can't run in a transaction. Keep backups.

Forgetting the schema. old_payments alone isn't found if archive isn't on the search path; write archive.old_payments.

Practice

Challenge: Create a schema called reporting, create a table reporting.monthly_totals with a month column of type DATE and a total_usd column of type NUMERIC(10,2), then list the tables in that schema.

Show solution
SQL▶ Try it
CREATE SCHEMA reporting;
 
CREATE TABLE reporting.monthly_totals (
  month     DATE,
  total_usd NUMERIC(10,2)
);
 
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_schema = 'reporting';
Output
CREATE SCHEMA
 
CREATE TABLE
 
 table_schema |   table_name
--------------+----------------
 reporting    | monthly_totals
(1 row)

The new table lives in reporting, separate from the Fee Tracker's public tables. In Try it, both disappear when the run ends.

Quick check: Creating a database

3 questions
1What does DROP DATABASE feetracker; delete?
2Where do the Fee Tracker's tables live by default?
3How do you connect to the feetracker database in psql?

Key Takeaways

You want toWrite
Make a databaseCREATE DATABASE feetracker;
Connect in psql\c feetracker
Delete a databaseDROP DATABASE IF EXISTS feetracker;
Make a schemaCREATE SCHEMA archive;
Use a table in a schemaarchive.old_payments
See where you areSELECT current_database(), current_schema();

Was this tutorial helpful?

Lesson 27 of 115