Sub topic 2
Roles and databases in a PostgreSQL cluster
This chapter assumes that PostgreSQL is installed, the server is running, and you can connect with psql as the postgres superuser. You should know basic SQL statements such as SELECT and INSERT.
Roles and databases in a PostgreSQL cluster
A cluster is one running PostgreSQL server and all the data it manages. A cluster holds several databases. Each database holds its own schemas, tables, and rows.
Access is controlled by roles. A role is an account that can own objects and hold privileges. A role with the LOGIN attribute acts as a user. PostgreSQL does not treat users and groups as separate object types.
Creating your practice database
Run this as a role that has the CREATEDB privilege. The example uses the postgres superuser and sets a new role as the owner.
CREATE ROLE learner LOGIN PASSWORD 'change_me';
CREATE DATABASE firstdb OWNER learner;
\c firstdbThe \c meta-command switches the psql session to firstdb. Without it, your next statements would run in the database you first connected to.
Creating a table
The next statement defines a table with an identity primary key and typed columns.
CREATE TABLE books (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
published_year integer
);The id column is filled automatically. The NOT NULL constraints reject rows that leave title or author empty.
Inserting rows
Insert several rows with one statement. You do not supply a value for id.
INSERT INTO books (title, author, published_year)
VALUES
('Dune', 'Frank Herbert', 1965),
('Neuromancer', 'William Gibson', 1984),
('Emma', 'Jane Austen', 1815);
SELECT id, title FROM books;| id | title |
|---|---|
| 1 | Dune |
| 2 | Neuromancer |
| 3 | Emma |
Exercise
Exercise
Why does the INSERT statement omit the id column, and what happens if you try to supply id = 10 explicitly?
Show answer
The id column is GENERATED ALWAYS AS IDENTITY, so PostgreSQL assigns it. An explicit value is rejected with an error unless you use OVERRIDING SYSTEM VALUE in the INSERT.