Only the columns you need
Problem
The newsletter list
The shop sends a newsletter with offers. Your colleague in marketing needs only the customers' names and emails.
SELECT * gives everything: id, city, sign-up date. With 20 customers they will delete the rest by hand. With 200,000 and ten columns, they will not.
The idea
List the columns
Instead of *, write the columns you want, separated by commas:
The columns come in the order you wrote them. Swap them and run again.
This holds for every query from now on: take only what you need. The database sends less data, and whoever reads the query sees exactly what is used.
Try it
The price list
Show only the name and price of each product.
Solution
SELECT name, price FROM products;Two columns, 25 rows. Exactly what you would put on the shelf.
See it
One comma
This query looks almost like the first one. Run it:
The idea
Other names with AS
A column can be shown under another name. That is called an alias and is written with AS:
A name without spaces is written as it is. If it has spaces, put it in double quotes. Single quotes in SQL are for text; you will use them in the next lesson.
An alias does not change the table. It only changes the column heading in this result.
Try it
The stock
Show the name and stock of the products, but call the columns product and in_stock.
Solution
SELECT name AS product, stock AS in_stock FROM products;SELECT name AS product, stock AS in_stock FROM products; Here the check also looks at the column names.
Exercise
The orders in brief
For each order show its number, date and status, without the customer.
Solution
SELECT id, ordered_at, status FROM orders;Three columns: id, ordered_at, status. 60 rows, one per order.
Test