1. Database Basics & Querying
What Is a Database? Tables, Keys & SELECT
Understand relational databases with a spreadsheet analogy, learn rows, columns, and primary keys, and write your first SELECT, WHERE, ORDER BY, and LIMIT queries.
- Understand relational tables, rows, columns, and Primary Keys
- Retrieve exact columns and filter rows with SELECT and WHERE
- Sort and cap query results using ORDER BY and LIMIT
If you have ever used Microsoft Excel or Google Sheets, you already understand 70% of how a relational database works.
Think of a database as a workbook containing multiple connected spreadsheets (tables). Each table has columns (like name, email, price) and rows (one record per student, product, or order). Unlike a spreadsheet, a database can safely handle millions of rows and thousands of users at the same time.
Why Primary Keys Matter
Every row needs one unique ID so two people with the same name ("Rahul Verma") never get confused. That column is called a Primary Key (id).
| id | name | track | hours_studied |
|---|---|---|---|
| 1 | Riya | Python | 12 |
| 2 | Rahul | SQL | 8 |
| 3 | Rahul | Git | 5 |
Notice rows 2 and 3 share the name "Rahul", yet their id (2 and 3) keeps them 100% distinct.
Your First Query: SELECT and FROM
SQL (Structured Query Language) reads like plain English:
-- Get only the columns you need
SELECT name, track
FROM students;Or fetch every column with * (great while exploring, though in production apps it's best to list exact column names):
SELECT *
FROM students;Filtering Rows with WHERE
Use WHERE to ask for specific rows:
SELECT name, hours_studied
FROM students
WHERE track = 'SQL'
AND hours_studied >= 5;In SQL, text values use single quotes ('SQL'), not double quotes. Double quotes are reserved for column or table names in databases like PostgreSQL.
Sorting & Limiting Results (ORDER BY + LIMIT)
SELECT name, hours_studied
FROM students
ORDER BY hours_studied DESC
LIMIT 5;ASCsorts smallest → largest (default).DESCsorts largest → smallest (top performers first).LIMIT 5returns only the first 5 rows.
Even though you write SELECT at the top, the database executes clauses in this order:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Step 1: FROM / JOIN builds the working dataset
SQL first reads tables and matches JOIN conditions before looking at any column aliases in SELECT.
Try It Yourself: Live SQL Query
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
Why does every well-designed table have a Primary Key?
Which query returns the top 3 most expensive products?