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.

3 min readUpdated 2026-11-29
In This Lesson
  • 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).

idnametrackhours_studied
1RiyaPython12
2RahulSQL8
3RahulGit5

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:

sql
-- 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):

sql
SELECT *
FROM students;

Filtering Rows with WHERE

Use WHERE to ask for specific rows:

sql
SELECT name, hours_studied
FROM students
WHERE track = 'SQL'
  AND hours_studied >= 5;
Single Quotes for Text in SQL

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)

sql
SELECT name, hours_studied
FROM students
ORDER BY hours_studied DESC
LIMIT 5;
  • ASC sorts smallest → largest (default).
  • DESC sorts largest → smallest (top performers first).
  • LIMIT 5 returns only the first 5 rows.
How SQL Actually Runs Your Query

Even though you write SELECT at the top, the database executes clauses in this order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.

Interactive Walkthrough: SQL Clause Execution OrderStep 1 / 5
1. FROM & JOIN2. WHERE3. GROUP BY & Aggregates4. HAVING5. SELECT → ORDER BY → LIMIT
Active Pipeline State: 5 orders × order_items

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

SQL (SQLite)Live SQL: SELECT, WHERE & ORDER BY
Output

Click “Run Code” to execute this snippet right in your browser.

Quick Checkpoints

Check Your Understanding

Why does every well-designed table have a Primary Key?

Check Your Understanding

Which query returns the top 3 most expensive products?