7. Calculations and functions

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 <= 3 ORDER BY order_id, product_id;
order_idproduct_idqtypriceqty * price
11255.0110.0
14235.070.0
27325.075.0
28190.090.0
31155.055.0
361120.0120.0
6 rows

The calculation is done for each row, and the table itself doesn't change. The operators:

OperatorMeans7 and 2 give
+add9
-subtract5
*multiply14
/divide3 (!)
%remainder after dividing1
SELECT 7 + 2, 7 - 2, 7 * 2, 7 / 2, 7 % 2, 7.0 / 2, -7 / 2, -7 % 2;
7 + 27 - 27 * 27 / 27 % 27.0 / 2-7 / 2-7 % 2
9514313.5-3-1
1 row

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?

SELECT name, stock, stock / 12, stock % 12 FROM product WHERE stock > 0;
namestockstock / 12stock % 12
Coffee120100
Green Tea8068
Croissant3026
Banana Bread1210
Cheesecake808
Potato Chips200168
Dried Mango4539
Cashew Nuts2018
Notebook7563
Pen300250
10 rows

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:

SELECT 30 / 200 * 100, 30 * 100 / 200, 30 * 100.0 / 200, 1 / 0;
30 / 200 * 10030 * 100 / 20030 * 100.0 / 2001 / 0
01515.0NULL
1 row

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 <= 3 ORDER BY order_id, product_id;
order_idline_total
1110.0
170.0
275.0
290.0
355.0
3120.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.07 AS "price with VAT" FROM product WHERE category_id = 1;
productprice with VAT
Coffee58.85
Green Tea48.15
Orange Juice42.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_idline_total
8300.0
9240.0
15300.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:

FunctionGives
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)
SELECT upper(name), lower(name), length(name) FROM product WHERE category_id = 1;
upper(name)lower(name)length(name)
COFFEEcoffee6
GREEN TEAgreen tea9
ORANGE JUICEorange juice12
3 rows

length counts characters, not bytes: 'กาแฟ' is 4 characters (ก า แ ฟ):

SELECT length('Coffee'), length('กาแฟ'), length(''), length(NULL);
length('Coffee')length('กาแฟ')length('')length(NULL)
640NULL
1 row

substr cuts out a piece. Without a length, it goes to the end; a negative start counts from the end:

SELECT name, substr(name, 1, 3), substr(name, -3), substr(name, 4) FROM product WHERE category_id = 2;
namesubstr(name, 1, 3)substr(name, -3)substr(name, 4)
CroissantCroantissant
Banana BreadBaneadana Bread
CheesecakeCheakeesecake
3 rows

replace takes the dashes out of phone numbers, and trim removes the spaces people type by mistake (the brackets show where the text begins and ends):

SELECT name, phone, replace(phone, '-', '') AS digits FROM customer WHERE phone IS NOT NULL;
namephonedigits
Somchai Jaidee081-234-56780812345678
Malee Srisuk089-111-22220891112222
Pim Chaiya086-555-01010865550101
Narin Thongdee082-777-88880827778888
Kanya Boonmee084-246-13570842461357
Wichai Saelim083-999-00000839990000
Tawan Rungruang085-123-45670851234567
Lalita Meesuk087-654-32100876543210
8 rows
SELECT '[' || trim('  Coffee  ') || ']', '[' || ltrim('  Coffee  ') || ']', '[' || rtrim('  Coffee  ') || ']';
'[' || trim(' Coffee ') || ']''[' || ltrim(' Coffee ') || ']''[' || rtrim(' Coffee ') || ']'
[Coffee][Coffee ][ Coffee]
1 row

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;
namespace_atfirst_name
Somchai Jaidee8Somchai
Malee Srisuk6Malee
Anan Wongsa5Anan
Pim Chaiya4Pim
Narin Thongdee6Narin
Kanya Boonmee6Kanya
Wichai Saelim7Wichai
Siriporn Kaewdee9Siriporn
Tawan Rungruang6Tawan
Lalita Meesuk7Lalita
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:

SELECT typeof(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)
integerrealtextnullrealinteger
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:

SELECT CAST('42' AS INTEGER) + 1, CAST(55.9 AS INTEGER), CAST(7 AS REAL) / 2, CAST(42 AS TEXT), CAST('12abc' AS INTEGER), CAST('abc' AS INTEGER);
CAST('42' AS INTEGER) + 1CAST(55.9 AS INTEGER)CAST(7 AS REAL) / 2CAST(42 AS TEXT)CAST('12abc' AS INTEGER)CAST('abc' AS INTEGER)
43553.542120
1 row

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
7347
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 round(55 * 1.07, 2), round(58.85), round(2.5), round(-2.5), round(1234.5678, 1), abs(-15), abs(15);
round(55 * 1.07, 2)round(58.85)round(2.5)round(-2.5)round(1234.5678, 1)abs(-15)abs(15)
58.8559.03.0-3.01234.61515
1 row

Prices with 7% VAT, rounded to satang (2 places):

SELECT name, price, round(price * 1.07, 2) AS with_vat FROM product;
namepricewith_vat
Coffee55.058.85
Green Tea45.048.15
Orange Juice40.042.8
Croissant35.037.45
Banana Bread60.064.2
Cheesecake120.0128.4
Potato Chips25.026.75
Dried Mango90.096.3
Cashew Nuts150.0160.5
Notebook30.032.1
Pen15.016.05
Highlighter25.026.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:

In the templateShows
%da whole number
%.2fa number with 2 decimal places
%stext
%,da whole number with commas every 3 digits
%5d, %-8spadded to 5 (8) characters, on the right (left)
%%a real %
SELECT printf('%.2f', 55), printf('%d items', 12), printf('%5d|', 42), printf('%-8s|', 'Pen'), printf('%,d', 1234567), printf('%.1f%%', 12.345);
printf('%.2f', 55)printf('%d items', 12)printf('%5d|', 42)printf('%-8s|', 'Pen')printf('%,d', 1234567)printf('%.1f%%', 12.345)
55.0012 items 42|Pen |1,234,56712.3%
1 row
SELECT name, printf('%8.2f', price) AS price, format('%s: %d left', name, stock) AS note FROM product WHERE category_id = 3;
namepricenote
Potato Chips 25.00Potato Chips: 200 left
Dried Mango 90.00Dried Mango: 45 left
Cashew Nuts 150.00Cashew 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').

  1. Show each order line's order_id, product_id and what the line costs, named total.
  2. Show each customer's name in capitals, and how many characters it has.
  3. Show each product's price and its price with 7% VAT, rounded to 2 decimal places.
  4. 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;
SELECT upper(name) AS name, length(name) AS letters FROM customer;
SELECT name, price, round(price * 1.07, 2) AS with_vat FROM product;
SELECT printf('%s: %.2f baht', name, price) AS label FROM product;
order_idproduct_idtotal
11110.0
1470.0
2890.0
2775.0
36120.0
3155.0
410150.0
411150.0
59150.0
62180.0
6560.0
6750.0
7155.0
78180.0
811300.0
81090.0
96240.0
94140.0
91110.0
10245.0
28 rows (the first 20 shown)
nameletters
SOMCHAI JAIDEE14
MALEE SRISUK12
ANAN WONGSA11
PIM CHAIYA10
NARIN THONGDEE14
KANYA BOONMEE13
WICHAI SAELIM13
SIRIPORN KAEWDEE16
TAWAN RUNGRUANG15
LALITA MEESUK13
10 rows
namepricewith_vat
Coffee55.058.85
Green Tea45.048.15
Orange Juice40.042.8
Croissant35.037.45
Banana Bread60.064.2
Cheesecake120.0128.4
Potato Chips25.026.75
Dried Mango90.096.3
Cashew Nuts150.0160.5
Notebook30.032.1
Pen15.016.05
Highlighter25.026.75
12 rows
label
Coffee: 55.00 baht
Green Tea: 45.00 baht
Orange Juice: 40.00 baht
Croissant: 35.00 baht
Banana Bread: 60.00 baht
Cheesecake: 120.00 baht
Potato Chips: 25.00 baht
Dried Mango: 90.00 baht
Cashew Nuts: 150.00 baht
Notebook: 30.00 baht
Pen: 15.00 baht
Highlighter: 25.00 baht
12 rows

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