Work out new values from the columns: arithmetic, names for results, joining text, and the functions for text and numbers.
Arithmetic
After SELECT you can write not only columns but expressions (calculations) on them. Each order line has a quantity (qty) and a price; their product is what the line costs:
SELECT order_id, product_id, qty, price, qty * price FROM order_item WHERE order_id <= 3ORDERBY order_id, product_id;
order_id
product_id
qty
price
qty * price
1
1
2
55.0
110.0
1
4
2
35.0
70.0
2
7
3
25.0
75.0
2
8
1
90.0
90.0
3
1
1
55.0
55.0
3
6
1
120.0
120.0
6 rows
The calculation is done for each row, and the table itself doesn't change. The operators:
As chapter 2 showed, a whole number divided by a whole number gives a whole number: 7 / 2 is 3, the rest dropped (towards zero, so -7 / 2 is -3). With a decimal point on either side, 7.0 / 2, you get 3.5.
/ and % together are handy: how many full boxes of 12 does each product's stock fill, and how many are left over?
Whole-number division bites hardest with percentages. 30 out of 200 is 15%, yet 30 / 200 * 100 gives 0: 30 / 200 is worked out first, and as whole numbers it is 0. Multiplying first, 30 * 100 / 200, gives 15; making one number decimal, 30 * 100.0 / 200, gives 15.0. And dividing by zero gives NULL, not an error:
When both sides of / are whole numbers, the fraction is lost. For a percentage or an average, put a decimal point on one side (100.0), or multiply before you divide.
AS: a name for a result column
A calculated column is named after its expression, qty * price, which reads poorly. AS gives it a name of your choosing (an alias):
SELECT order_id, qty * price AS line_total FROM order_item WHERE order_id <= 3ORDERBY order_id, product_id;
order_id
line_total
1
110.0
1
70.0
2
75.0
2
90.0
3
55.0
3
120.0
6 rows
AS works on ordinary columns too. A name with spaces or other unusual characters goes in double quotes, since it is a name (chapter 3). Thai VAT is 7%, so the price with VAT is the price times 1.07:
SELECT name AS product, price * 1.07AS "price with VAT" FROM product WHERE category_id = 1;
product
price with VAT
Coffee
58.85
Green Tea
48.15
Orange Juice
42.8
3 rows
The alias names the column of the result; it doesn't rename anything in the table. You can sort by it (ORDER BY line_total, as in chapter 6). SQLite and Phai SQL let you use it in WHERE as well:
SELECT order_id, qty * price AS line_total FROM order_item WHERE line_total > 200;
order_id
line_total
8
300.0
9
240.0
15
300.0
3 rows
Many other databases refuse that, because by the standard WHERE is worked out before the SELECT list. If your SQL may one day run elsewhere, write the calculation again in WHERE: WHERE qty * price > 200.
Joining text with ||
|| joins pieces of text into one (concatenation). A customer's name with the city in brackets:
SELECT name || ' (' || city || ')'AS who FROM customer;
who
Somchai Jaidee (Bangkok)
Malee Srisuk (Chiang Mai)
Anan Wongsa (Bangkok)
Pim Chaiya (Phuket)
Narin Thongdee (Khon Kaen)
Kanya Boonmee (Chiang Mai)
Wichai Saelim (Bangkok)
Siriporn Kaewdee (Phuket)
Tawan Rungruang (Khon Kaen)
Lalita Meesuk (Bangkok)
10 rows
Remember chapter 5: anything joined with NULL is NULL. Anan has no phone, so his whole line is gone:
SELECT name || ', tel. ' || phone AS contact FROM customer WHERE city = 'Bangkok';
contact
Somchai Jaidee, tel. 081-234-5678
NULL
Wichai Saelim, tel. 083-999-0000
Lalita Meesuk, tel. 087-654-3210
4 rows
coalesce(phone, '-') in place of phone would keep the line.
Functions for text
A function takes values in brackets and gives one value back. The common ones for text:
Function
Gives
upper(t), lower(t)
the text in capitals, or in small letters
length(t)
how many characters
substr(t, start, n)
n characters from position start (the first character is 1)
replace(t, a, b)
the text with every a changed to b
trim(t), ltrim(t), rtrim(t)
the text without spaces at both ends, the left, the right
instr(t, a)
where a first appears in t (0 if it doesn't)
SELECTupper(name), lower(name), length(name) FROM product WHERE category_id = 1;
upper(name)
lower(name)
length(name)
COFFEE
coffee
6
GREEN TEA
green tea
9
ORANGE JUICE
orange juice
12
3 rows
length counts characters, not bytes: 'กาแฟ' is 4 characters (ก า แ ฟ):
Functions can be put inside one another. instr(name, ' ') finds the space between first name and surname; substr up to just before it gives the first name:
SELECT name, instr(name, ' ') AS space_at, substr(name, 1, instr(name, ' ') - 1) AS first_name FROM customer;
name
space_at
first_name
Somchai Jaidee
8
Somchai
Malee Srisuk
6
Malee
Anan Wongsa
5
Anan
Pim Chaiya
4
Pim
Narin Thongdee
6
Narin
Kanya Boonmee
6
Kanya
Wichai Saelim
7
Wichai
Siriporn Kaewdee
9
Siriporn
Tawan Rungruang
6
Tawan
Lalita Meesuk
7
Lalita
10 rows
Types: typeof() and CAST
Every value has a type. typeof() says which: integer (whole number), real (number with a fraction), text, blob (raw bytes) or null. In the shop, price is real and stock is integer:
SELECTtypeof(1), typeof(1.0), typeof('1'), typeof(NULL), typeof(price), typeof(stock) FROM product WHERE id = 1;
typeof(1)
typeof(1.0)
typeof('1')
typeof(NULL)
typeof(price)
typeof(stock)
integer
real
text
null
real
integer
1 row
CAST(value AS type) turns a value into another type. Text to a number, a fraction to a whole number (the fraction is dropped, not rounded), a whole number to REAL to avoid whole-number division:
Turning text into a number reads the digits at the start and stops at the first character that isn't one: '12abc' gives 12, and 'abc' gives 0, with no error. Arithmetic does the same by itself; || turns numbers into text:
SELECT'3' + 4, '3' || 4, '3 apples' + 4;
'3' + 4
'3' || 4
'3 apples' + 4
7
34
7
1 row
Because a bad number quietly becomes 0 instead of an error, check data that comes from outside (a file, a form) before calculating with it. typeof() shows what is really in a column.
Numbers for people: round, abs, printf
round(x, n) rounds to n decimal places (without n, to a whole number, but still a real). Halves go away from zero: 2.5 becomes 3, -2.5 becomes -3. abs(x) drops the minus sign:
SELECT name, price, round(price * 1.07, 2) AS with_vat FROM product;
name
price
with_vat
Coffee
55.0
58.85
Green Tea
45.0
48.15
Orange Juice
40.0
42.8
Croissant
35.0
37.45
Banana Bread
60.0
64.2
Cheesecake
120.0
128.4
Potato Chips
25.0
26.75
Dried Mango
90.0
96.3
Cashew Nuts
150.0
160.5
Notebook
30.0
32.1
Pen
15.0
16.05
Highlighter
25.0
26.75
12 rows
round gives a number, so 42.8 still shows one decimal place. To show a number in a fixed form, use printf() (format() is the same function under another name). It takes a template text, with a % sign for each value:
SELECT name, printf('%8.2f', price) AS price, format('%s: %d left', name, stock) AS note FROM product WHERE category_id = 3;
name
price
note
Potato Chips
25.00
Potato Chips: 200 left
Dried Mango
90.00
Dried Mango: 45 left
Cashew Nuts
150.00
Cashew Nuts: 20 left
3 rows
printf gives text. Use it for the last step, showing; keep calculating and sorting with the numbers themselves (sorted as text, '150.00' would come before '25.00').
Show each order line's order_id, product_id and what the line costs, named total.
Show each customer's name in capitals, and how many characters it has.
Show each product's price and its price with 7% VAT, rounded to 2 decimal places.
Show a label for each product like Coffee: 55.00 baht.
Show the answer
SELECT order_id, product_id, qty * price AS total FROM order_item;
SELECTupper(name) AS name, length(name) AS letters FROM customer;
SELECT name, price, round(price * 1.07, 2) AS with_vat FROM product;
SELECTprintf('%s: %.2f baht', name, price) AS label FROM product;
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made