Sub topic 3
Running Your First SELECT
This chapter assumes PostgreSQL is installed, the server is running, and you can connect with psql. It also assumes the firstdb database and the books table from the previous chapter exist, with three rows.
Running your first SELECT
A SELECT statement reads rows from a table. This query returns every row and column:
SELECT * FROM books;To return only some columns, list their names:
SELECT title, published_year
FROM books
WHERE published_year > 1900
ORDER BY published_year DESC;Each SQL statement ends with a semicolon. psql waits until it sees one before sending the statement to the server.
Filtering and sorting results
WHERE keeps only the rows that match a condition. ORDER BY sorts the result. ASC sorts ascending and is the default. DESC sorts descending, so the newest books come first.
Exploring with psql meta-commands
A meta-command starts with a backslash. psql handles these itself, so they do not go to the server.
| Command | Purpose |
|---|---|
| `\l` | List databases |
| `\dt` | List tables in the current database |
| `\d books` | Describe the columns of the books table |
| `\q` | Quit psql |
Changing and removing rows safely
Always include a WHERE clause in UPDATE and DELETE. Without one, the statement applies to every row.
UPDATE books SET published_year = 1966 WHERE title = 'Dune';
DELETE FROM books WHERE title = 'Emma';Fixing common connection errors
Most connection failures show one of these messages.
| Error message | Likely cause | Fix |
|---|---|---|
| `could not connect to server` | Server is stopped, or the host or port is wrong | Run `pg_isready`, then check `-h` and `-p` |
| `password authentication failed for user` | Wrong user name or password | Check the `-U` value and retype the password |
| `database "firstdb" does not exist` | Database name is wrong or it was never created | Connect to `postgres` and run `\l` to see the names |
pg_isready -h localhost -p 5432Cleaning up
You cannot drop a database while connected to it. Switch to postgres first.
\c postgres
DROP DATABASE firstdb;Exercise
Exercise
Write a query that returns the title of each book published before 1970, sorted alphabetically by title.
Show answer
SELECT title FROM books WHERE published_year < 1970 ORDER BY title ASC;