Sub topic 10
Running Your First `SELECT`
Assume PostgreSQL is installed, the server is running, and you are connected to the firstdb database with psql. This chapter also assumes that the books table from the previous chapter exists and contains sample rows.
A SELECT statement reads data. It does not change the table. The basic form names the columns to return and the table to read:
SELECT column_name
FROM table_name;Run this query at the firstdb=# prompt:
SELECT title, author
FROM books;PostgreSQL returns a result set, which is a table-shaped collection of query results:
title | author
-------------+------------------
Dune | Frank Herbert
Neuromancer | William Gibson
Emma | Jane Austen
(3 rows)The semicolon marks the end of the SQL statement. The line breaks are optional, but placing each clause on its own line makes longer queries easier to read.
Selecting columns
You can request one column, several columns, or every column.
SELECT title
FROM books;
SELECT title, published_year
FROM books;
SELECT *
FROM books;The asterisk means “all columns.” It is useful while exploring a table, but naming columns is usually clearer in application code. If someone adds a column later, a query using * automatically starts returning that new column.
The order of columns in the SELECT list controls the order in the result. It does not change the table itself.
You can also calculate values in a query:
SELECT title, published_year, published_year + 1 AS next_year
FROM books;AS next_year gives the calculated column a readable label. This label is called an alias.
Checking the server with `SELECT`
A query does not need a table. PostgreSQL can evaluate an expression directly:
SELECT version();The version() function returns information about the PostgreSQL server. This is a useful connection check because it confirms that the server accepted and executed your query.
The client and server have different roles:
Understanding `NULL`
A NULL value means that a value is missing or unknown. It is different from zero and different from an empty string.
If published_year is NULL, this query displays a blank-looking value:
SELECT title, published_year
FROM books;Do not test for missing values with published_year = NULL. SQL uses a separate test:
SELECT title
FROM books
WHERE published_year IS NULL;WHERE is introduced here only to show the correct NULL test. Filtering and sorting results in more detail comes next.
| Query part | Purpose |
|---|---|
| `SELECT title, author` | Chooses the values to return |
| `FROM books` | Chooses the table to read |
| `WHERE published_year IS NULL` | Keeps rows matching a condition |
Exercise
Write a query that returns the title and author columns from the books table.
Show answer
SELECT title, author FROM books;