Numbers in SQL: Rounding, Division, Median, Mode and Percentiles
Working with numbers in SQL: ROUND, TRUNC, FLOOR and CEIL and how each rounds negative values and halves, safe division with NULLIF, percentages of a total, median and percentiles with PERCENTILE_CONT and PERCENTILE_DISC, the mode, standard deviation and z-scores, and the other math functions.
kvi5hnuCode Sprout team member12 min readOn this page
Numeric work in SQL goes beyond SUM and AVG. Reports need values rounded the right way, percentages that add up, divisions that don't fail on zero, and statistics that describe data better than an average, such as the median, percentiles and the standard deviation.
This article covers those tools. Article 35 explained the numeric types and integer division. Here the focus is on what you do with the values. The examples use the shop database and the daily takings table from Part 6.
Rounding: ROUND, TRUNC, FLOOR and CEIL
-- ROUND, TRUNC, FLOOR and CEIL on positive and negative values
SELECT x,
ROUND(x) AS round_0,
ROUND(x, 1) AS round_1,
ROUND(x, -1) AS round_tens,
TRUNC(x) AS trunc_0,
FLOOR(x) AS floor_x,
CEIL(x) AS ceil_x
FROM (VALUES (2.45), (2.5), (-2.5), (-2.45), (17.35)) AS t(x);
-- Floating-point values round half to even in PostgreSQL
SELECT ROUND(CAST(2.5 AS double precision)) AS float_2_5,
ROUND(CAST(3.5 AS double precision)) AS float_3_5,
ROUND(2.5) AS numeric_2_5;
x | round_0 | round_1 | round_tens | trunc_0 | floor_x | ceil_x
-------+---------+---------+------------+---------+---------+--------
2.45 | 2 | 2.5 | 0 | 2 | 2 | 3
2.5 | 3 | 2.5 | 0 | 2 | 2 | 3
-2.5 | -3 | -2.5 | 0 | -2 | -3 | -2
-2.45 | -2 | -2.5 | 0 | -2 | -3 | -2
17.35 | 17 | 17.4 | 20 | 17 | 17 | 18
(5 rows)
float_2_5 | float_3_5 | numeric_2_5
-----------+-----------+-------------
2 | 4 | 3
(1 row)
The four functions differ in direction:
| Function | Rounds | 2.5 | −2.5 | 17.35 |
|---|---|---|---|---|
ROUND(x) | to the nearest integer, halves away from zero | 3 | −3 | 17 |
TRUNC(x) | towards zero, dropping the fraction | 2 | −2 | 17 |
FLOOR(x) | down, towards minus infinity | 2 | −3 | 17 |
CEIL(x) | up, towards plus infinity | 3 | −2 | 18 |
ROUND(x, n)andTRUNC(x, n)keepndecimal places. A negativenrounds to tens, hundreds and so on:ROUND(17.35, -1)is 20.FLOORandTRUNCagree for positive numbers and differ for negative ones:FLOOR(-2.5)is −3,TRUNC(-2.5)is −2. UseFLOORfor "which bucket is this value in" calculations (article 46) andTRUNCfor "drop the fraction".CEIL(orCEILING) is useful for "how many boxes":CEIL(units / 12.0)boxes of 12.
Halves: away from zero or to even?
There are two common rules for a value exactly halfway between two results:
- Half away from zero: 2.5 → 3, −2.5 → −3, 3.5 → 4. This is what most people learned at school, and what PostgreSQL, MySQL, SQL Server and Oracle do for exact (
DECIMAL) values. - Half to even ("banker's rounding"): 2.5 → 2, 3.5 → 4. Halves go to the nearest even digit, so over many values the rounding errors cancel out instead of pushing totals up. PostgreSQL, MySQL and Oracle (for
BINARY_DOUBLE) use it for floating-point values, as the second query shows.
With floating-point values, there's a further twist: most "halves" aren't exactly halves. As a floating-point number, 2.675 is really 2.67499999..., so SQLite, which stores it that way, rounds ROUND(2.675, 2) to 2.67. Round DECIMAL values when exact results matter.
Names differ slightly: SQL Server has no TRUNC and uses ROUND(x, n, 1) to truncate. MySQL uses TRUNCATE(x, n). SQL Server's CEILING and FLOOR don't take a number of decimal places.
Rounding and totals
Rounding each value and then adding them up can give a different total from rounding the sum. Three items of 33.333 each round to 33.33, which totals 99.99, while the unrounded sum, 99.999, rounds to 100.00. Reports that show rounded lines next to a rounded total can therefore appear not to add up. Either round only the final results, or compute the total from the rounded lines, and be consistent.
Division: zero, NULL and percentages
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Units sold per product (0 for products never ordered)
CREATE VIEW units_sold AS
SELECT p.product_id, p.name, p.category, COALESCE(SUM(oi.qty), 0) AS units
FROM products p
LEFT JOIN order_items oi ON oi.product_id = p.product_id
GROUP BY p.product_id, p.name, p.category;
\pset null '(null)'
-- Dividing by zero is an error...
SELECT 10 / 0;
-- ...so NULLIF turns a zero divisor into NULL, and the result is NULL instead
SELECT p.name,
p.stock,
u.units AS units_sold,
ROUND(CAST(p.stock AS numeric) / NULLIF(u.units, 0), 1) AS stock_per_unit_sold
FROM products p
JOIN units_sold u ON u.product_id = p.product_id
ORDER BY p.product_id;
-- Each category's share of the total stock, as a percentage
SELECT category,
SUM(stock) AS stock,
ROUND(100.0 * SUM(stock) / SUM(SUM(stock)) OVER (), 1) AS pct_of_total
FROM products
GROUP BY category
ORDER BY pct_of_total DESC;
psql:/workspace/solution.sql:72: ERROR: division by zero
name | stock | units_sold | stock_per_unit_sold
-------------------+-------+------------+---------------------
Ridge 2 tent | 12 | 1 | 12.0
Summit 4 tent | 3 | 1 | 3.0
Glow head torch | 40 | 3 | 13.3
Basecamp lantern | 15 | 0 | (null)
Trail 30 backpack | 22 | 1 | 22.0
Day 18 backpack | 0 | 1 | 0.0
Merino socks | 75 | 6 | 12.5
(7 rows)
category | stock | pct_of_total
----------+-------+--------------
clothing | 75 | 44.9
lighting | 55 | 32.9
packs | 22 | 13.2
tents | 15 | 9.0
(4 rows)
Division by zero is an error in PostgreSQL, SQL Server and Oracle, and one zero in the data makes the whole query fail. The standard fix is NULLIF(divisor, 0), which turns a zero divisor into NULL (article 8), so the division returns NULL for that row instead of failing. The lantern hasn't sold any units, so its ratio is NULL. Wrap the result in COALESCE(..., 0) if a report needs a number there, but think first about whether 0 is a true answer: "no stock per unit sold" isn't the same as "infinitely much".
MySQL and SQLite return NULL for division by zero rather than an error. MySQL raises an error only when inserting or updating data in strict mode.
The second query computes each category's share of the total. SUM(SUM(stock)) OVER () is a window function over the grouped rows (article 26): it adds up the per-category sums to give the grand total on every row. Multiplying by 100.0 before dividing avoids integer division. The rounded percentages here add up to 100.0, but in general they may add up to 99.9 or 100.1.
Median and percentiles
The average (mean) is easily distorted by a few extreme values. The median, the middle value of the sorted data, isn't. For prices, salaries, response times and house prices, the median usually describes a "typical" value better.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Average versus median: one expensive tent pulls the average up
SELECT ROUND(AVG(price), 2) AS average,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY price) AS median_cont,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price) AS median_disc,
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY price) AS first_quartile,
ROUND(CAST(PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY price) AS numeric), 2) AS third_quartile
FROM products;
-- With an even number of values, CONT interpolates and DISC picks a real value
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) AS median_cont,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY amount) AS median_disc
FROM (VALUES (10), (20), (30), (40)) AS t(amount);
-- The most frequent value: MODE()
SELECT MODE() WITHIN GROUP (ORDER BY qty) AS most_common_qty,
MODE() WITHIN GROUP (ORDER BY unit_price) AS most_common_price
FROM order_items;
average | median_cont | median_disc | first_quartile | third_quartile
---------+-------------+-------------+----------------+----------------
137.21 | 54 | 54.00 | 30.75 | 169.97
(1 row)
median_cont | median_disc
-------------+-------------
25 | 20
(1 row)
most_common_qty | most_common_price
-----------------+-------------------
1 | 16.00
(1 row)

The average price is 137.21, more than all but two of the products, because the two tents pull it up. The median is 54.00, the Day 18 backpack, with three products cheaper and three dearer.
PostgreSQL has two percentile functions, both written as ordered-set aggregates with WITHIN GROUP (ORDER BY ...):
PERCENTILE_CONT(f)("continuous") returns the value at fractionfof the way through the sorted data, interpolating between two values if necessary. With 10, 20, 30 and 40, the median falls between 20 and 30, so it returns 25. It always returnsdouble precision, so round the result with a cast tonumeric.PERCENTILE_DISC(f)("discrete") returns an actual value from the data: the first value whose position reaches the fraction. For 10, 20, 30 and 40, it returns 20. It keeps the column's type.
PERCENTILE_CONT(0.25) and PERCENTILE_CONT(0.75) give the first and third quartiles: a quarter of the prices are below 30.75, and three quarters below 169.97. The 0.9, 0.95 and 0.99 percentiles are common for response times ("p95"). PostgreSQL also accepts an array, PERCENTILE_CONT(ARRAY[0.25, 0.5, 0.75]), and returns an array of results.
MODE() returns the most frequent value. The most common order quantity is 1. For unit prices there's a tie, 16.00 and 34.50 twice each, and MODE returns 16.00, the first in the ORDER BY: when several values are equally common, MODE returns the first one in that order.
Support varies a lot:
| Database | Median and percentiles |
|---|---|
| PostgreSQL | PERCENTILE_CONT, PERCENTILE_DISC and MODE as aggregates |
| Oracle | the same, plus MEDIAN(x) and STATS_MODE(x) |
| SQL Server | PERCENTILE_CONT and PERCENTILE_DISC only as window functions, with OVER (PARTITION BY ...). SQL Server 2022 added APPROX_PERCENTILE_CONT as an aggregate |
| MySQL | none. Compute the median with ROW_NUMBER and COUNT (below) |
| MariaDB | PERCENTILE_CONT, PERCENTILE_DISC and MEDIAN as window functions |
| SQLite | median() and percentile() from the percentile extension, built into the command-line shell |
Without percentile functions, the median can be computed with window functions:
SELECT AVG(price) AS median
FROM (SELECT price,
ROW_NUMBER() OVER (ORDER BY price) AS rn,
COUNT(*) OVER () AS n
FROM products) AS t
WHERE rn IN (FLOOR((n + 1) / 2.0), CEIL((n + 1) / 2.0));
With an odd number of rows, both positions are the middle row. With an even number, they're the two middle rows, and AVG interpolates between them, like PERCENTILE_CONT.
Spread: standard deviation and variance
The average and median describe the centre of the data. The standard deviation describes how spread out it is: roughly, how far a typical value is from the mean.
-- Daily takings of a market stall; no trading on 4 March
CREATE TABLE daily_sales (
day DATE PRIMARY KEY,
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO daily_sales VALUES
(DATE '2026-03-01', 120.00),
(DATE '2026-03-02', 80.00),
(DATE '2026-03-03', 150.00),
(DATE '2026-03-05', 60.00),
(DATE '2026-03-06', 200.00),
(DATE '2026-03-07', 90.00),
(DATE '2026-03-08', 110.00);
-- Spread: standard deviation and variance of daily takings
SELECT ROUND(AVG(amount), 2) AS mean,
ROUND(STDDEV_SAMP(amount), 2) AS stddev_sample,
ROUND(STDDEV_POP(amount), 2) AS stddev_population,
ROUND(VAR_SAMP(amount), 2) AS variance_sample,
MIN(amount) AS lowest, MAX(amount) AS highest
FROM daily_sales;
-- z-score: how many standard deviations each day is from the mean
SELECT day,
amount,
ROUND((amount - AVG(amount) OVER ()) / STDDEV_SAMP(amount) OVER (), 2) AS z_score
FROM daily_sales
ORDER BY z_score DESC;
mean | stddev_sample | stddev_population | variance_sample | lowest | highest
--------+---------------+-------------------+-----------------+--------+---------
115.71 | 47.21 | 43.71 | 2228.57 | 60.00 | 200.00
(1 row)
day | amount | z_score
------------+--------+---------
2026-03-06 | 200.00 | 1.79
2026-03-03 | 150.00 | 0.73
2026-03-01 | 120.00 | 0.09
2026-03-08 | 110.00 | -0.12
2026-03-07 | 90.00 | -0.54
2026-03-02 | 80.00 | -0.76
2026-03-05 | 60.00 | -1.18
(7 rows)
STDDEV_SAMP(orSTDDEV) andVAR_SAMP(orVARIANCE) treat the data as a sample of a larger population and divide byn − 1.STDDEV_POPandVAR_POPtreat it as the whole population and divide byn. Use the sample versions unless the data really is everything there is. With many rows, the difference is small.- The variance is the square of the standard deviation, in squared units, which makes the standard deviation easier to interpret.
The second query computes a z-score for each day: how many standard deviations its takings are from the mean. 6 March, at 1.79, is the most unusual day. Values beyond about ±2 or ±3 are common thresholds for flagging outliers. Window aggregates with OVER () put the mean and standard deviation on every row, so no join is needed.
SQL Server names these functions STDEV, STDEVP, VAR and VARP. MySQL has STDDEV_SAMP, STDDEV_POP and friends. SQLite has none built in.
Other math functions
-- More numeric functions
SELECT ABS(-7.5) AS abs_value,
SIGN(-7.5) AS sign_value,
MOD(17, 5) AS mod_value,
POWER(2, 10) AS power_value,
SQRT(144) AS sqrt_value,
ROUND(LN(10.0), 4) AS natural_log,
ROUND(EXP(1.0), 4) AS e,
GREATEST(3, 9, 4) AS greatest_value,
LEAST(3, 9, 4) AS least_value;
-- Compound growth: 1,000 at 5% a year for 10 years, and the yearly rate that doubles it
SELECT ROUND(1000 * POWER(1.05, 10), 2) AS after_10_years,
ROUND(100 * (POWER(2, 1.0 / 10) - 1), 2) AS pct_to_double_in_10;
abs_value | sign_value | mod_value | power_value | sqrt_value | natural_log | e | greatest_value | least_value
-----------+------------+-----------+-------------+------------+-------------+--------+----------------+-------------
7.5 | -1 | 2 | 1024 | 12 | 2.3026 | 2.7183 | 9 | 3
(1 row)
after_10_years | pct_to_double_in_10
----------------+---------------------
1628.89 | 7.18
(1 row)
| Function | Returns |
|---|---|
ABS(x) | the absolute value |
SIGN(x) | −1, 0 or 1 |
MOD(a, b) or a % b | the remainder of a / b (its sign follows a: -7 % 3 is −1) |
POWER(x, y) | x to the power y |
SQRT(x) | the square root |
LN(x), LOG(x), EXP(x) | natural logarithm, base-10 logarithm (PostgreSQL), e to the power x |
GREATEST(...), LEAST(...) | the largest or smallest of several values in one row |
GREATEST and LEAST compare values within a row, while MAX and MIN compare values across rows. They're available in PostgreSQL, MySQL, Oracle, SQLite (as multi-argument MAX and MIN) and SQL Server 2022+. In PostgreSQL they ignore NULLs, while in MySQL and Oracle any NULL argument makes the result NULL.
POWER handles growth calculations. 1,000 growing at 5% a year for 10 years is 1000 * POWER(1.05, 10) = 1,628.89. The yearly rate that doubles a value in 10 years is POWER(2, 1.0 / 10) - 1, about 7.18%.
With one argument, LOG is the base-10 logarithm in PostgreSQL and SQLite, but the natural logarithm in MySQL and SQL Server. Oracle's LOG requires the base as the first argument. When in doubt, use LN, or LOG10 where it exists.
Random numbers come from RANDOM() in PostgreSQL and SQLite, RAND() in MySQL and SQL Server, and DBMS_RANDOM.VALUE in Oracle. PostgreSQL 17 added random(min, max) for random integers or decimals in a range.
Trends and robust outliers
Two more statistical tools come up in reports. Linear regression fits a straight line through points, for a trend or a simple forecast. The standard REGR_SLOPE, REGR_INTERCEPT and REGR_R2 aggregates, in PostgreSQL and Oracle, calculate it directly. And the median absolute deviation (MAD) finds outliers more reliably than the standard deviation, which a single extreme value inflates:
-- A linear trend: fit units = slope * week + intercept, and forecast week 9
CREATE TABLE weekly (week INTEGER PRIMARY KEY, units INTEGER);
INSERT INTO weekly VALUES (1, 102), (2, 108), (3, 115), (4, 119), (5, 128), (6, 131), (7, 140), (8, 144);
SELECT ROUND(REGR_SLOPE(units, week)::numeric, 3) AS slope,
ROUND(REGR_INTERCEPT(units, week)::numeric, 3) AS intercept,
ROUND(REGR_R2(units, week)::numeric, 4) AS r_squared,
ROUND((REGR_SLOPE(units, week) * 9 + REGR_INTERCEPT(units, week))::numeric, 1) AS forecast_week_9
FROM weekly;
-- Outliers by median absolute deviation, which a single extreme value can't distort
WITH amounts (v) AS (VALUES (20), (22), (19), (24), (21), (23), (250)),
med AS (SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY v) AS m FROM amounts),
mad AS (SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ABS(v - m)) AS d FROM amounts, med)
SELECT v, ABS(v - m) / d AS deviations, ABS(v - m) / d > 3.5 AS outlier
FROM amounts, med, mad
ORDER BY v;
slope | intercept | r_squared | forecast_week_9
-------+-----------+-----------+-----------------
6.083 | 96.000 | 0.9939 | 150.8
(1 row)
v | deviations | outlier
-----+------------+---------
19 | 1.5 | f
20 | 1 | f
21 | 0.5 | f
22 | 0 | f
23 | 0.5 | f
24 | 1 | f
250 | 114 | t
(7 rows)
Sales grow by about 6.08 units a week from a base of 96, and REGR_R2 close to 1 means the line fits well, so the forecast for week 9 is about 151. Forecasts from a straight line are only as good as the assumption that the trend continues.
In the second query, the median is 22 and the median distance from it is 2, so 250 is 114 MADs away. A common rule flags values more than about 3.5 MADs from the median. A z-score (above) with the usual threshold of 3 would miss it: the outlier inflates the standard deviation so much that its own z-score is only about 2.3.
What's current
- PostgreSQL 17 added
random(min, max). PostgreSQL 16 addedrandom_normal()for normally distributed random numbers. - SQL Server 2022 added
GREATEST,LEAST, andAPPROX_PERCENTILE_CONTandAPPROX_PERCENTILE_DISCas fast approximate percentile aggregates. - SQLite ships a percentile extension with
median(),percentile(),percentile_cont()andpercentile_disc(), which the command-line shell includes. - MySQL 9 still has no median or percentile function.
Common questions
Why does ROUND(2.5) give 3 but ROUND(2.5::float) give 2?
Exact values round halves away from zero, and floating-point values round halves to even in PostgreSQL and MySQL.
How do I avoid division-by-zero errors?
Divide by NULLIF(divisor, 0). The result is NULL where the divisor is zero.
What's the difference between PERCENTILE_CONT and PERCENTILE_DISC?
PERCENTILE_CONT interpolates between values and may return a value that isn't in the data. PERCENTILE_DISC always returns an actual value from the data.
How do I calculate a median in MySQL?
Number the rows with ROW_NUMBER(), count them with COUNT(*) OVER (), and average the middle one or two rows.
Should I use STDDEV_SAMP or STDDEV_POP?
STDDEV_SAMP when the data is a sample of something larger, which is the usual case. STDDEV_POP when it's the complete population.
Why don't my rounded percentages add up to 100? Each percentage is rounded separately. Show one more decimal place, or adjust the largest value so the total is exactly 100.
Summary
ROUNDrounds to the nearest value,TRUNCtowards zero,FLOORdown andCEILup. They differ on negative numbers.- Exact values round halves away from zero. Floating-point values round halves to even in PostgreSQL and MySQL.
- Divide by
NULLIF(divisor, 0)to avoid division-by-zero errors. Multiply by100.0before dividing for percentages. - The median,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x), resists outliers better than the average.PERCENTILE_DISCreturns an actual value.MODE()returns the most frequent value. - Percentile support varies: MySQL has none, and SQL Server only has window versions.
STDDEV_SAMPandVAR_SAMPmeasure spread. z-scores flag unusual values.
Practice questions
What do ROUND(-7.5), TRUNC(-7.5), FLOOR(-7.5) and CEIL(-7.5) return in PostgreSQL?
Answer
−8, −7, −8 and −7. ROUND rounds the half away from zero, TRUNC drops the fraction, FLOOR goes down and CEIL goes up.
Write a query that shows each order's total value and its percentage of all order value, rounded to one decimal place.
Answer
SELECT order_id,
SUM(qty * unit_price) AS order_value,
ROUND(100.0 * SUM(qty * unit_price) / SUM(SUM(qty * unit_price)) OVER (), 1) AS pct
FROM order_items
GROUP BY order_id
ORDER BY order_id;
Order 104 (489.00) is the largest, at 45.3% of the 1,080.44 total.
What do PERCENTILE_CONT(0.5) and PERCENTILE_DISC(0.5) return for the values 3, 5, 8 and 100?
Answer
PERCENTILE_CONT returns 6.5, halfway between the two middle values 5 and 8. PERCENTILE_DISC returns 5. The average would be 29, distorted by the 100.
A query computes SUM(refunds) / SUM(orders) per month and fails in one month. What's the likely cause and the fix?
Answer
A month where SUM(orders) is 0 makes the divisor zero. Divide by NULLIF(SUM(orders), 0) so that month returns NULL instead of failing. If both sums are integers, also multiply by 1.0 to avoid integer division.
Write a query that returns the days whose takings are more than one standard deviation above the mean.
Answer
SELECT day, amount
FROM (SELECT day, amount,
AVG(amount) OVER () AS mean,
STDDEV_SAMP(amount) OVER () AS sd
FROM daily_sales) AS t
WHERE amount > mean + sd
ORDER BY day;
Only 6 March (200.00) qualifies: the mean is 115.71 and the standard deviation 47.21, so the threshold is 162.92.
Previous: String Techniques in SQL: Splitting, Aggregating and Extracting Text
Next: Dates and Times in SQL: Types, Current Time, Parts, Formatting and Time Zones

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.