SELECT to work. These get a little harder as you go. Try writing
each query yourself before you open the solution.
We are using the series tables:
-
users (id, name, email, country, created_at)
-
orders (id, user_id, total, status, created_at)
-
products (id, name, price, category)
-
order_items (id, order_id, product_id, quantity)
1. Grab one column
Return the name of every user.
Solution
SELECT name
FROM users;
SELECT names the column, FROM names the table. The simplest query there is.
2. Grab a few columns
Return the name, email, and country of every user, in that order.
Solution
SELECT name, email, country
FROM users;
List the columns with commas between them. They come back in the order you
wrote them, so you control the shape of the result.
3. Fix the lazy query
A teammate wrote SELECT * FROM products; but the page only needs the product
name and price. Rewrite it the safe way.
Solution
SELECT name, price
FROM products;
Naming the columns means you only pull what you need, and the query does not
break if someone adds a new column to products later.
4. Rename for the API
The front end expects the product name in a field called title and the price
in a field called cost. Return those two columns with the new names.
Solution
SELECT name AS title,
price AS cost
FROM products;
AS renames the column only in the result. The real table keeps its original
column names. This is how you match what an API or front end expects.
5. Unique list
Return the list of distinct categories in the products table, so each
category shows up only once.
Solution
SELECT DISTINCT category
FROM products;
DISTINCT removes repeated values. Perfect for filling a filter or a dropdown
menu without showing "tech" five times.
6. Unique countries, renamed
Return the unique countries your users come from, but show the column as
user_country in the result.
Solution
SELECT DISTINCT country AS user_country
FROM users;
You can stack ideas: DISTINCT strips the duplicates, and AS renames the
output. SQL lets you combine small tools to get exactly what you want.
Nice work. You can now pull the exact columns you need, rename them, and trim
duplicates. In Part 03 you will add WHERE, so you can ask for only the rows
that match a condition. Keep going, ninja.