Choosing columns

Lesson 3 of 18 · SQL foundations

A query asks for a result, without changing the stored rows. SELECT names the result columns; FROM chooses the table. SQL keywords are conventionally uppercase, but SQLite accepts lowercase too. A semicolon ends each statement in these examples. Single quotes delimit text values; identifiers name tables and columns.

SELECT title, pages FROM books ORDER BY id;
title pages
Moss Atlas 120
River Notes 80
Clay Roads 200
Night Sky NULL

SELECT * requests every column, but naming columns makes a query’s output explicit. AS gives a result column a temporary name, not a schema change:

SELECT title AS book_title, pages + 10 AS extended_pages FROM books ORDER BY id;

The calculated page counts are 130, 90, 210, and NULL: arithmetic with an unknown remains unknown. SELECT DISTINCT shelf_id FROM books returns each distinct selected value once, including one NULL. With multiple columns, DISTINCT applies to the whole selected combination. Without ORDER BY, result order is not guaranteed.

Chapter index · Course index