Your first query

Topic 4 of 4 in Getting started10 min readBeginnerFree course

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:

SQL
SELECT 2 + 3;
Text
 ?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:

SQL
SELECT 2 + 3 AS answer, 'Hello, SQL' AS greeting;
Text
 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:

SQL
SELECT first_name, last_name, country
FROM customers;
Text
 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 *:

SQL
SELECT * FROM categories;
Text
 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:

Anatomy of a query. SELECT name, price chooses which columns to return. FROM products says which table to read. WHERE stock > 0 says which rows to keep. ORDER BY price DESC says how to sort the result. LIMIT 3 says how many rows at most. The result is Burr Grinder 89.00, Electric Kettle 59.90 and Gift Card 25.00. Keywords are not case-sensitive (select is the same as SELECT); writing them in capitals is a common convention. A semicolon ends the statement.

Here’s that query running — the three most expensive products that are in stock:

SQL
SELECT name, price
FROM products
WHERE stock > 0
ORDER BY price DESC
LIMIT 3;
Text
      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:

SQL
SELECT first_name, city
FROM customers
WHERE country = 'UK';
Text
 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, SELECT and Select are 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 */.
SQL
-- Products in category 2 (Tea)
select name,     price
  from products   where category_id = 2   /* tea only */ ;
Text
          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:

SQL
SELECT first_name FROM customers WHERE city = "Pune";
Text
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:

SQL
SELECT name, prise FROM products;
Text
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:

SQL
SELECT first_name last_name city
FROM customers;
Text
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.

Exercise

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.

SQL
SELECT first_name, last_name, city
FROM customers
-- keep only customers in India, then sort 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.