Select, Filter and Sort · Problem 8 of 118

Last Names Starting with S

MediumSelect, Filter and SortShop data

A printed customer directory needs the "S" page.

Return the last_name and first_name of every customer whose last name starts with the letter S (upper-case S), sorted by last_name, then first_name, then customer_id.

Only return customer_id as a tie-breaker in the sorting; it does not have to be in the output.

Hint 1

LIKE 'S%' means "starts with S"; % stands for any number of characters.

Reference solution

SELECT last_name, first_name
FROM customers
WHERE last_name LIKE 'S%'
ORDER BY last_name, first_name, customer_id;

% matches any run of characters, _ matches exactly one. In SQLite, LIKE ignores the case of English letters, so 'S%' also matches names starting with a lower-case s; this data has none, and the SUBSTR version is case-sensitive. Different databases treat case differently, so always test with your own data. Sorting by a column you do not output (customer_id) is allowed and is a good way to break ties.

Another way. SUBSTR takes the first letter and compares it exactly.

SELECT last_name, first_name
FROM customers
WHERE SUBSTR(last_name, 1, 1) = 'S'
ORDER BY last_name, first_name, customer_id;