Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing

SQL & Analytical Warehousing

Progress0/29
x

Understanding Data

  • What is data?8m
  • What is a database?8m
  • Tables, rows, and columns10m
  • Primary keys and foreign keys10m

Relational core

  • Relational basics8m
  • NULL handling10m
  • Aggregations & grouping10m
  • Multi-table joins12m
  • Subqueries & CTEs10m

Windows, cleaning & opsPreview

  • Window functions (the DE benchmark)Free14m
  • Data cleaning & string/date manipulation10m
  • CASE expressions10m
  • Deduplication & incremental upserts12m
  • Indexing, partitioning & optimization12m

Advanced Querying

  • Set operations: UNION, INTERSECT, EXCEPT10m
  • Recursive CTEs for hierarchical data12m
  • Querying semi-structured JSON12m
  • Pivoting and unpivoting12m

Warehouse & Dimensional Modeling

  • OLTP vs OLAP mental model10m
  • Star schema: facts, dimensions, grain14m
  • Surrogate keys & conformed dimensions12m
  • Slowly Changing Dimensions Type 1 / 2 / 316m
  • Additive, semi-additive, and non-additive facts12m
  • Normalization vs denormalization for analytics12m

Performance & Production SQL

  • Query plans: hash, merge, nested-loop14m
  • Partitioning & clustering in real warehouses12m
  • Views vs materialized views10m
  • PK / FK / CHECK, and how warehouses relax them12m
  • Capstone: model a star from orders18m
Back to track
  1. Learn
  2. SQL & Analytical Warehousing
  3. Understanding Data
  4. Primary keys and foreign keys

Lesson 4 of 29 · Theory first, then run it

Primary keys and foreign keys

sqlbeginner10 min

Overview

A primary key uniquely identifies each row. A foreign key connects one table to another.

On this page7 sections›
  1. 1The idea
  2. 2Why this exists
  3. 3Picture this
  4. 4A small example
  5. 5Common beginner questions
  6. 6What comes next
  7. 7Practice

The idea

A primary key is a column (or combination of columns) that uniquely identifies every row in a table. In the orders table, order_id is the primary key: no two orders share the same order_id. If you try to insert a duplicate order_id, the database will reject it.

A foreign key is a column that references the primary key of another table. The payments table has an order_id column that points to orders.order_id. This link connects the two tables so you can combine payment information with order information in a single query.

Together, primary keys and foreign keys create the 'relational' part of a relational database. They prevent duplicate records and enable you to join data from multiple tables.

Why this exists

Imagine an e-commerce company where the same order_id appears twice in the orders table. When you calculate total revenue by summing order_total, every duplicated order gets counted twice. Your revenue report shows $200,000 when the real number is $150,000. The CEO makes hiring decisions based on wrong numbers.

Primary keys prevent this by guaranteeing uniqueness. Foreign keys ensure that when you look up payment information for an order, you are connecting to the right record. Without these constraints, data quality breaks down silently and dashboards show incorrect numbers.

Picture this

Primary key connects to foreign key
orders tablepayments tableorder_id connects themordersorder_id (PK)user_idorder_totalpaymentspayment_id (PK)order_id (FK)amount

orders.order_id is the primary key. payments.order_id is the foreign key that references it.

Keys are the foundation of data integrity in relational databases.

ConceptWhat it doesExampleWhat breaks without it
Primary keyUniquely identifies each roworders.order_idDuplicate orders, wrong revenue totals
Foreign keyReferences another table's PKpayments.order_idOrphan payments with no matching order
Composite keyTwo+ columns form the key(order_id, product_id)Duplicate line items in an order

You can check if a column is truly unique by grouping on it and looking for counts greater than 1. If the result is empty (zero rows), the column is unique.

A small example

Run the example below in this tab. Read the input, follow the code, then check the output matches what you expect.

SQLUniqueness check
-- Check: is order_id unique in orders?
SELECT order_id, COUNT(*) AS copies
FROM orders
GROUP BY order_id
HAVING COUNT(*) > 1;

An empty result means no duplicates exist. Every order_id appears exactly once. This is the most basic data quality check a data engineer runs.

Keys enable JOINs

When you learn JOINs in a few lessons, you will match rows on these key columns. Understanding keys now makes joins intuitive later.

Copy-paste without reading the output

Run Sample first. If the numbers or row count look wrong, stop and re-read the previous section before changing code.

Common beginner questions

Can a table have no primary key?

Technically yes, but it is bad practice. Without a primary key, you cannot guarantee uniqueness, and duplicates can silently corrupt your data. Production tables should always have a defined key.

What is a surrogate key?

A surrogate key is an artificial identifier (like an auto-incrementing number) that the database generates. It has no business meaning but guarantees uniqueness. Natural keys (like email or order_id) come from the business data itself. You will learn more about surrogate keys in the dimensional modeling module.

What comes next

Now that you understand what data, databases, tables, and keys are, you are ready to write SQL queries. In the next module, you will learn SELECT, WHERE, GROUP BY, and JOIN: the four operations that power almost every SQL query.

Practice

Run Sample to check if order_id is unique in the orders table. The result should be empty (zero rows), proving every order_id appears exactly once. Then complete Exercise: write your own uniqueness check.

Rate:
Was this useful?
Tables, rows, and columnsRelational basics