# Data Modeling and Databases by [kirupa](https://www.kirupa.com/me/index.htm) | filed under [Build Essentials](https://www.kirupa.com/build/index.htm) **TL;DR:** Before an app saves anything, someone decides what kinds of things it keeps track of, what it records about each one, and how those things point at each other. That plan is our data model (aka schema). A good one stores each fact in one place, links things with keys, and makes our real questions easy to answer. - Give each kind of thing its own table, with a primary key that never changes. Other tables point at that key with a foreign key instead of copying the details. - An order with many products needs a table in the middle, with one row per line. Copy each line's price onto that row on purpose, in whole cents. - An index works like the one at the back of a book. Lookups get much faster, and every write pays a little extra to keep the index current. - Change the shape in small migrations: add the new column, fill it in, switch the code, then remove the old one. Waiting to fix it later only gets more expensive. A few months ago, Wren asked an AI coding agent for a quick online order form for the Crumb & Co. website. It was up and running in an afternoon. Customers typed their name, their phone number, and what they wanted, and every morning our kitchen baked from the list it collected. Then the questions started. A regular changed her phone number. The owner raised the price of a croissant. Rosa wanted to know how many croissants we sold last week, and nobody could tell her without reading every single order. In this article, we'll look at how to shape our app's data so questions like Rosa's stay easy to answer as our product grows. Onwards! ## One Wide Row Per Order Our agent saved every order as one row in a big, spreadsheet-like list called orders: ![The orders table from our first order form, with columns id, customer, phone, items, and total. 1041: June Park, 555-0142, 2 croissants, 1 sourdough, $15.00. 1042: Sam Ortiz, 555-0187, croissant + 2 baguettes, $11.50. 1043: June P., 555-0142, Croissant x3, $10.50. 1044: Ava Lee, 555-0113, 1 sourdough, $8.00. 1045: june park, 555-0142, 4 croissants, $14.00.](https://www.kirupa.com/build/images/data_modeling_wide_rows.png) Each row holds the name and phone number exactly as our customer typed them, plus the order written out as a sentence. If we squint, our orders list is the kitchen junk drawer. Everything fits, and it works great until we need to find something: ![A gag: our orders table drawn as a kitchen junk drawer with an orders label on its front. It is stuffed with a croissant, a phone, a receipt, a key, a memo, and a baguette. A handwritten note points at the phone: It's in here somewhere!](https://www.kirupa.com/build/images/data_modeling_junk_drawer.png) We're about to search our drawer twice, and neither search will go well. ## Where the Shape Starts to Hurt June Park is one of our regulars, with 14 orders in our list. When she got a new phone number, our agent updated every row where the customer is exactly June Park: [![June's new number is 555-0199, replacing 555-0142. Below are all 14 of her order rows in two columns, each with id, customer, and phone. The update changed the 12 rows whose customer is exactly June Park to 555-0199. Two rows, 1043 (June P.) and 1045 (june park), still say 555-0142. A handwritten note points at them: Missed these two!](https://www.kirupa.com/build/images/data_modeling_phone_rows.png)](https://www.kirupa.com/build/images/data_modeling_phone_rows.png) Twelve of her rows got the new number, but on the other two, June had typed her name as June P. and june park, so they didn't match, which leaves us with two phone numbers for June and nothing in our list that tells us which one is right. A week later, Rosa asked something that sounds really simple: ![Rosa asks: How many croissants did we sell last week? Below her question are the id and items columns from our orders table, with every mention of a croissant highlighted: 2 croissants, croissant, Croissant x3, nothing in 1044's 1 sourdough, and 4 croissants. A handwritten note points at the items column: Read every row?](https://www.kirupa.com/build/images/data_modeling_croissant_text.png) Our answer is buried in sentences that our customers typed, and order 1042 doesn't even say how many. Both problems have the same cause. We stored June's number in 14 places, and we stored what people ordered as text that only a person can read. ## Labeled Drawers and Cross-Reference Cards Long before computers, offices kept this stuff in filing cabinets, where each drawer held one kind of thing and every card had a number in its corner. When a card needed something from another drawer, it carried a small cross-reference card that said *see Customers #7* instead of copying the details. Here is our bakery's data organized that way: ![A filing cabinet with three labeled drawers: Customers, Orders, and Products. The Customers drawer's front card is #7, June Park, 555-0199. The Products drawer's front card is #1, Croissant, $3.50. The Orders drawer's front card is #1041, placed Nov 24, with a small blue cross-reference card clipped to it that says see Customers #7. An arrow runs from that cross-reference card to June's card.](https://www.kirupa.com/build/images/data_modeling_drawers.png) June's phone number lives on exactly one card, and our order just points at it, so a new number will only mean updating one card. Databases work the same way. Each drawer is a **table**, each card is a **row**, and each blank on a card is a **column**. The number in a card's corner is its **primary key**, a unique id that never changes. The cross-reference card is a **foreign key**, a column holding another table's primary key. Our plan for all of this is our **data model** (aka schema), and designing it is called data modeling. The idea comes from E. F. Codd's 1970 paper, [A Relational Model of Data for Large Shared Data Banks](https://doi.org/10.1145/362384.362685), which is why PostgreSQL, MySQL, and SQLite are called relational databases. Here are two of our drawers as tables: ![Two tables. customers has columns id, name, and phone, with rows 3 Sam Ortiz 555-0187, 7 June Park 555-0199, and 12 Ava Lee 555-0113. orders has columns id, customer_id, and placed_at, with rows 1041 7 Nov 24, 1042 3 Nov 24, and 1043 7 Nov 26. An arrow runs from order 1041's row to June's row in customers. Handwritten notes point at customers' id column: primary key, and at orders' customer_id column: foreign key.](https://www.kirupa.com/build/images/data_modeling_tables.png) Order 1041 has a customer_id of **7**, and 7 is June's primary key. Because our database knows where customer_id points, it will [refuse to save](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-FK) an order for a customer who doesn't exist. ## Keys That Never Change Why do we point at June with a 7 instead of her name? Names change, and two customers can share one. A good primary key is boring on purpose. It is unique, and it never changes, so nothing that points at it ever has to change either. Here are June's 14 orders pointing at her: ![Left: the customers table with rows 3 Sam Ortiz 555-0187 and 7 June Park 555-0199. Right: June's orders, with columns id and customer_id: 0988, 0993, 0999, then 8 more orders, then 1041, 1043, and 1045, every one with customer_id 7. A bracket groups all 14 orders, and one arrow runs from it to June's row. A handwritten note points at June's phone number: Change it once!](https://www.kirupa.com/build/images/data_modeling_one_to_many.png) June's phone number now lives in one cell, and all 14 of her orders see a change right away. One customer has many orders, and each order has exactly one customer, so this is called a **one-to-many** relationship. ## The Table in the Middle Orders and products are trickier, because one order can have many products and one product shows up in many orders, so neither table can hold the other's id in one column. For this **many-to-many** relationship, we will add a table in the middle with one row per line of an order: [![Three tables side by side. orders lists ids 1041 to 1045. order_items has columns order_id, product_id, and quantity, one row per line: 1041 1 2, 1041 2 1, 1042 1 1, 1042 3 2, 1043 1 3, 1044 2 1, and 1045 1 4. products lists 1 Croissant, 2 Sourdough, and 3 Baguette. Order 1041 is highlighted: arrows run from its two order_items rows back to order 1041 and over to Croissant and Sourdough.](https://www.kirupa.com/build/images/data_modeling_join_table.png)](https://www.kirupa.com/build/images/data_modeling_join_table.png) Each row in our order_items table points at one order and one product, and it says how many. Order 1041 gets two rows, one for its croissants and one for its sourdough. Rosa's question finally has a real answer. Croissants are product 1, so we add up the quantity on every row whose product_id is 1: [![The same three tables. Every order_items row with product_id 1 is highlighted, and arrows run from those four rows to Croissant in products. Their quantities are 2, 1, 3, and 4. Below the table: 2 + 1 + 3 + 4 = 10, with a croissant beside it.](https://www.kirupa.com/build/images/data_modeling_croissant_answer.png)](https://www.kirupa.com/build/images/data_modeling_croissant_answer.png) That's **10** croissants for these five orders, and we didn't have to guess once. For Rosa's whole week, we will run the very same lookup. ## A Copy We Make on Purpose Our wide row did get one thing right by accident. It recorded what June actually paid. Let's see what happens when the owner raises the croissant from **350** cents to **400** cents: ![The products table: the croissant's price_cents goes from 350 to 400; Sourdough is 800 and Baguette is 400. Below it, order 1041's two order_items rows: product 1, quantity 2, and product 2, quantity 1. A receipt for order 1041 works the total out from today's prices: 2 Croissant $8.00, 1 Sourdough $8.00, total $16.00. A sticky note says June paid $15.00, and a handwritten note points at the total: History changed!](https://www.kirupa.com/build/images/data_modeling_price_change.png) Our order lines only say which product and how many, so our receipt uses today's prices, and order 1041 now adds up to $16.00 even though June paid $15.00. Our fix is to copy the price onto each line when the order is placed: ![The same products table, with the croissant now at 400. order 1041's order_items rows have a new unit_price_cents column holding 350 for the croissants and 800 for the sourdough. The receipt now reads 2 Croissant $7.00, 1 Sourdough $8.00, total $15.00, which matches what June paid. A handwritten note points at the unit_price_cents column: What she paid!](https://www.kirupa.com/build/images/data_modeling_price_copy.png) Isn't this the copying we just got rid of? Not quite. June's phone number is one fact that should match everywhere. The price on a line is what we charged on November 24, and that should never change, so this copy is our record of history. > **Note: Store Money in Whole Cents** > > We store prices as whole cents (350) instead of dollars (3.50). Computers store decimals as floating point numbers, which can't represent most fractions exactly. In JavaScript, `0.1 + 0.2` gives you 0.30000000000000004, and there's even a [whole website](https://0.30000000000000004.com/) named after that number. Whole cents always add up exactly. ## Writing It Down Now that we've seen how our pieces fit with pictures, here is the same design in SQL (the language relational databases speak) for PostgreSQL: ```sql CREATE TABLE customers ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, phone text ); CREATE TABLE products ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, price_cents integer NOT NULL ); CREATE TABLE orders ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id integer NOT NULL REFERENCES customers (id), placed_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE order_items ( order_id integer NOT NULL REFERENCES orders (id), product_id integer NOT NULL REFERENCES products (id), quantity integer NOT NULL CHECK (quantity > 0), unit_price_cents integer NOT NULL, PRIMARY KEY (order_id, product_id) ); ``` Each PRIMARY KEY is the number in a card's corner (no two rows can share one), each REFERENCES is a cross-reference card, and unit_price_cents is our copy on purpose. Here is Rosa's question for last week: ```sql SELECT sum(order_items.quantity) AS croissants FROM order_items JOIN orders ON orders.id = order_items.order_id JOIN products ON products.id = order_items.product_id WHERE products.name = 'Croissant' AND orders.placed_at >= '2026-11-23' AND orders.placed_at < '2026-11-30'; ``` The JOIN lines follow our cross-reference cards, the WHERE lines keep only last week's croissants, and sum adds up their quantities. ## Tables or Documents? Not every database uses tables. A **document database** like MongoDB stores each record as one nested document, usually written as JSON (a text format built from curly braces). Here is order 1041 stored the everything-in-one-folder way: ![Order 1041 stored as one document. On the left, it's drawn as a folder labeled order 1041 holding June's details (June Park, 555-0199), her two lines (2 Croissant at 350 and 1 Sourdough at 800), and a total of 1500. On the right is the same order written out as nested JSON, with a customer object and an items list inside it.](https://www.kirupa.com/build/images/data_modeling_document.png) To show a receipt, our app grabs one document and is done. [MongoDB's own guidance](https://www.mongodb.com/docs/manual/data-modeling/best-practices/#link-related-data) says this works best when we read the pieces together. It hurts with our shared data, because June's details get copied into every order: ![Three of June's order documents side by side, 1041, 1043, and 1045, each drawn as a folder. Every folder carries its own copy of June's name and phone number, 555-0199, plus its own items. A handwritten note points at the middle folder: A copy in every order!](https://www.kirupa.com/build/images/data_modeling_document_pain.png) That's 14 copies of June's phone number...all over again. My honest take is that for most new products, a relational database like PostgreSQL or SQLite is the boring, safe default, because our apps are full of shared things and questions that span many records. Both can still store JSON in a column (PostgreSQL has [jsonb](https://www.postgresql.org/docs/current/datatype-json.html), and SQLite has [JSON functions](https://sqlite.org/json1.html)) for our one-folder odds and ends. ## Finding Things Fast With Indexes What if we want all of June's orders? Without help, our database has to check every row's customer_id, like finding a topic by reading a whole book, which is a [linear search](https://www.kirupa.com/data_structures_algorithms/linear_search.htm). A book's index fixes this by listing topics in sorted order with their pages. A database **index** does the same for one of our columns, and the [PostgreSQL docs](https://www.postgresql.org/docs/current/indexes-intro.html) use this exact comparison: [![Two ways to find June's orders, the ones with customer_id 7. Left, check every row: all 10 rows of orders 1036 to 1045 get a check mark, and the three with customer_id 7 (1041, 1043, 1045) are highlighted, with a turtle and 10 of 10 rows checked. Right, look it up in the customer_id index, which lists each customer_id in order with its rows: 3 is 1038, 1042; 5 is 1036; 7 is 1041, 1043, 1045; 9 is 1037, 1040; and 12 is 1039, 1044. The 7 entry is highlighted, with a rabbit and straight to 3 rows.](https://www.kirupa.com/build/images/data_modeling_index.png)](https://www.kirupa.com/build/images/data_modeling_index.png) On the left, our database checks all 10 rows to find June's 3, while on the right, it finds 7 in the sorted index and jumps straight to her orders. With 10 rows, we'd never notice. With a few million, we really, REALLY would. PostgreSQL's default index is a B-tree, a sorted tree that works a lot like [binary search](https://www.kirupa.com/data_structures_algorithms/binary_search.htm). Indexes aren't free, though. Each one takes up space, and every new or changed row has to update it too, so our writes get slower. Our rule of thumb is to index the columns we look things up by, and while PostgreSQL indexes our primary keys for us, foreign keys like orders.customer_id are up to us. ## Changing the Shape Without Breaking Things All of this is great for a new app, but ours is live. It's tempting to say we'll fix the schema later, except later gets more expensive every week as more orders and code depend on the old shape. The most famous later in computing is Y2K: ![A gag about the Y2K bug: an old beige computer celebrating at midnight on January 1, 2000. Its screen reads 01/01/00 and HAPPY NEW YEAR 1900!, with a party popper beside it. A handwritten note points at the computer: Wrong century!](https://www.kirupa.com/build/images/data_modeling_y2k.png) For decades, programs saved memory by storing years as two digits, so 2000 would show up as 00...which a computer could read as 1900. [Britannica](https://www.britannica.com/technology/Y2K-bug) puts the cost of fixing it at an estimated $300 billion. The safe way to change a live database is with **migrations**, which are small scripts that each change the shape a little and live in [version control](https://www.kirupa.com/build/git_and_version_control.htm) next to our code. For big changes, we will use what Danilo Sato's write-up on Martin Fowler's site calls [parallel change](https://martinfowler.com/bliki/ParallelChange.html) (aka expand and contract): [![Four steps down a numbered line, each with the same two orders rows. Step 1, add the new column: orders has id, customer, phone, and a new, empty customer_id. Step 2, fill it in: customer_id is 7 for 1041 (June Park, 555-0142) and 3 for 1042 (Sam Ortiz, 555-0187). Step 3, switch the code: the app reads and writes customer_id, and the customer and phone columns are grayed out. Step 4, remove the old columns: orders has just id and customer_id.](https://www.kirupa.com/build/images/data_modeling_parallel_change.png)](https://www.kirupa.com/build/images/data_modeling_parallel_change.png) Every step leaves our running code working, so a mistake only sets us back one small step. Filling in the new column is called a backfill, and it's where our messy data bites one last time, since a person has to match June P. and june park to customer 7. ## When an AI Agent Designs the Tables Agents will happily invent a schema on the spot, and they tend to pick whatever gets today's feature working fastest, which is how we got one wide row with a sentence for the items. Before an agent writes any code for us, we now ask it to do this: - Show us the tables, with their columns and keys. - Answer our five real questions using only those tables. - Write every change as a migration we can review. Here is the check we'll run on its answers: ![A checklist of five questions, each with a check mark and the tables that answer it. Croissants sold last week? order_items, orders, products. June's phone number? customers. What June paid for 1041? order_items. Who hasn't ordered in a month? customers, orders. Best seller on Saturdays? order_items, orders, products.](https://www.kirupa.com/build/images/data_modeling_five_questions.png) If a question can only be answered by reading text or guessing, our schema isn't done yet. We are also extra careful with any migration that removes a column or a table, since that's the one step we can't easily undo. ## Try It This Week Grab some paper, and let's model the main thing your own product keeps track of: 1. List your product's nouns, like customers, orders, and products. 2. Draw one box per noun with the columns it needs and an id. 3. Draw an arrow wherever one box points at another, and give every many-to-many its own box in the middle. 4. Write down the five questions you'll need to answer most often. 5. Trace which boxes answer each question, and change your boxes if an answer means reading a sentence or guessing. ## Frequently Asked Questions **What Is Data Modeling?** Data modeling is deciding what kinds of things an app keeps track of, what it records about each one, and how those things connect. The result is a data model, also called a schema: a set of tables, their columns, and the keys that link them. A good data model stores each fact in one place and makes the questions you ask most often easy to answer. **What Is the Difference Between a Primary Key and a Foreign Key?** A primary key is a unique id for each row in a table, like customer 7, and it should never change. A foreign key is a column in another table that holds that id, like an order’s customer_id, so the order points at the customer instead of copying their details. The database can then check that every foreign key points at a row that really exists. **Should I Use a SQL or NoSQL Database for My App?** For most new products, a relational (SQL) database like PostgreSQL or SQLite is the safe default, because most apps have shared data and questions that span many records. Document databases like MongoDB work best when you almost always read one record and everything inside it together. Relational databases can also store JSON documents in a column, so you can mix the two when it helps. **What Is a Database Migration?** A migration is a small, versioned script that changes a database’s shape, like adding a column or creating a table. Migrations live in version control next to your code, so every copy of the database gets the same changes in the same order. For big changes, add the new shape first, fill it in, switch your code, and only then remove the old shape. ## Conclusion Ok! It's time to wrap things up. Our order form started as one wide row per order, which was fine until June changed her number and Rosa asked about croissants. Data modeling got us out of that mess with one table per kind of thing, primary keys that never change, and foreign keys that point at things instead of copying them (except for prices, which we copy on purpose). Indexes keep our lookups fast, and migrations let us change the shape safely. We will still get parts of our schema wrong, and that is what migrations are for. What we can do is get the nouns and keys roughly right on day one, while changing them is cheap. Crumb & Co.'s actual kitchen junk drawer, by the way, is still a mess. Nobody has written a migration for it yet. Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Read the next article in the series, [APIs and Webhooks](https://www.kirupa.com/build/apis_and_webhooks.htm), or check out some related content: - [Faster Searching with Binary Search](https://www.kirupa.com/data_structures_algorithms/binary_search.htm). The halve-it-every-time search that makes sorted lookups, like a database index, so fast. - [Hashtable (aka Hashmap or Dictionary)](https://www.kirupa.com/data_structures_algorithms/hashtable_hashmap_dictionary.htm). How looking something up by its key can be nearly instant. - [Vector Databases](https://www.kirupa.com/ai_fundamentals/vector_databases.htm). The kind of database that finds things by meaning for our AI features. 3. Stuck on something, or curious about a detail we skipped? [Ask on the forums](https://forum.kirupa.com/), and we’ll help you out. ## Test your knowledge! [Take the Data Modeling and Databases Quiz](https://www.kirupa.com/quizzes/data_modeling.htm). Practice with 6 multiple-choice questions and an explanation after every answer.