SQL Lesson 1: Every App You Use Is Just Boxes in a Cabinet
๐ Full written solution: https://interview-kit-fe.vercel.app/sql-lesson-01-sql-overview-databases-and-tables ๐ป Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/sql-lesson-01-sql-overview-databases-and-tables Chapters: 0:00 Every App You Use Is Just Boxes in a Cabinet 0:17 What Is a Database? 0:34 What Is a Table? 0:51 Rows and Columns 1:09 The Schema: Your Blueprint 1:31 Data Types Keep Data Honest 1:49 The Primary Key 2:10 Change One Person, Nobody Else Moves 2:28 Why Relational? The 'Related' Part 2:45 Common Mistake #1: No Unique Key 3:05 Common Mistake #2: Wrong Type 3:22 Alternative: Spreadsheets 3:47 Database vs Spreadsheet 4:02 Recap & What's Next Your first step into SQL and relational databases โ no experience needed. We break down what a database really is, how tables store rows and columns, and why the schema is your data blueprint. You'll learn how data types and primary keys keep your data honest, why 'relational' means change one record and nothing else breaks, and the two beginner mistakes that wreck tables. Plus: database vs spreadsheet, and when each one wins. #SQL #Databases #LearnToCode #DataEngineering #SQLTutorial Watch next: - 74% of Women Lived. 19% of Men Didn't. The Data Explains Why: https://youtu.be/xg_LtvWLmBw - You've Used These 10 Functions Thousands of Times #shorts: https://youtu.be/oZu7t8eNNpM - Lesson: How Do Apps Survive a Million Users Without Crashing?: https://youtu.be/wHWdfeklLG4
SEO PACKAGE
1. SEO Title
SQL for Beginners: What a Relational Database Really Is (Tables, Schema, Keys Explained)
2. SEO Subtitle
Learn how every app stores its data using tables, schemas, data types, and primary keys โ the four ideas that make everything else in SQL make sense.
3. Featured Quote
"You store each fact once and link to it, instead of copying it everywhere โ that single habit is what 'relational' really means."
4. Meta Description
Learn SQL from zero: understand databases, tables, schema, data types, and primary keys with plain-English analogies and clear examples. Start here. (154 characters)
5. URL Slug
sql-basics-relational-databases-tables-schema-primary-keys
6. Keywords
- SQL for beginners
- relational database
- what is a database
- database tables explained
- database schema
- primary key
- SQL data types
- database vs spreadsheet
- learn SQL
- SQL tutorial
- rows and columns database
- data modeling basics
- coding interview databases
- database normalization intro
- foreign key relationship
- SQL fundamentals
- backend development basics
- data engineering for beginners
- database design
- structured data storage
7. Tags
SQL, Databases, Relational Database, Learn to Code, SQL Tutorial, Data Engineering, Backend Development, Coding Interview, Database Design, Primary Key, Schema, Beginner Programming, Software Engineering, Data Structures
SQL Fundamentals: What a Relational Database Really Is
8. Introduction
Open almost any app on your phone โ Instagram, your banking app, a mobile game โ and behind the pretty screens they all share one quiet secret: they keep their information in labeled boxes inside an organized container. That container is a database, and the language most of them speak is SQL.
If you want to work in backend development, data engineering, or full-stack software engineering, this is the foundation you build everything else on. It is also one of the most common areas interviewers probe, because it reveals whether you actually understand how data lives, not just how to write a SELECT. A candidate who can explain why a primary key matters, or when a database beats a spreadsheet, signals real engineering maturity.
The good news: the core of relational databases rests on just four ideas โ databases, tables, schema, and primary keys. Master these and the rest of SQL is just building on top. This lesson walks you through each one with everyday analogies, small examples, and the mistakes that trip up nearly every beginner. No prior experience required.
9. Problem Overview
Here is the real problem we are solving: How do you store information so a computer can hand it back quickly, keep it accurate, and let many people use it at once โ without everything falling apart?
Imagine you are building an app with users, orders, and products. You need to:
- Store many records of the same kind (all your users, all your orders).
- Guarantee that each record is clean and correctly typed (an age is a number, a name is text).
- Find or update one specific record instantly, even among millions.
- Avoid copying the same fact into a dozen places where it can drift out of sync.
A relational database is the tool designed exactly for this. Picture a giant filing cabinet full of labeled drawers. The whole cabinet is the database. Each drawer holds one kind of thing and is called a table. Inside a drawer, the information is laid out like a spreadsheet โ columns describe the fields, rows are the individual records, and each cell holds a single value.
Before you store anything, you tell the database the shape of each table. That shape is the schema โ a blueprint declaring "this table has an id that is a number, a name that is text, an age that is a number." Once set, the database enforces the schema for you. Nobody can slip the word banana into an age column.
That is the problem, and that is the map of the solution.
10. Example
Let's make it concrete with a small users table.
| id (number) | name (text) | age (number) | city (text) |
|---|---|---|---|
| 1 | Ada | 36 | London |
| 2 | Grace | 41 | New York |
| 3 | Alan | 29 | Manchester |
Reading this table:
- The columns are
id,name,age, andcity. They describe what each piece of data means. - Each row is one real person โ one complete record.
- The box where row
2meets theagecolumn holds the single value41. That box is a cell. - The
idcolumn is our primary key: every value in it is unique, so we can always point to exactly one row.
Now say it's Grace's birthday and she turns 42. We want to change only her age:
| id | name | age | city |
|---|---|---|---|
| 1 | Ada | 36 | London |
| 2 | Grace | 42 | New York |
| 3 | Alan | 29 | Manchester |
Notice what happened to Ada and Alan: nothing. The primary key let the database walk straight to the row where id = 2 and update that row alone. Whether the table has 3 people or 3 million, the change is surgical. That precision is the whole reason primary keys exist.
11. Intuition
How does an experienced engineer arrive at this design, rather than memorize it?
Start from a pain point. Suppose you keep customers in a plain list and two of them are named "Alex Smith." One moves to a new city and you need to update just that one. With only names to go on, you are stuck โ you cannot tell the two Alexes apart. The instinct that follows is: give every record a guaranteed-unique handle. That handle is the primary key, and it is what makes precise, safe updates possible.
Next, think about repetition. If every order row copied the customer's full name, email, and address, then a single email change would force you to hunt down and edit dozens of rows. Miss one, and your data now contradicts itself. The lazy โ and correct โ instinct is: write each fact once, in one place, and everywhere else just point to it by its key. An orders table stores a customer_id, and that id points back to the full record in the users table. That is literally why we call it relational: tables relate to each other through keys.
Finally, think about trust. You do not want to re-check every value your app reads. So you push the rules down into the database itself through the schema and data types. The database becomes the guard that never sleeps.
Those three instincts โ unique handles, store-once-and-link, and enforced rules โ are the intuition. The mechanics of SQL are just how we express them.
12. Brute Force Approach: The Spreadsheet
Idea: Just use a spreadsheet. Put everything โ users, their orders, their addresses โ into one big sheet and edit by hand.
Algorithm:
- Open a spreadsheet.
- Add a column for every field you can think of.
- Type rows in as data arrives.
- Scroll, sort, and edit manually.
Advantages:
- Zero setup. You start in seconds.
- Visual and familiar โ great for a quick personal list or a one-off calculation.
- No schema to design, no rules to declare.
Disadvantages:
- Nothing enforces correctness. You can type
maybeinto an age column and the sheet happily accepts it. - No reliable way to tell duplicate rows apart.
- Numbers stored as text sort wrong (
10lands before2). - It buckles when several people edit at once, or when you cross ~100,000 rows.
Complexity (informal):
- Setup effort: very low.
- Cost as the system grows: very high โ correctness and speed both degrade sharply.
The spreadsheet is the friendly notebook you grab for a quick note. It is the right tool for small, informal, single-user jobs โ and the wrong tool the moment the job gets big or serious.
13. Optimal Approach: The Relational Database
The relational database keeps the "table of rows and columns" feel of a spreadsheet but adds three enforced guarantees. Let's walk through each.
Step 1 โ Define a schema before storing data. You declare the table's shape up front. The database then treats that shape as a contract it will never break.
Step 2 โ Give every column a data type.
Each column may only hold one kind of value โ a number, text, a date. This is the guardrail that stops your birthday field from holding the word maybe, and stops numbers from being stored as text.
| Column | Data Type | Allowed | Rejected |
|---|---|---|---|
id |
INTEGER | 42 |
"forty-two" |
name |
TEXT | "Ada" |
(anything is text) |
age |
INTEGER | 36 |
"maybe" |
joined |
DATE | 2024-05-01 |
"soon" |
Step 3 โ Give every table a primary key.
One column (often id) whose value is unique for every row. It is the passport number of the row โ no two are ever the same โ and it is what makes single-row updates instant and unambiguous.
Step 4 โ Relate tables instead of copying data. Store each fact once. Link to it by key.
users orders
+----+-------+-------+ +----------+-------------+--------+
| id | name | city | | order_id | customer_id | total |
+----+-------+-------+ +----------+-------------+--------+
| 1 | Ada | London| <-----+ | 5001 | 1 | 29.99 |
| 2 | Grace | NY | +-| 5002 | 1 | 12.50 |
+----+-------+-------+ +----------+-------------+--------+
^
customer_id points back to users.id
Ada's name lives in exactly one place. Both of her orders simply reference customer_id = 1. Change her name once, and every order automatically reflects the truth โ because they never stored a copy in the first place.
14. Python Code
Here is a complete, runnable example using Python's built-in sqlite3 module โ no installation required. It creates the schema, enforces a primary key, links two tables, and performs the surgical update from our example.
import sqlite3
# An in-memory database: perfect for learning and experiments.
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
# Step 1 & 2: Define the schema with typed columns.
# Step 3: 'id' is the PRIMARY KEY โ unique for every row.
cursor.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
city TEXT
)
""")
# Step 4: A second table that LINKS back to users by key.
cursor.execute("""
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total REAL NOT NULL,
FOREIGN KEY (customer_id) REFERENCES users(id)
)
""")
# Insert some people.
users = [
(1, "Ada", 36, "London"),
(2, "Grace", 41, "New York"),
(3, "Alan", 29, "Manchester"),
]
cursor.executemany("INSERT INTO users VALUES (?, ?, ?, ?)", users)
# Ada places two orders โ we store only her id, never her name.
orders = [
(5001, 1, 29.99),
(5002, 1, 12.50),
]
cursor.executemany("INSERT INTO orders VALUES (?, ?, ?)", orders)
# The surgical update: change ONLY Grace's row, found by primary key.
cursor.execute("UPDATE users SET age = ? WHERE id = ?", (42, 2))
# Ask the table a question: who is Grace now, and what did Ada order?
cursor.execute("SELECT name, age FROM users WHERE id = 2")
print(cursor.fetchone()) # ('Grace', 42)
cursor.execute("""
SELECT users.name, orders.total
FROM orders
JOIN users ON users.id = orders.customer_id
""")
print(cursor.fetchall()) # [('Ada', 29.99), ('Ada', 12.5)]
connection.close()
15. Code Walkthrough
sqlite3.connect(":memory:")โ spins up a throwaway database that lives in RAM. Nothing to install, nothing left on disk. Ideal for practice.CREATE TABLE users (...)โ this is the schema in action. Each column names its data type (INTEGER,TEXT,REAL).PRIMARY KEYonidpromises the database will keep it unique.NOT NULLsays the value may not be missing.- The
orderstable โFOREIGN KEY (customer_id) REFERENCES users(id)is the relational link. It tells the database thatcustomer_idmust correspond to a realidinusers. This is store-once-and-link, enforced. executemany(..., users)โ inserts many rows in one call. The?placeholders safely bind values (and, as a bonus, prevent SQL injection).UPDATE users SET age = ? WHERE id = ?โ the heart of the lesson.WHERE id = 2uses the primary key to target exactly one row. Change 2 to any id and only that row moves.- The
JOINโ this is the payoff of linking. We fetch each order's total and the customer's name by matchingusers.id = orders.customer_id, even though the name was never copied intoorders.
16. Dry Run
Let's trace the update line by line for the users table.
Starting state:
| id | name | age |
|---|---|---|
| 1 | Ada | 36 |
| 2 | Grace | 41 |
| 3 | Alan | 29 |
Execute: UPDATE users SET age = 42 WHERE id = 2
- The database scans for rows where
id = 2. Becauseidis the primary key, it can go straight there โ at most one row can match. - It finds row 2 (Grace).
- It sets that row's
ageto42. - It checks the schema: is
42a validINTEGER? Yes. The write is accepted. - Rows 1 and 3 are never touched.
Ending state:
| id | name | age |
|---|---|---|
| 1 | Ada | 36 |
| 2 | Grace | 42 |
| 3 | Alan | 29 |
One row changed. Two rows untouched. That is the guarantee the primary key buys you.
17. Complexity Analysis
Databases are about access cost, so let's reason about it.
- Looking up a row by primary key: roughly O(log n) time. The database keeps an index on the primary key (typically a B-tree), so it does not scan every row โ it navigates the index. Even with millions of rows, the update in our dry run stays fast. That is why keys exist.
- Looking up by a non-indexed column (say, searching by
name): O(n) โ a full table scan, because there is no shortcut. This is why frequently-searched columns get indexes. - Space: O(n) for the rows themselves, plus extra space for each index you create. An index trades a little storage for a lot of speed.
The takeaway: the schema and keys are not bureaucracy โ they are what turn a linear scan into a logarithmic jump.
18. Alternative Solutions
Spreadsheets (revisited): Great for small, informal, single-user data. No schema, instant start โ but no enforced rules, poor concurrency, and slow past ~100k rows.
NoSQL / document databases (e.g. MongoDB): Store flexible, schema-light documents. Excellent when your data shape changes often or is deeply nested, and when you need to scale horizontally. The trade-off: you often give up strict enforced relationships and, historically, some multi-record transaction guarantees.
| Option | Enforced rules | Relationships | Best for |
|---|---|---|---|
| Spreadsheet | None | Manual | Quick personal lists |
| Relational DB (SQL) | Strong | First-class (keys) | Structured, multi-user systems |
| Document DB (NoSQL) | Flexible | App-managed | Fast-changing, nested data |
For most apps with users, orders, and clear relationships, the relational database is the default choice โ and the reason SQL is worth learning first.
19. Edge Cases
- Empty table: A table with a valid schema but zero rows is perfectly legal. Queries simply return nothing.
- Duplicate primary key: Attempting to insert a second row with an existing
idis rejected โ that is the primary key doing its job. - Missing required value: Inserting a row without a
NOT NULLfield fails. Decide up front which columns are optional. - Minimum / boundary values: A
0or negative age is type-valid (it's an integer) even if it's logically wrong โ types don't know your business rules. Add aCHECK (age >= 0)constraint when the meaning matters. - Very large tables: Millions of rows are routine โ as long as you index the columns you search and update by.
20. Common Mistakes
- Skipping a unique key. Two rows both saying
Alex, 30and now you cannot update just one. Always give rows a way to be told apart. - Storing numbers as text. Text sorts character-by-character, so
"10"comes before"2", and math breaks. Store numbers as numbers. - Copying the same fact everywhere. Duplicating a customer's name into every order means one change requires many edits โ and guarantees eventual contradictions. Store once, link by key.
- Treating types as optional. Letting a column accept anything defeats the schema's whole purpose. The guardrails only work if you set them.
- Ignoring indexes on searched columns. Searching a huge table by an unindexed column forces a full scan. If you query by it often, index it.
- Assuming "it's a small table, it won't matter." It always grows. The habits you skip at 10 rows become disasters at a million.
21. Interview Questions
- What is the difference between a primary key and a foreign key?
- Why is a relational database usually better than a spreadsheet for a multi-user application?
- What does the schema enforce, and what does it not enforce (e.g. business rules)?
- Why might sorting a column of "numbers" produce wrong results, and how do you fix it?
- What is normalization, and why do we avoid copying the same data into many rows?
- When would you reach for a NoSQL database instead of SQL?
- How does an index change the time complexity of a lookup?
22. Similar Problems
- Database schema design questions โ testing whether you can model users, orders, and products into clean, related tables.
- "Design a system" interview rounds (URL shortener, e-commerce cart) โ nearly all start with "what tables do you need, and what are their keys?"
- LeetCode SQL problems such as Combine Two Tables (#175), Duplicate Emails (#182), and Employees Earning More Than Their Managers (#181) โ each one exercises joins, keys, and relationships, the exact concepts in this lesson.
They're related because every one of them rewards the same four fundamentals: tables, schema, types, and keys.
23. Key Takeaways
- A database is your labeled filing cabinet; a table is one drawer laid out like a spreadsheet.
- Columns describe, rows are the entries, and each cell holds one value.
- The schema is the enforced rulebook; data types are the guardrails that keep each column clean.
- The primary key guarantees every row is unique and enables surgical, single-row updates.
- Relational means: store each fact once and link to it by key, instead of copying it everywhere.
Get these four ideas and everything else in SQL is just building on this foundation. In the next lesson, we'll actually start asking the tables questions with real queries.
24. Watch the Video
Reading builds understanding, but seeing it click is faster. Watch the full walkthrough โ with the cabinet-and-drawers analogy animated end to end โ right here: {LINK}. It's the gentlest possible on-ramp to SQL, and it sets up every lesson that follows.
25. About the Series
This is part of Fun with Learning Technology โ a series that turns intimidating software engineering topics into short, friendly lessons anyone can follow. We start from real intuition, use everyday analogies, and never assume prior experience. Whether you're breaking into backend development, data engineering, or just curious how the apps you use actually work, the series meets you where you are and builds you up one clear idea at a time.
26. Call To Action
If this made SQL click for you:
- ๐ Like the video on YouTube โ it genuinely helps the series reach more beginners.
- ๐ Subscribe so you don't miss Lesson 2, where we write our first real queries.
- ๐ฉ Subscribe on Substack for the written deep-dives like this one.
- ๐ฌ Comment with the analogy that helped most โ or the one thing still confusing you.
- ๐ Share it with someone who's just starting their coding journey.
SOCIAL MEDIA
LinkedIn Post
Every app you use โ your bank, your favorite social feed, the game you played this morning โ stores its data the same way: in labeled boxes inside an organized container. That container is a database, and understanding it is one of the highest-leverage things a new developer can learn.
I put together a beginner-friendly breakdown of the four ideas that make all of SQL make sense:
๐๏ธ Database โ the whole filing cabinet. ๐ Table โ one drawer, laid out like a spreadsheet, holding one kind of thing. ๐ Schema โ the blueprint the table always obeys. It's why nobody can type "banana" into an age column. ๐ Primary key โ a unique handle for every row, so you can update exactly one record among millions without touching the rest.
The idea that clicks hardest for most people is what "relational" actually means: you store each fact once and link to it by key, instead of copying it everywhere. Change a customer's name in one place, and every order they ever made reflects it automatically โ because you never duplicated it to begin with.
Two mistakes wreck more beginner tables than anything else:
- Skipping a unique key, so you can't tell duplicate rows apart.
- Storing numbers as text, so "10" sorts before "2" and your math quietly breaks.
If you're moving into backend development, data engineering, or full-stack work, this is the foundation everything else stands on. Get these four ideas and the rest of SQL is just building on top.
Full lesson and runnable Python examples in the comments. What analogy finally made databases click for you?
#SQL #Databases #SoftwareEngineering #LearnToCode #DataEngineering
Twitter/X Thread
1/ Every app on your phone hides the same secret structure. Instagram, your bank, your games โ all store data in labeled boxes inside a giant cabinet. Here's how it actually works, in plain English. ๐งต
2/ Picture a filing cabinet full of labeled drawers. That whole cabinet is a database โ software whose only job is to store information neatly and hand it back fast. That's the entire idea.
3/ Open one drawer and you find a spreadsheet. That single spreadsheet is a table. A table holds one kind of thing โ all your users, or all your orders โ in neat rows and columns.
4/ Columns are the headers across the top (name, age, city). Each row is one record โ one real person. Where a row meets a column, that box is a cell, holding a single value. Columns describe; rows are the entries.
5/ Before you add data, you declare the table's shape. That's the schema โ a blueprint: id is a number, name is text. Once set, the database enforces it. Nobody can sneak "banana" into the age column.
6/ Every column has a data type โ the kind of value it allows. This sounds boring, but it's what stops your birthday field from holding the word "maybe." Types are the guardrails.
7/ Two people named Alex Smith. How do you tell them apart? Give every row a unique number: the primary key. Like a passport number โ no two are ever the same.
8/ The superpower: it's Grace's birthday, bump her age to 42. What happens to everyone else? Nothing. The key lets the database walk straight to Grace's row and change only her โ whether the table has 3 rows or 3 million.
9/ Why "relational"? Instead of one giant messy table, you make small focused tables and connect them. Your orders table stores a customer_id that points back to the users table. Store each fact once, link to it โ never copy it everywhere.
10/ Master four ideas โ database, table, schema, primary key โ and the rest of SQL is just building on top. Full lesson + runnable Python here ๐ {LINK} Follow for Lesson 2, where we start asking the tables real questions.
Facebook Post
Ever wondered how your bank app, Instagram, or your favorite game actually remembers all your stuff? ๐ค
They all use the same trick: a database โ basically a giant filing cabinet for a computer. Each drawer is a table (one for users, one for orders), laid out like a spreadsheet with rows and columns.
The magic ingredient is the primary key โ a unique number for every row, like a passport. It's what lets an app update just your record without touching anyone else's, even among millions of people.
I made a beginner-friendly lesson that explains it all with simple analogies โ no experience needed. If you've ever been curious how software really works under the hood, this is a fun place to start. ๐ {LINK}
Reddit Summary
A beginner-friendly mental model for relational databases (tables, schema, keys)
Sharing a breakdown I found useful for absolute beginners. The core framing:
- Database = a filing cabinet. Software whose job is to store data and return it fast.
- Table = one drawer, shaped like a spreadsheet. Holds one kind of thing (users, orders).
- Columns describe fields; rows are records; a cell is one value.
- Schema = the blueprint you declare up front. The database then enforces it โ you can't put text in a number column.
- Data types = per-column guardrails. Storing numbers as text is a classic bug (text sorts "10" before "2").
- Primary key = a unique handle per row. It's what makes updating exactly one row (out of millions) fast and unambiguous.
- Relational = store each fact once, link to it by key, instead of copying it everywhere. An
orderstable holds acustomer_idthat points back tousers.
Two beginner traps worth internalizing: skipping a unique key (can't tell duplicate rows apart) and storing numbers as text (sorting/math break).
There's a runnable Python sqlite3 example that builds the schema, links two tables, and does a single-row update by key if anyone wants to poke at it hands-on. Happy to answer questions on any of the concepts.
GITHUB README
# SQL Fundamentals โ Databases, Tables, Schema & Primary Keys
Your first step into SQL and relational databases, with runnable Python examples.
No prior experience required.
## ๐ Problem
How do you store information so a computer can return it quickly, keep it accurate,
and let many people use it at once โ without everything falling apart?
A plain spreadsheet works for a quick personal list, but it breaks down the moment
you need enforced rules, precise updates, or many users at once. Relational
databases solve exactly this.
## ๐ก Intuition
Three instincts lead an engineer to the relational design:
1. **Unique handles** โ give every record a guaranteed-unique id so you can point
to exactly one row (the primary key).
2. **Store once, link** โ write each fact in one place and reference it by key
instead of copying it everywhere (this is what "relational" means).
3. **Enforced rules** โ push correctness into the database itself via a schema and
data types, so you never have to re-check every value.
## ๐งญ Approach
- **Database** โ the whole container (the filing cabinet).
- **Table** โ one drawer, laid out in rows and columns; holds one kind of thing.
- **Schema** โ the blueprint declaring each column's name and type; enforced by the DB.
- **Data types** โ guardrails so a number column can't hold the word "maybe".
- **Primary key** โ a unique column (usually `id`) enabling instant single-row updates.
- **Foreign key** โ a link from one table to another (e.g. `orders.customer_id โ users.id`).
## ๐ Python Solution
```python
import sqlite3
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL,
city TEXT
)
""")
cursor.execute("""
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total REAL NOT NULL,
FOREIGN KEY (customer_id) REFERENCES users(id)
)
""")
cursor.executemany("INSERT INTO users VALUES (?, ?, ?, ?)", [
(1, "Ada", 36, "London"),
(2, "Grace", 41, "New York"),
(3, "Alan", 29, "Manchester"),
])
cursor.executemany("INSERT INTO orders VALUES (?, ?, ?)", [
(5001, 1, 29.99),
(5002, 1, 12.50),
])
# Surgical update: change ONLY Grace's row, found by primary key.
cursor.execute("UPDATE users SET age = ? WHERE id = ?", (42, 2))
cursor.execute("""
SELECT users.name, orders.total
FROM orders
JOIN users ON users.id = orders.customer_id
""")
print(cursor.fetchall()) # [('Ada', 29.99), ('Ada', 12.5)]
connection.close()
โฑ๏ธ Complexity
| Operation | Time | Notes |
|---|---|---|
| Lookup / update by primary key | O(log n) | Uses the primary-key index (B-tree) |
| Lookup by non-indexed column | O(n) | Full table scan |
| Storage | O(n) | Plus extra space per index |
๐ฅ Video
Watch the full walkthrough: {LINK}
๐ Article
Full written deep-dive (SEO article + examples + common mistakes): {LINK}
Part of the Fun with Learning Technology series โ intimidating engineering topics made friendly, one clear idea at a time. ```
The solution
age TEXT: "9", "10", "2"
sorted -> "10", "2", "9" -- wrong!
age INTEGER: 9, 10, 2
sorted -> 2, 9, 10 -- rightReady to try it yourself? Solve Sql problems with instant feedback in the practice sandbox.
Practice now โ


