B4Coder
0%
LessonAbout 6 min

Chapter 1 · Lesson 3 of 5

03. Sums and new column names

Work things out in a query with + - * /, and name the new column with AS.

A query can work things out as it goes. Here, each student's age next year is their age + 1. The table doesn't change: the sum is only in the result.

SQL
SELECT name, age, age + 1 FROM students;

Result

name    | age | age + 1
--------+-----+--------
Asha    | 15  | 16
Ravi    | 16  | 17
Meera   | 14  | 15
Arjun   | 15  | 16
Divya   | 14  | 15
Karthik | 16  | 17
Priya   | 17  | 18
Rahul   | 14  | 15
Sneha   | 15  | 16
Vikram  | 16  | 17

That last column is called age + 1, which isn't a good name. AS gives it a better one. Names with no spaces are easiest: next_year, not next year.

SQL
SELECT name, age + 1 AS next_year FROM students;

Result

name    | next_year
--------+----------
Asha    | 16
Ravi    | 17
Meera   | 15
Arjun   | 16
Divya   | 15
Karthik | 17
Priya   | 18
Rahul   | 15
Sneha   | 16
Vikram  | 17

Your turn

1Steps

  1. 1The subjects table has how many periods a week each subject gets. A month of school is 4 weeks.
  2. 2Show each subject's name, and its periods in a month (its periods times 4) in a column called periods_a_month.

Write it in query.sql. The tables are in the Tables tab, beside Results.

Use: FROM, AS

Starting code

The editor starts empty. Copy this into it to begin, or write your own from scratch.

SQL
SELECT name, periods FROM subjects;

2Expected output

Your query should show

nameperiods_a_month
Maths24
Science24
English20
Tamil16
Social Science16

5 rows, in any order. The column names count too.

3Hints

Stuck? Open one hint at a time: each gives a bit more help.

Hint 1

The second column should be a sum: the periods times 4.

Hint 2

Multiply with *: periods * 4. Then name the column with AS.

Hint 3

The second column is periods * 4 AS periods_a_month.

query.sql