DWH Interview Question 9 - What's wrong with keeping everything in one flat table?

Data Warehouse Interview Q&A · Question 9

In this post we are going to cover a question that sets up normalization: what's wrong with keeping everything in one flat table? One wide table with every column looks simple, and spreadsheets work that way, so why not a database?

The problem is redundancy: a flat table stores the same facts again and again in many rows. Redundancy causes three classic problems, called anomalies: the update anomaly, the insert anomaly and the delete anomaly.

We will build TB Shop's orders as one flat table and break it in all three ways, two of them with real SQL. Then we will fix it by storing each fact once, and finish with the case where repeating data is actually fine.

Question 9 of the Real DWH Question and Answers series on TechBrothersIT.

The interview answer

Say this first

A single flat table stores the same facts in many rows (redundancy). That causes three anomalies: an update anomaly (a fact changed in one row but not the others), an insert anomaly (you can't store a new product until someone orders it), and a delete anomaly (deleting an order also deletes the only record of a customer or product). Normalization fixes them.

Let's create some sample data

We create one wide orders_flat table with everything about an order in one place: order, customer, city, product, category, price and quantity. We also create orders_flat_copy, an untouched copy that we use at the end to build the fixed design.

Sample data — run this first
DROP TABLE IF EXISTS orders_flat;
DROP TABLE IF EXISTS orders_flat_copy;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS products;

-- everything about an order, in ONE wide table
CREATE TABLE orders_flat (
  order_id INT PRIMARY KEY,
  customer VARCHAR(50),
  city     VARCHAR(50),
  product  VARCHAR(50),
  category VARCHAR(50),
  price    DECIMAL(10,2),
  qty      INT
);
INSERT INTO orders_flat VALUES
  (1001, 'Sara Khan', 'Toronto', 'Laptop Stand',   'Accessories', 35.00, 1),
  (1002, 'Omar Ali',  'Dallas',  'Wireless Mouse', 'Electronics', 25.00, 1),
  (1003, 'Sara Khan', 'Toronto', 'Desk Lamp',      'Home',        30.00, 1),
  (1004, 'Lina Park', 'Seattle', 'Laptop Stand',   'Accessories', 35.00, 2),
  (1005, 'Sara Khan', 'Toronto', 'USB-C Cable',    'Accessories',  9.00, 3);

-- an untouched copy, used at the end to build the fixed design
CREATE TABLE orders_flat_copy (
  order_id INT PRIMARY KEY,
  customer VARCHAR(50),
  city     VARCHAR(50),
  product  VARCHAR(50),
  category VARCHAR(50),
  price    DECIMAL(10,2),
  qty      INT
);
INSERT INTO orders_flat_copy SELECT * FROM orders_flat;

Here is the flat table.

Query
SELECT * FROM orders_flat ORDER BY 1;
Result5 rows · 7 columns
order_idcustomercityproductcategorypriceqty
1001Sara KhanTorontoLaptop StandAccessories35.001
1002Omar AliDallasWireless MouseElectronics25.001
1003Sara KhanTorontoDesk LampHome30.001
1004Lina ParkSeattleLaptop StandAccessories35.002
1005Sara KhanTorontoUSB-C CableAccessories9.003

Look at Sara Khan. Her name and her city are written on every one of her orders: 1001, 1003 and 1005. And the Laptop Stand: its category and price are repeated on every order of that product.

Step 1: Redundancy - how many times is each customer stored?

Let's count the copies. This query groups the flat table by customer and city and counts how many rows carry each one.

Query
SELECT customer, city, COUNT(*) AS times_stored
FROM orders_flat
GROUP BY customer, city
ORDER BY times_stored DESC, customer;
Result3 rows · 3 columns
customercitytimes_stored
Sara KhanToronto3
Lina ParkSeattle1
Omar AliDallas1

Sara Khan and Toronto are stored three times. Lina Park and Omar Ali are stored once each, only because they have one order each so far. In a real shop with millions of orders, that is millions of copies of the same few facts, and every copy is a chance for the data to disagree.

Step 2: The update anomaly

Sara moves to Ottawa. The app updates the city on her latest order, order 1005, and stops there. Let's run that update, and then ask the table where Sara lives.

Statement
UPDATE orders_flat
SET city = 'Ottawa'
WHERE order_id = 1005;

Now let's check the result.

Query
SELECT DISTINCT customer, city
FROM orders_flat
WHERE customer = 'Sara Khan'
ORDER BY city;
Result2 rows · 2 columns
customercity
Sara KhanOttawa
Sara KhanToronto

The table gives two answers: Ottawa and Toronto. The data contradicts itself, and every report that groups by city is now wrong. To avoid this, every copy must be updated every time. In a flat table, someone always misses one.

The insert anomaly

TB Shop starts selling a new product, a Monitor Arm, at 45.00. Nobody has ordered it yet. Where do we store it? The only table is the orders table, so the row would look like this:

orders_flat3 rows · 5 columns
order_idcustomerproductcategoryprice
1001Sara KhanLaptop StandAccessories35.00
1003Sara KhanDesk LampHome30.00
NULLNULLMonitor ArmAccessories45.00

The new row has no order and no customer. But order_id is the primary key, and a primary key cannot be NULL, so the database rejects it. The business cannot record a simple fact, a new product and its price, until some unrelated event happens: someone has to order it first.

Step 3: The delete anomaly

Omar cancels order 1002. It was his only order, and also the only order of the Wireless Mouse. We only want to remove one order, so let's delete that one row and then check which products the table still knows about.

Statement
DELETE FROM orders_flat
WHERE order_id = 1002;

Now let's check the result.

Query
SELECT DISTINCT product
FROM orders_flat
ORDER BY product;
Result3 rows · 1 column
product
Desk Lamp
Laptop Stand
USB-C Cable

Only three products are left: Desk Lamp, Laptop Stand and USB-C Cable. The Wireless Mouse is gone, and so is every trace of Omar Ali. We wanted to delete an order, and we also lost a customer and a product.

Step 4: The fix - store each fact once

The fix is to store each fact once, in its own table. Customers go into a customers table with one row each, and products into a products table with one row each. Orders then only need to point to them. We build both from the untouched orders_flat_copy, because the original table was damaged by the last two steps.

Statement
CREATE TABLE customers (customer VARCHAR(50), city VARCHAR(50));
INSERT INTO customers
SELECT DISTINCT customer, city FROM orders_flat_copy;

CREATE TABLE products (
  product VARCHAR(50), category VARCHAR(50), price DECIMAL(10,2));
INSERT INTO products
SELECT DISTINCT product, category, price FROM orders_flat_copy;

Now let's check the result.

Query
SELECT * FROM customers ORDER BY customer;
Result3 rows · 2 columns
customercity
Lina ParkSeattle
Omar AliDallas
Sara KhanToronto

Three customers, one row each: Lina Park in Seattle, Omar Ali in Dallas and Sara Khan in Toronto. Sara is now stored once, so moving her to Ottawa would be one update, in one row. A new product like the Monitor Arm is just a new row in products, and deleting an order never deletes a product or a customer. This process has a name, normalization, and it is the next question in the series.

When is a flat table OK?

This is the follow-up that separates good candidates from great ones: is a flat, repeated table always bad? No.

In a data warehouse, dimension tables repeat data on purpose. A customer dimension stores city, state and country on every customer row instead of splitting them out. That is safe because users never edit warehouse tables directly. A controlled pipeline loads them, so all the copies are written together and the anomalies cannot happen.

Who writes the data?Redundancy is...
OLTP tablesMany users and applicationsa problem: anomalies
Warehouse dimensionsOne controlled pipelinea tool: simpler, faster reads
Wide reports, exportsGenerated, read-onlyfine

Redundancy is a problem where many users and applications write data. It is a tool where pipelines write and people only read.

Say this

Normalize systems that take writes; denormalize on purpose for analysis.

Follow-up questions interviewers ask

Is redundancy always bad?

No. Warehouse dimensions are denormalized on purpose; they are loaded by controlled pipelines, not edited by users, so anomalies are avoided.

Which anomaly is the most common in practice?

The update anomaly: copies drifting apart, producing contradicting reports.

The full script

Here is everything from this post in one script. Copy it and run it top to bottom.

Full script — copy and run top to bottom
-- ========================================================================
-- Data Warehouse Interview Q&A #9 - What is wrong with one flat table?
-- TechBrothersIT. Sample data is invented for teaching.
-- Standard SQL, tested on PostgreSQL 16. Runs top to bottom in one go.
-- Run it in an empty database or schema: other videos reuse table names
-- like dim_customer, and their leftover tables can block the DROPs below.
-- PostgreSQL example:  CREATE SCHEMA dwh_q09;  SET search_path TO dwh_q09;
-- ========================================================================

-- Step 0: create and load the sample data
DROP TABLE IF EXISTS orders_flat;
DROP TABLE IF EXISTS orders_flat_copy;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS products;

-- everything about an order, in ONE wide table
CREATE TABLE orders_flat (
  order_id INT PRIMARY KEY,
  customer VARCHAR(50),
  city     VARCHAR(50),
  product  VARCHAR(50),
  category VARCHAR(50),
  price    DECIMAL(10,2),
  qty      INT
);
INSERT INTO orders_flat VALUES
  (1001, 'Sara Khan', 'Toronto', 'Laptop Stand',   'Accessories', 35.00, 1),
  (1002, 'Omar Ali',  'Dallas',  'Wireless Mouse', 'Electronics', 25.00, 1),
  (1003, 'Sara Khan', 'Toronto', 'Desk Lamp',      'Home',        30.00, 1),
  (1004, 'Lina Park', 'Seattle', 'Laptop Stand',   'Accessories', 35.00, 2),
  (1005, 'Sara Khan', 'Toronto', 'USB-C Cable',    'Accessories',  9.00, 3);

-- an untouched copy, used at the end to build the fixed design
CREATE TABLE orders_flat_copy (
  order_id INT PRIMARY KEY,
  customer VARCHAR(50),
  city     VARCHAR(50),
  product  VARCHAR(50),
  category VARCHAR(50),
  price    DECIMAL(10,2),
  qty      INT
);
INSERT INTO orders_flat_copy SELECT * FROM orders_flat;


-- Step 1: Redundancy: how many times is each customer stored?
SELECT customer, city, COUNT(*) AS times_stored
FROM orders_flat
GROUP BY customer, city
ORDER BY times_stored DESC, customer;

-- Step 2: Update anomaly: Sara moves, but only one row gets updated
UPDATE orders_flat
SET city = 'Ottawa'
WHERE order_id = 1005;

-- check the result
SELECT DISTINCT customer, city
FROM orders_flat
WHERE customer = 'Sara Khan'
ORDER BY city;

-- Step 3: Delete anomaly: cancel Omar's only order
DELETE FROM orders_flat
WHERE order_id = 1002;

-- check the result
SELECT DISTINCT product
FROM orders_flat
ORDER BY product;

-- Step 4: The fix: store each fact once, in its own table
CREATE TABLE customers (customer VARCHAR(50), city VARCHAR(50));
INSERT INTO customers
SELECT DISTINCT customer, city FROM orders_flat_copy;

CREATE TABLE products (
  product VARCHAR(50), category VARCHAR(50), price DECIMAL(10,2));
INSERT INTO products
SELECT DISTINCT product, category, price FROM orders_flat_copy;

-- check the result
SELECT * FROM customers ORDER BY customer;

Key points

  • Redundancy: the same facts copied into many rows
  • Update anomaly: one copy changes, the others don't
  • Insert anomaly: can't store a fact until something else exists
  • Delete anomaly: deleting a row loses other facts
  • Fix: store each fact once (normalization)
Next in this series

Question 10 — Normalization: 1NF, 2NF, 3NF What is normalization? Explain 1NF, 2NF and 3NF.

Every query and every result on this page was run on PostgreSQL 16 using the script above. The SQL is standard and runs on most databases with small changes (noted in the script). All tables and data are invented demo data for teaching.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.