Sub topic 7
Creating Your Practice Database
This chapter covers creating the database you will use for the rest of the tutorial. It assumes you have PostgreSQL installed, a server that accepts connections, and a working psql session as a role that can create databases (the postgres superuser in the examples). It also assumes you know what a database and a table are, and that you are comfortable in a terminal.
What a database is in PostgreSQL
A PostgreSQL server process manages a cluster. A cluster is a set of databases that share one data directory, one port, and one set of roles. Each database in the cluster is an isolated container for tables, views, functions, and other objects. A connection is bound to exactly one database for its whole life. You cannot query a table in another database by naming it. To work in another database, you open a new connection or switch with \c.
Every new cluster contains three databases:
| Database | Purpose |
|---|---|
| `postgres` | A default database for administrative connections and tools. |
| `template1` | The default template that new databases are copied from. |
| `template0` | A pristine, read-only template used for special cases such as changing the encoding. |
A practice database keeps your experiments away from the postgres database, which tools often expect to be empty and available.
Connecting first
You need a session before you can create anything. Connect to the default postgres database as the postgres role:
psql -h localhost -p 5432 -U postgresIf the connection succeeds, the prompt looks like postgres=#. The name before = is the current database. The # means you are a superuser. A regular role sees > instead.
Running CREATE DATABASE
The CREATE DATABASE statement makes the new database. Then the \c meta-command switches your session to it:
CREATE DATABASE firstdb;
\c firstdbOn success, the server answers CREATE DATABASE. The \c command prints a line such as You are now connected to database "firstdb" as user "postgres". The prompt changes to firstdb=#.
Two details are worth knowing:
CREATE DATABASEends with a semicolon, because it is an SQL statement.\cis a psql meta-command and does not need one. The client handles it, and the server never sees it.CREATE DATABASEcannot run inside a transaction block. If you issueBEGIN;first, the server rejects the statement withCREATE DATABASE cannot run inside a transaction block.
What happens when you create a database
CREATE DATABASE firstdb; with no options copies template1. The copy includes every object in template1, such as installed extensions and default privileges. The new database also inherits its encoding and locale settings from the template. This is why the command takes a moment on large templates, and why the template must have no other connections while it is being copied.
The command is shorthand for this fuller form:
CREATE DATABASE firstdb
TEMPLATE template1
ENCODING 'UTF8'
OWNER postgres;Here is what each option controls:
TEMPLATEnames the database to copy from. The default istemplate1.ENCODINGsets the character encoding. Most installations default toUTF8, which is the right choice for almost all new work.OWNERnames the role that owns the database. The default is the role running the command. The owner can drop the database and manage its objects.
For this tutorial the plain form is enough. The fuller form shows what the server does for you.
Checking that it worked
List all databases with the \l meta-command:
\lThe output is a table of names, owners, encodings, and privileges. You should see firstdb next to postgres, template0, and template1. You can also query the system catalog directly:
SELECT datname, datdba::regrole AS owner, pg_encoding_to_char(encoding) AS encoding
FROM pg_database
WHERE datname = 'firstdb';The \l command is a convenience. It runs a query against pg_database like this one.
To confirm which database you are in right now, use either of these:
SELECT current_database();
\conninfocurrent_database() returns the name as a query result. \conninfo prints the user, database, host, and port of the current connection.
Naming rules
Database names follow the same rules as other identifiers:
- An unquoted name is folded to lowercase.
CREATE DATABASE FirstDB;createsfirstdb. - A double-quoted name keeps its case exactly.
CREATE DATABASE "FirstDB";creates a different database, and you must quote it every time afterward. - Names are limited to 63 bytes. Longer names are silently truncated.
- Names with spaces or hyphens must be quoted, which gets awkward fast.
Use lowercase letters, digits, and underscores. That avoids quoting everywhere, including in shell commands such as createdb and pg_dump.
Common errors
| Message | Cause | Fix |
|---|---|---|
| `ERROR: database "firstdb" already exists` | You ran the command before. | Connect to it with `\c firstdb`, or drop it first (see the cleanup chapter). |
| `ERROR: permission denied to create database` | Your role lacks the `CREATEDB` attribute. | Connect as a superuser, or have one run `ALTER ROLE yourrole CREATEDB;`. |
| `ERROR: source database "template1" is being accessed by other users` | Another session is connected to the template. | Disconnect those sessions and retry. |
| `FATAL: database "firstdb" does not exist` | You typed the name wrong in `\c` or `psql -d`, or the create step failed. | Run `\l` and check the spelling. |
| `ERROR: CREATE DATABASE cannot run inside a transaction block` | An earlier `BEGIN;` is still open. | Run `ROLLBACK;` or `COMMIT;` and retry. |
Alternative: the createdb program
PostgreSQL ships a shell command, createdb, which sends the same CREATE DATABASE statement for you. It takes the same connection options as psql:
createdb -h localhost -p 5432 -U postgres firstdbUse it in scripts, where you do not want to start an interactive session. In this tutorial you stay in psql, so the SQL form is the one to use.
Connecting straight to the new database
Once the database exists, you can skip the postgres database and connect to firstdb directly. The -d option sets the database name:
psql -h localhost -p 5432 -U postgres -d firstdbThe prompt then starts at firstdb=#. The database name can also be given as a bare final argument, such as psql -U postgres firstdb.
Checkpoint
By now you should have these things in place:
- A
firstdbdatabase that appears in the\llisting. - A session whose prompt reads
firstdb=#. - A result from
SELECT current_database();that readsfirstdb.
The next chapter creates the books table here.
Exercise
You run CREATE DATABASE firstdb; and then CREATE TABLE books (id integer); in the same psql session, and the table lands in the postgres database instead of firstdb. What step did you skip, and how do you confirm which database you are in?
Show answer
You skipped switching connections with \c firstdb. CREATE DATABASE only creates the database and does not move your session into it. Confirm the current database with SELECT current_database(); or \conninfo, or read the name before = in the prompt.
Exercise
A colleague runs CREATE DATABASE "Sales"; and later \c sales fails with database "sales" does not exist. Why, and what would you do to avoid the problem?
Show answer
The double quotes preserved the capital S, so the database is named Sales. An unquoted sales is folded to lowercase and does not match it. Connect with \c "Sales". To avoid the problem, create databases with lowercase unquoted names.