Sub topic 7
Creating Your Practice Database
This chapter assumes PostgreSQL is installed, the server is running, and you can open psql. It also assumes you can connect to a maintenance database such as postgres.
A PostgreSQL database is a named container for tables, views, and other objects. A PostgreSQL cluster is the server-managed collection of databases. You connect to one database at a time, so create firstdb and then switch your session to it.
Create the database
Connect to the default postgres database:
psql -h localhost -p 5432 -U postgresThe options mean:
-h localhostconnects to PostgreSQL on your computer.-p 5432uses the usual PostgreSQL port.-U postgresselects thepostgresrole, which is commonly created during installation.
At the psql prompt, create the practice database:
CREATE DATABASE firstdb;A successful command returns:
CREATE DATABASEThe command creates an empty database. It does not create any tables yet.
Switch to the new database
The \c command is a psql meta-command. Meta-commands are instructions handled by the psql client rather than by the SQL server.
\c firstdbYou should see a message similar to:
You are now connected to database "firstdb" as user "postgres".The prompt may also change from postgres=# to firstdb=#. The prompt is a useful reminder of which database receives your next SQL statement.
Confirm the connection with SQL:
SELECT current_database(), current_user;The result should show firstdb as the database and postgres as the current role.
Understand the connection path
Your client does not connect directly to a table. It first reaches a PostgreSQL server, authenticates as a role, and selects one database inside the cluster.
Handle common errors
If PostgreSQL reports that firstdb already exists, the database was probably created during an earlier attempt. Connect to it instead:
\c firstdbIf PostgreSQL reports that you lack permission to create a database, your role does not have the required CREATEDB privilege. Ask an administrator to create the database or grant the privilege. Do not solve this by changing permissions broadly.
If you connect to the wrong database, run \c firstdb again. You can check the active connection with:
SELECT current_database();Keep the psql session connected to firstdb. The next chapter will create the books table inside it.
Exercise
Why should you run \c firstdb after CREATE DATABASE firstdb;?
Show answer
CREATE DATABASE creates the database but leaves the current session connected to its previous database. The \c command switches the session to firstdb so later tables and data are created there.