Your first query
Overview
You’ve already seen a few queries. Now it’s time to understand exactly how they’re put together, write your own, and learn what to do when PostgreSQL says no — because it will, and that’s normal.
The simplest query
SELECT doesn’t even need a table. It can just calculate:
SELECT 2 + 3; ?column?
----------
5
(1 row)The result is a table with one row and one column. PostgreSQL named the column ?column? because you didn’t give it a name. Add one with AS:
SELECT 2 + 3 AS answer, 'Hello, SQL' AS greeting; answer | greeting
--------+------------
5 | Hello, SQL
(1 row)Two things to notice: the comma separates the items in the list, and the text 'Hello, SQL' is in single quotes. In SQL, single quotes always mean a text value.
Reading from a table
Most queries read from a table, named with FROM. List the columns you want after SELECT:
SELECT first_name, last_name, country
FROM customers; first_name | last_name | country
------------+-----------+-----------
Asha | Rao | India
Ben | Carter | UK
Chen | Wei | Singapore
Dee | Okafor | Nigeria
Elena | García | Spain
Farhan | Ali | India
Grace | Kim | USA
Hugo | Martin | France
Isha | Patel | India
Jack | Wilson | USA
(10 rows)Ten customers, three columns each, and psql adds a row count at the end. The columns come back in the order you listed them, not the order they’re stored in.
To get every column, use *:
SELECT * FROM categories; id | name
----+-------------
1 | Coffee
2 | Tea
3 | Equipment
4 | Accessories
(4 rows)SELECT * is great for a quick look at a table you don’t know. In real queries and application code, list the columns you need: it’s clearer to read, sends less data, and doesn’t break when someone adds a column to the table later.
The anatomy of a query
Most queries you’ll write use some or all of five clauses, and they always appear in this order:
Here’s that query running — the three most expensive products that are in stock:
SELECT name, price
FROM products
WHERE stock > 0
ORDER BY price DESC
LIMIT 3; name | price
-----------------+-------
Burr Grinder | 89.00
Electric Kettle | 59.90
Gift Card | 25.00
(3 rows)You’ll study each clause in detail in the next chapter. For now, the important rule is the order: SELECT … FROM … WHERE … ORDER BY … LIMIT. Put WHERE after ORDER BY and you get a syntax error.
Filtering with WHERE
WHERE keeps only the rows for which a condition is true. Numbers are written as they are; text goes in single quotes:
SELECT first_name, city
FROM customers
WHERE country = 'UK'; first_name | city
------------+-------
Ben | Leeds
(1 row)Text comparisons are exact, including capital letters: WHERE country = 'uk' finds nobody, because the data says UK.
Style rules (and which ones matter)
SQL is relaxed about layout:
- Keywords are case-insensitive.
select,SELECTandSelectare identical. Writing keywords in capitals and names in lower case is a widespread convention because it makes queries easier to scan; this course follows it. - Whitespace is free. Spaces, tabs and line breaks are all the same to PostgreSQL. Short queries fit on one line; longer ones read best with one clause per line.
- Semicolons end statements. psql won’t run a query until it sees one, and they separate statements when you run several at once.
- Comments start with
--and run to the end of the line, or go between/*and*/.
-- Products in category 2 (Tea)
select name, price
from products where category_id = 2 /* tea only */ ; name | price
------------------------+-------
Darjeeling First Flush | 18.00
Assam Breakfast | 9.50
Jasmine Green | 12.75
Chamomile Calm | 8.00
(4 rows)It works, but it’s hard to read. Consistent formatting is a gift to the next person who reads your query — usually you.
Single quotes, double quotes
This catches out almost everyone coming from other languages:
'single quotes'make a text value:WHERE city = 'Pune'."double quotes"make an identifier — a table or column name — and are only needed when the name has capitals, spaces or clashes with a keyword:SELECT "Order Total" FROM ….
So WHERE city = "Pune" doesn’t compare with the text Pune; it looks for a column called Pune:
SELECT first_name FROM customers WHERE city = "Pune";ERROR: column "Pune" does not exist
LINE 1: SELECT first_name FROM customers WHERE city = "Pune";
^To put a single quote inside a text value, double it: 'O''Brien'.
Reading error messages
Errors are information, not failure. PostgreSQL’s messages have up to three useful parts. Here’s a misspelt column:
SELECT name, prise FROM products;ERROR: column "prise" does not exist
LINE 1: SELECT name, prise FROM products;
^
HINT: Perhaps you meant to reference the column "products.price".- The ERROR line says what’s wrong: there’s no column called
prise. - The LINE shows where, with a
^under the problem. - A HINT, when there is one, often tells you the fix.
Missing commas produce a different kind of error. PostgreSQL reads first_name last_name as “the column first_name, renamed to last_name” (a name can follow a column without AS), and then has no idea what to do with the next word:
SELECT first_name last_name city
FROM customers;ERROR: syntax error at or near "city"
LINE 1: SELECT first_name last_name city
^“Syntax error at or near” means PostgreSQL couldn’t parse the query, and the word it names is where it gave up. The real mistake is usually just before that word — here, the missing commas.
Tip: when a query fails, fix the first error first and run it again. One typo near the top can cause confusing messages further down.
A note on SELECT and safety
Everything in this lesson and the next few is read-only: SELECT never changes data, so you can’t break anything by experimenting. You’ll learn to change data — INSERT, UPDATE and DELETE — in chapter 8, along with the habits that keep those commands safe.
Customers in India
Bean & Leaf is planning a Diwali promotion. Write a query that returns the first_name, last_name and city of every customer whose country is 'India', sorted by first name. Remember that text values go in single quotes. You should get three customers: Asha, Farhan and Isha.
SELECT first_name, last_name, city
FROM customers
-- keep only customers in India, then sort by first nameSELECT first_name, last_name, city
FROM customers
WHERE country = 'India'
ORDER BY first_name;Summary
- A query is built from clauses written in a fixed order: SELECT, FROM, WHERE, ORDER BY, LIMIT. Only SELECT is required.
- SELECT lists the columns to return (or * for all of them); FROM names the table.
- Text values go in single quotes ('India'); double quotes are for unusual column or table names.
- Keywords are case-insensitive and whitespace is free, but a semicolon ends each statement.
- Error messages point at the problem: read the ERROR line, the LINE with its ^ marker, and any HINT.