Naming Columns with AS
A calculated column is named by its calculation, such as quantity * price. That's long, and it changes with every space you type. AS gives a column a name of your own, an alias:
SELECT title, price - 5 AS sale_price
FROM games;| title | sale_price |
|---|---|
| Dragon Forge | 35 |
| Pixel Racer | 10 |
| Moon Farm | 15 |
| … | … |
The alias is the column's name in the result only; the table doesn't change. Write aliases like the names of columns: in lowercase, without spaces, with the words joined by underscores. You can rename ordinary columns too: SELECT title AS game is handy when the result goes to someone who doesn't know the names of the columns.
You can use an alias in ORDER BY, so that you don't have to write the calculation twice: ORDER BY sale_price DESC sorts the games by their price in the sale. ORDER BY price - 5 DESC would work too, but the alias is shorter and clearer.
An alias with spaces must be in double quotes: AS "sale price". It works, but then you have to write the quotes every time you use the alias, so programmers prefer underscores.
Remember the missing comma from the first lesson? AS can be left out: SELECT title price FROM games; is a query with one column, the titles, named price. That's why a missing comma doesn't give an error. Always write AS: then everyone can see that the new name is there on purpose.
Instructions
The query in the editor calculates what the customer paid for each item. Name its last column total, and sort the items by it, from the largest; the items with the same total by the order ID:
| order_id | game_id | total |
|---|---|---|
| 22 | 14 | 60 |
| 26 | 15 | 60 |
| 27 | 15 | 60 |
| … | … | … |
Below it, prepare a list of games for the shop's website: the title and the genre of every game, sorted by title. The website expects the title in a column named game and the genre in a column named category:
| game | category |
|---|---|
| Bakery Story | Simulation |
| Castle Siege | Strategy |
| Cube Logic | Puzzle |
| … | … |
Start programming for free
7/9