Numbers and math

Topic 3 of 5 in Working with values11 min readBeginnerFree course

Overview

Shops are full of numbers: prices, quantities, stock levels, discounts, shipping fees, tax. SQL does arithmetic on every row as easily as a spreadsheet, but there are a few traps — especially around types — that produce wrong answers without any error. This lesson covers the operators and functions you’ll use most, and how to avoid those traps.

Choosing a number type

Numbers in SQL. integer and bigint store whole numbers such as 42 or -7, used for ids, counts and quantities. numeric(10, 2) stores exact decimals such as 19.99, used for money and prices, with no rounding errors. double precision and real store approximate floating-point numbers, used for measurements and science; 0.1 + 0.2 = 0.30000000000000004. Watch out for integer division: SELECT 7 / 2 gives 3, because both sides are integers and the result is an integer; SELECT 7 / 2.0 gives 3.5000000000000000; SELECT round(7 / 2.0, 1), 7 % 2 gives 3.5 and 1.

Type Holds Use for
integer whole numbers up to about ±2.1 billion ids, counts, quantities, stock
bigint whole numbers up to about ±9.2 × 10¹⁸ ids in huge tables, byte counts
numeric(p, s) exact decimals: p digits in total, s after the point money, prices, percentages, anything that must add up exactly
double precision approximate floating point, about 15 significant digits measurements, scientific values, coordinates

The Bean & Leaf prices are numeric(10,2): up to ten digits, two after the decimal point.

Why not use floating point for money? Because floating-point numbers are stored in binary, and most decimal fractions can’t be represented exactly:

SQL
SELECT 0.1::double precision + 0.2::double precision AS float_sum,
       0.1::numeric + 0.2::numeric                   AS numeric_sum;
Text
      float_sum      | numeric_sum 
---------------------+-------------
 0.30000000000000004 |         0.3
(1 row)

That tiny error is harmless for a temperature reading and unacceptable on an invoice — add up enough of them and your accounts don’t balance. numeric is exact. (A plain 0.1 in PostgreSQL is already numeric, so you get exact maths unless you ask for floats.)

Arithmetic operators

Operator Meaning Example Result
+ - * / the usual four 10 / 4.0 2.5
% remainder (modulo) 17 % 5 2
^ power 2 ^ 10 1024
@ or abs() absolute value abs(-7) 7

Normal precedence applies — *, / and % before + and - — and brackets change it. Every row gets its own calculation:

SQL
SELECT order_id, product_id, quantity, unit_price,
       quantity * unit_price AS line_total
FROM order_items
WHERE order_id = 2;
Text
 order_id | product_id | quantity | unit_price | line_total 
----------+------------+----------+------------+------------
        2 |          9 |        1 |      89.00 |      89.00
        2 |          2 |        2 |      12.00 |      24.00
(2 rows)

The integer division trap

When both sides of / are integers, PostgreSQL performs integer division and throws away the remainder:

SQL
SELECT 7 / 2      AS int_division,
       7 / 2.0    AS numeric_division,
       7 % 2      AS remainder,
       -7 / 2     AS negative;
Text
 int_division |  numeric_division  | remainder | negative 
--------------+--------------------+-----------+----------
            3 | 3.5000000000000000 |         1 |       -3
(1 row)

Integer division truncates toward zero, so -7 / 2 is -3, not -4. This bites hardest when you calculate a ratio of two integer columns — say, what fraction of products are out of stock — and get 0 every time. Cast one side to numeric:

SQL
SELECT 2 / 12                 AS wrong,
       2::numeric / 12        AS right,
       round(100.0 * 2 / 12, 1) AS percent;
Text
 wrong |         right          | percent 
-------+------------------------+---------
     0 | 0.16666666666666666667 |    16.7
(1 row)

Multiplying by 100.0 (a numeric) at the start is a common idiom for percentages: it makes the whole calculation numeric.

Integer division and % are genuinely useful when you want whole units — how many boxes of 6 can we fill, and how many items are left?

SQL
SELECT name, stock,
       stock / 6 AS boxes_of_6,
       stock % 6 AS loose
FROM products
WHERE category_id = 1;
Text
         name          | stock | boxes_of_6 | loose 
-----------------------+-------+------------+-------
 Ethiopian Yirgacheffe |    40 |          6 |     4
 Colombian Supremo     |    55 |          9 |     1
 Decaf House Blend     |     0 |          0 |     0
(3 rows)

Other databases: SQL Server and SQLite also do integer division on integers. MySQL’s / always returns a decimal, and it has a separate DIV operator for integer division.

Rounding

Function What it does x = 26.325 x = -2.5
round(x) nearest whole number 26 -3
round(x, 2) nearest, to 2 decimal places 26.33 -2.50
ceil(x) round up 27 -2
floor(x) round down 26 -3
trunc(x, 1) chop off digits 26.3 -2.5

For numeric values, round rounds halves away from zero (so 26.325 becomes 26.33). Here they are on real data — the average product price:

SQL
SELECT avg(price)            AS exact,
       round(avg(price), 2)  AS rounded,
       ceil(avg(price))      AS ceiling,
       floor(avg(price))     AS floor,
       trunc(avg(price), 1)  AS truncated
FROM products;
Text
        exact        | rounded | ceiling | floor | truncated 
---------------------+---------+---------+-------+-----------
 26.3250000000000000 |   26.33 |      27 |    26 |      26.3
(1 row)

avg is an aggregate function — it combines all twelve prices into one value. You’ll study aggregates properly in the next chapter.

Round at the end. Do calculations at full precision and round only the final result. Rounding each line before adding them up can make totals drift by a cent or two.

Mixing types

When an expression combines different number types, PostgreSQL converts to the more general one: integer → numeric → double precision. quantity * unit_price is integer × numeric, so the result is numeric. If you need a particular type, cast explicitly:

SQL
SELECT 3 * 1.5             AS int_times_numeric,
       (3 * 1.5)::integer  AS cast_to_integer,
       12.75::int          AS rounds_not_truncates,
       '19.99'::numeric(5,1) AS fewer_decimals;
Text
 int_times_numeric | cast_to_integer | rounds_not_truncates | fewer_decimals 
-------------------+-----------------+----------------------+----------------
               4.5 |               5 |                   13 |           20.0
(1 row)

Casting to integer or to fewer decimal places rounds; it doesn’t chop. Use trunc if you need to cut digits off.

Handy number functions

SQL
SELECT greatest(4.99, 6.50, 0) AS largest,
       least(4.99, 6.50, 0)    AS smallest,
       sqrt(2)                 AS square_root,
       power(1.05, 3)          AS three_years_at_5pct,
       sign(-12)               AS sign;
Text
 largest | smallest |    square_root     | three_years_at_5pct | sign 
---------+----------+--------------------+---------------------+------
    6.50 |        0 | 1.4142135623730951 |  1.1576250000000000 |   -1
(1 row)

greatest and least compare values across a row — for example, greatest(shipping_fee, 5.00) charges a minimum fee of $5. (random() returns a random number between 0 and 1; it’s useful for sampling rows, but its output changes on every run, so it isn’t shown here.)

Formatting numbers for people

For reports, to_char formats a number with a pattern: 9 is a digit, 0 a digit that’s always shown, G a thousands separator, D the decimal point and FM removes padding:

SQL
SELECT name,
       price * stock                                   AS raw_value,
       to_char(price * stock, 'FM999G999D00')          AS formatted,
       '$' || to_char(price * stock, 'FM999G999D00')   AS with_currency
FROM products
WHERE id IN (1, 12);
Text
         name          | raw_value | formatted | with_currency 
-----------------------+-----------+-----------+---------------
 Ethiopian Yirgacheffe |    580.00 | 580.00    | $580.00
 Gift Card             |  24975.00 | 24,975.00 | $24,975.00
(2 rows)

Formatting turns numbers into text, so do it last, only for display — you can’t sum or sort formatted values correctly. Most applications and BI tools format numbers themselves and expect the raw numbers from SQL.

Tip: if a number looks wrong, check its type with pg_typeof: SELECT pg_typeof(7 / 2), pg_typeof(7 / 2.0); returns integer and numeric.

Exercise

Line totals and boxes

Two calculations for the operations team. First, for the items in order 21, return product_id, quantity, unit_price, a line_total (quantity × unit price) and a discounted column showing the line total with 15% off, rounded to 2 decimal places, sorted by product_id. Second, teas are packed in boxes of 12: for every product in category 2, return its name, stock, how many full_boxes of 12 its stock fills, and how many units are left_over, sorted by name.

SQL
-- 1. Order 21 line totals with 15% off
SELECT product_id, quantity, unit_price
FROM order_items
WHERE order_id = 21;

-- 2. Full boxes of 12 and leftovers for each tea

Summary

  • Use integer types for counts, numeric for money and other exact decimals, and double precision only for measurements where tiny rounding errors don't matter.
  • Dividing two integers gives an integer (7 / 2 = 3); make one side numeric to keep the fraction.
  • % gives the remainder, ^ raises to a power, and abs, round, ceil, floor and trunc tidy up results.
  • round(x, 2) rounds to 2 decimal places; round half away from zero applies to numeric values.
  • Mixing types promotes to the more precise one; use CAST or :: when you need a specific type.