Database BI and Data Quality
What you will learn
- What business intelligence (BI) is
- What a KPI and a metric definition are
- Why metrics should be defined once
- Four basic data quality checks in SQL
- Why bad data can silently change a report
1. From tables to decisions
Business intelligence (BI) means turning data into information people use to decide: reports, dashboards, charts and ad-hoc questions. BI tools usually sit on top of a warehouse (lessons 13.1 to 13.3): they send SQL queries, then draw tables and charts from the answers.
A KPI (key performance indicator) is a number a team watches to judge how it is doing: monthly net sales, orders shipped on time, share of customers who come back. Choose a few that match real goals; a dashboard with fifty numbers helps nobody.
2. Define each metric once
"Sales" sounds simple, but two people may mean different things: Does it include returns? Taxes? Cancelled orders? If each dashboard builds its own formula, the company ends up with several different "sales" numbers and arguments about which is right.
The cure is to define each metric once, in one place that every report uses, and to write down the definition. In SQL, a view (lesson 4.7) is a natural home. We will use the sales warehouse from lesson 13.2 (six products, three stores, 181 days) and define net sales: the amount of valid sale rows, ignoring rows with a zero or negative quantity or a negative amount.
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds the tables of the small sales warehouse of lesson 13.2 to your browser's copy; run the examples from top to bottom, and Reset data starts again.
CREATE TABLE dim_date (date_key INTEGER PRIMARY KEY, full_date TEXT, month INTEGER, month_name TEXT, quarter INTEGER, year INTEGER);
CREATE TABLE dim_product (product_key INTEGER PRIMARY KEY, name TEXT, category TEXT, brand TEXT);
CREATE TABLE dim_store (store_key INTEGER PRIMARY KEY, name TEXT, city TEXT, region TEXT);
CREATE TABLE fact_sales (date_key INTEGER, product_key INTEGER, store_key INTEGER, quantity INTEGER, amount INTEGER);
INSERT INTO dim_product VALUES
(1, 'Tea 250g', 'Grocery', 'Hill'), (2, 'Rice 5kg', 'Grocery', 'Delta'),
(3, 'Notebook', 'Stationery', 'Page'), (4, 'Pen box', 'Stationery', 'Page'),
(5, 'Lamp', 'Home', 'Glow'), (6, 'Kettle', 'Home', 'Glow');
INSERT INTO dim_store VALUES
(1, 'Gulshan', 'Dhaka', 'Central'), (2, 'Mirpur', 'Dhaka', 'Central'), (3, 'Agrabad', 'Chattogram', 'South-East');
INSERT INTO dim_date
WITH RECURSIVE days(d) AS (SELECT date('2026-01-01') UNION ALL SELECT date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), d, CAST(strftime('%m', d) AS INTEGER),
substr('JanFebMarAprMayJun', (CAST(strftime('%m', d) AS INTEGER) - 1) * 3 + 1, 3),
(CAST(strftime('%m', d) AS INTEGER) - 1) / 3 + 1, CAST(strftime('%Y', d) AS INTEGER)
FROM days;
INSERT INTO fact_sales
WITH RECURSIVE days(i, d) AS (SELECT 0, date('2026-01-01') UNION ALL SELECT i + 1, date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), p.product_key, s.store_key,
(i + p.product_key * s.store_key) % 5 + 1,
((i + p.product_key * s.store_key) % 5 + 1) *
CASE p.product_key WHEN 1 THEN 120 WHEN 2 THEN 450 WHEN 3 THEN 60 WHEN 4 THEN 90 WHEN 5 THEN 700 ELSE 1200 END
FROM days CROSS JOIN dim_product p CROSS JOIN dim_store s
WHERE (i + p.product_key + s.store_key) % 4 = 0;
SELECT 'dim_date' AS table_name, COUNT(*) AS row_count FROM dim_date
UNION ALL SELECT 'dim_product', COUNT(*) FROM dim_product
UNION ALL SELECT 'dim_store', COUNT(*) FROM dim_store
UNION ALL SELECT 'fact_sales', COUNT(*) FROM fact_sales;
table_name row_count
----------- ---------
dim_date 181
dim_product 6
dim_store 3
fact_sales 815
(4 rows)
CREATE TABLE dim_date (date_key INTEGER PRIMARY KEY, full_date TEXT, month INTEGER, month_name TEXT, quarter INTEGER, year INTEGER);
CREATE TABLE dim_product (product_key INTEGER PRIMARY KEY, name TEXT, category TEXT, brand TEXT);
CREATE TABLE dim_store (store_key INTEGER PRIMARY KEY, name TEXT, city TEXT, region TEXT);
CREATE TABLE fact_sales (date_key INTEGER, product_key INTEGER, store_key INTEGER, quantity INTEGER, amount INTEGER);
INSERT INTO dim_product VALUES
(1, 'Tea 250g', 'Grocery', 'Hill'), (2, 'Rice 5kg', 'Grocery', 'Delta'),
(3, 'Notebook', 'Stationery', 'Page'), (4, 'Pen box', 'Stationery', 'Page'),
(5, 'Lamp', 'Home', 'Glow'), (6, 'Kettle', 'Home', 'Glow');
INSERT INTO dim_store VALUES
(1, 'Gulshan', 'Dhaka', 'Central'), (2, 'Mirpur', 'Dhaka', 'Central'), (3, 'Agrabad', 'Chattogram', 'South-East');
INSERT INTO dim_date
WITH RECURSIVE days(d) AS (SELECT date('2026-01-01') UNION ALL SELECT date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), d, CAST(strftime('%m', d) AS INTEGER),
substr('JanFebMarAprMayJun', (CAST(strftime('%m', d) AS INTEGER) - 1) * 3 + 1, 3),
(CAST(strftime('%m', d) AS INTEGER) - 1) / 3 + 1, CAST(strftime('%Y', d) AS INTEGER)
FROM days;
INSERT INTO fact_sales
WITH RECURSIVE days(i, d) AS (SELECT 0, date('2026-01-01') UNION ALL SELECT i + 1, date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), p.product_key, s.store_key,
(i + p.product_key * s.store_key) % 5 + 1,
((i + p.product_key * s.store_key) % 5 + 1) *
CASE p.product_key WHEN 1 THEN 120 WHEN 2 THEN 450 WHEN 3 THEN 60 WHEN 4 THEN 90 WHEN 5 THEN 700 ELSE 1200 END
FROM days CROSS JOIN dim_product p CROSS JOIN dim_store s
WHERE (i + p.product_key + s.store_key) % 4 = 0;
SELECT 'dim_date' AS table_name, COUNT(*) AS row_count FROM dim_date
UNION ALL SELECT 'dim_product', COUNT(*) FROM dim_product
UNION ALL SELECT 'dim_store', COUNT(*) FROM dim_store
UNION ALL SELECT 'fact_sales', COUNT(*) FROM fact_sales;
table_name row_count
----------- ---------
dim_date 181
dim_product 6
dim_store 3
fact_sales 815
(4 rows)
CREATE TABLE dim_date (date_key INTEGER PRIMARY KEY, full_date TEXT, month INTEGER, month_name TEXT, quarter INTEGER, year INTEGER);
CREATE TABLE dim_product (product_key INTEGER PRIMARY KEY, name TEXT, category TEXT, brand TEXT);
CREATE TABLE dim_store (store_key INTEGER PRIMARY KEY, name TEXT, city TEXT, region TEXT);
CREATE TABLE fact_sales (date_key INTEGER, product_key INTEGER, store_key INTEGER, quantity INTEGER, amount INTEGER);
INSERT INTO dim_product VALUES
(1, 'Tea 250g', 'Grocery', 'Hill'), (2, 'Rice 5kg', 'Grocery', 'Delta'),
(3, 'Notebook', 'Stationery', 'Page'), (4, 'Pen box', 'Stationery', 'Page'),
(5, 'Lamp', 'Home', 'Glow'), (6, 'Kettle', 'Home', 'Glow');
INSERT INTO dim_store VALUES
(1, 'Gulshan', 'Dhaka', 'Central'), (2, 'Mirpur', 'Dhaka', 'Central'), (3, 'Agrabad', 'Chattogram', 'South-East');
INSERT INTO dim_date
WITH RECURSIVE days(d) AS (SELECT date('2026-01-01') UNION ALL SELECT date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), d, CAST(strftime('%m', d) AS INTEGER),
substr('JanFebMarAprMayJun', (CAST(strftime('%m', d) AS INTEGER) - 1) * 3 + 1, 3),
(CAST(strftime('%m', d) AS INTEGER) - 1) / 3 + 1, CAST(strftime('%Y', d) AS INTEGER)
FROM days;
INSERT INTO fact_sales
WITH RECURSIVE days(i, d) AS (SELECT 0, date('2026-01-01') UNION ALL SELECT i + 1, date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), p.product_key, s.store_key,
(i + p.product_key * s.store_key) % 5 + 1,
((i + p.product_key * s.store_key) % 5 + 1) *
CASE p.product_key WHEN 1 THEN 120 WHEN 2 THEN 450 WHEN 3 THEN 60 WHEN 4 THEN 90 WHEN 5 THEN 700 ELSE 1200 END
FROM days CROSS JOIN dim_product p CROSS JOIN dim_store s
WHERE (i + p.product_key + s.store_key) % 4 = 0;
SELECT 'dim_date' AS table_name, COUNT(*) AS row_count FROM dim_date
UNION ALL SELECT 'dim_product', COUNT(*) FROM dim_product
UNION ALL SELECT 'dim_store', COUNT(*) FROM dim_store
UNION ALL SELECT 'fact_sales', COUNT(*) FROM fact_sales;
table_name row_count
----------- ---------
dim_date 181
dim_product 6
dim_store 3
fact_sales 815
(4 rows)
Before the view, a clean month: January's total in lesson 13.3 was 173,160. Now imagine that during a faulty load, four bad rows slipped into the fact table:
INSERT INTO fact_sales VALUES (20260101, 99, 1, 2, 500); -- product 99 does not exist
INSERT INTO fact_sales VALUES (20260102, 1, 1, -3, -360); -- negative quantity
INSERT INTO fact_sales VALUES (20260101, 2, 2, 5, 2250); -- a repeated row
INSERT INTO fact_sales VALUES (NULL, 1, 1, 1, 120); -- missing date
CREATE VIEW v_net_sales AS
SELECT d.month_name, SUM(f.amount) AS net_sales, SUM(f.quantity) AS units
FROM fact_sales f JOIN dim_date d ON d.date_key = f.date_key
WHERE f.quantity > 0 AND f.amount >= 0
GROUP BY d.month ORDER BY d.month;
SELECT * FROM v_net_sales LIMIT 3;
month_name net_sales units
---------- --------- -----
Jan 175910 423
Feb 176070 385
Mar 176030 413
(3 rows)
INSERT INTO fact_sales VALUES (20260101, 99, 1, 2, 500); -- product 99 does not exist
INSERT INTO fact_sales VALUES (20260102, 1, 1, -3, -360); -- negative quantity
INSERT INTO fact_sales VALUES (20260101, 2, 2, 5, 2250); -- a repeated row
INSERT INTO fact_sales VALUES (NULL, 1, 1, 1, 120); -- missing date
CREATE VIEW v_net_sales AS
SELECT d.month_name, SUM(f.amount) AS net_sales, SUM(f.quantity) AS units
FROM fact_sales f JOIN dim_date d ON d.date_key = f.date_key
WHERE f.quantity > 0 AND f.amount >= 0
GROUP BY d.month ORDER BY d.month;
SELECT * FROM v_net_sales LIMIT 3;
month_name net_sales units
---------- --------- -----
Jan 175910 423
Feb 176070 385
Mar 176030 413
(3 rows)
INSERT INTO fact_sales VALUES (20260101, 99, 1, 2, 500); -- product 99 does not exist
INSERT INTO fact_sales VALUES (20260102, 1, 1, -3, -360); -- negative quantity
INSERT INTO fact_sales VALUES (20260101, 2, 2, 5, 2250); -- a repeated row
INSERT INTO fact_sales VALUES (NULL, 1, 1, 1, 120); -- missing date
CREATE VIEW v_net_sales AS
SELECT d.month_name, SUM(f.amount) AS net_sales, SUM(f.quantity) AS units
FROM fact_sales f JOIN dim_date d ON d.date_key = f.date_key
WHERE f.quantity > 0 AND f.amount >= 0
GROUP BY d.month ORDER BY d.month;
SELECT * FROM v_net_sales LIMIT 3;
month_name net_sales units
---------- --------- -----
Jan 175910 423
Feb 176070 385
Mar 176030 413
(3 rows)
Look at January: 175,910 instead of 173,160. The difference, 2,750, is exactly the orphan row (500) plus the repeated row (2,250). The view's WHERE removed the negative row and the JOIN dropped the row with no date, so those two did no harm, but nothing caught the orphan or the duplicate, and the report is now wrong without any error message. That is why warehouses need data quality checks.
3. Four basic quality checks
Each check is a query that should return zero.
SELECT 'rows with a missing key' AS check_name, COUNT(*) AS bad_rows FROM fact_sales
WHERE date_key IS NULL OR product_key IS NULL OR store_key IS NULL
UNION ALL
SELECT 'orphans (no matching product)', COUNT(*) FROM fact_sales f
LEFT JOIN dim_product p ON p.product_key = f.product_key WHERE p.product_key IS NULL
UNION ALL
SELECT 'impossible values', COUNT(*) FROM fact_sales WHERE quantity <= 0 OR amount < 0
UNION ALL
SELECT 'duplicate rows', COUNT(*) FROM
(SELECT date_key, product_key, store_key, COUNT(*) AS c FROM fact_sales GROUP BY 1, 2, 3 HAVING c > 1);
check_name bad_rows
----------------------------- --------
rows with a missing key 1
orphans (no matching product) 1
impossible values 1
duplicate rows 1
(4 rows)
SELECT 'rows with a missing key' AS check_name, COUNT(*) AS bad_rows FROM fact_sales
WHERE date_key IS NULL OR product_key IS NULL OR store_key IS NULL
UNION ALL
SELECT 'orphans (no matching product)', COUNT(*) FROM fact_sales f
LEFT JOIN dim_product p ON p.product_key = f.product_key WHERE p.product_key IS NULL
UNION ALL
SELECT 'impossible values', COUNT(*) FROM fact_sales WHERE quantity <= 0 OR amount < 0
UNION ALL
SELECT 'duplicate rows', COUNT(*) FROM
(SELECT date_key, product_key, store_key, COUNT(*) AS c FROM fact_sales GROUP BY 1, 2, 3 HAVING c > 1);
check_name bad_rows
----------------------------- --------
rows with a missing key 1
orphans (no matching product) 1
impossible values 1
duplicate rows 1
(4 rows)
SELECT 'rows with a missing key' AS check_name, COUNT(*) AS bad_rows FROM fact_sales
WHERE date_key IS NULL OR product_key IS NULL OR store_key IS NULL
UNION ALL
SELECT 'orphans (no matching product)', COUNT(*) FROM fact_sales f
LEFT JOIN dim_product p ON p.product_key = f.product_key WHERE p.product_key IS NULL
UNION ALL
SELECT 'impossible values', COUNT(*) FROM fact_sales WHERE quantity <= 0 OR amount < 0
UNION ALL
SELECT 'duplicate rows', COUNT(*) FROM
(SELECT date_key, product_key, store_key, COUNT(*) AS c FROM fact_sales GROUP BY 1, 2, 3 HAVING c > 1);
check_name bad_rows
----------------------------- --------
rows with a missing key 1
orphans (no matching product) 1
impossible values 1
duplicate rows 1
(4 rows)
| Check | What it finds | Why it matters |
|---|---|---|
| Completeness (missing keys, unexpected NULLs) | rows that cannot be placed in a report | totals leave rows out silently |
| Referential integrity (orphans) | facts pointing to a dimension row that does not exist (lesson 3.5) | a join drops them, or a LEFT JOIN shows blanks |
| Validity (impossible values) | negative quantities, dates in the future | wrong sums and averages |
| Uniqueness (duplicates) | the same event loaded twice | totals are inflated |
Other common checks: freshness (did today's data arrive?), row counts (did the load bring about as many rows as usual?) and reconciliation (does the warehouse total match the source system's total?).
Run the checks after every load, before anyone opens a dashboard. Decide in advance what happens when one fails: stop the load, quarantine the bad rows, or alert a person. Lesson 13.4's habit of counting rows in, rejected and loaded is part of the same discipline.
4. Habits of good reporting
- Name the grain and the filter. "Net sales per month, valid rows only" beats "Sales".
- Show the date of the last load on every dashboard so readers know how fresh the numbers are.
- Keep definitions in a shared document (a business glossary) and in views or shared code, not in each report.
- Compare like with like. A partial month beside a full month looks like a drop that never happened.
- Choose charts honestly: start bars at zero, label units, and avoid decoration that hides the numbers.
- Control access. Reports may show personal or sensitive data; give people only what they need (chapter 8).
Worked example: investigate a surprising number
A manager says: "January net sales were 175,910 in the dashboard but finance says 173,160."
- Reproduce the number: the view gives 175,910.
- Find the gap: 175,910 − 173,160 = 2,750.
- Look for rows that explain it: run the four checks. Orphan: 1 row (500). Duplicate: 1 row (2,250). 500 + 2,250 = 2,750, so these two rows account for the whole gap.
- Fix the cause, not only the report: reject orphans and duplicate keys during the load (lessons 13.4 and 3.5).
- Add the checks to the load, so the same fault is caught the next time.
The investigation took one subtraction and four queries, because the metric was defined in one view and the checks existed.
Common mistakes
- Trusting a number because the query ran without errors. Wrong data produces smooth, wrong answers.
- Defining "sales" separately in every report.
- Fixing the dashboard but not the data feed.
- Hiding data quality problems instead of reporting them. Trust is lost the first time a number is wrong and nobody can explain it.
- Running quality checks rarely. Run them on every load.
Key takeaways
- BI turns warehouse data into reports and dashboards; KPIs are the few numbers a team watches.
- Define each metric once, write it down, and keep it in a shared view or code.
- Data quality checks are queries that should return zero: missing keys, orphans, impossible values, duplicates.
- Bad data does not raise errors; it silently changes totals, so run the checks after every load.
- Show freshness and definitions on every report.
Practice
1. What is a KPI?
Show answer
A key performance indicator: a number a team watches to judge how it is doing against a goal, such as monthly net sales.
2. Why is it risky for each dashboard to compute "sales" in its own way?
Show answer
Dashboards will show different numbers (for example with or without returns), and people will not know which is right. Define the metric once.
3. In the lesson, which two bad rows caused the extra 2,750 in January?
Show answer
The orphan row with product 99 (500) and the repeated row (2,250): 500 + 2,250 = 2,750.
4. Why did the negative-quantity row not change the view's January total?
Show answer
The view's WHERE quantity > 0 AND amount >= 0 filtered it out. (The row with a missing date was dropped by the JOIN.)
5. Write a query that counts fact rows whose store does not exist in dim_store.
Show answer
SELECT COUNT(*) FROM fact_sales f
LEFT JOIN dim_store s ON s.store_key = f.store_key
WHERE s.store_key IS NULL;
6. Name two checks other than the four in the lesson.
Show answer
For example: freshness (did the latest data arrive?), row-count comparison with earlier loads, and reconciliation with the source system's totals.