Calculate and Name Columns
Part of the First Queries section of Coddy's PostgreSQL journey. Lesson 11 of 20.
A SELECT expression computes a value for each row. Multiplication uses *. AS gives a result column a readable name; it does not rename the source column.
Input table products:
id | name | category | price | stock | active | note |
|---|---|---|---|---|---|---|
1 | Map | travel | 12 | 5 | True | NULL |
2 | Notebook | books | 8 | 0 | True | Recycled |
3 | Atlas | books | 24 | 3 | False | NULL |
4 | Mug | home | 12 | 8 | True | Blue |
5 | lamp | home | 30 | 2 | False | Clearance |
6 | Mini map | travel | 6 | 10 | True | NULL |
SELECT id, price * 2 AS pair_price FROM products ORDER BY id;For Map, two units cost 24, so pair_price is 24. The expression is calculated independently for each product. A column alias describes the result without changing the stored price.
Calculate in the SELECT list and name expressions with AS.
Challenge
EasyReturn id and inventory_value, defined as price times stock, for every product. Order by id.
The input tables are shown in the test panel. Each run starts from fresh data. Return the named columns in the stated order; do not hard-code the displayed rows.
Try it yourself
-- Write your SQL here.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in First Queries
3Build Useful Results
Calculate and Name ColumnsUnique Results with DISTINCTLabels with CASEFallbacks with COALESCEPacking LabelsPractice on your own: PostgreSQL playground