Module 6 · Lesson 2

SQL Queries

Learn the core SQL clauses for retrieving data: SELECT, WHERE, ORDER BY, and LIMIT.

Audio: SQL Queries
0:000:00

SQL Queries

SQL (Structured Query Language) is the standard way to talk to relational databases. The single most important statement is SELECT, which retrieves rows from one or more tables.

The SELECT Statement

A basic query has four common pieces:

SELECT columns
FROM table
WHERE condition
ORDER BY column [ASC|DESC]
LIMIT n;

SELECT lists which columns you want back. * means "all columns," but in real code you should name them explicitly so the result is stable when the schema changes.

WHERE Filters Rows

WHERE restricts which rows are returned. You can use comparison operators (=, <, >, <=, >=, <>), BETWEEN, IN, LIKE for pattern matching, and combine conditions with AND, OR, and NOT. Only rows where the condition evaluates to true make it into the result.

ORDER BY and LIMIT

ORDER BY sorts the result rows. Default order is ascending; add DESC for descending. LIMIT caps how many rows come back, which is essential for pagination and for queries against large tables. The example above grabs the two most expensive products that cost more than two dollars.

Why Set-Based Thinking Matters

SQL is declarative: you describe the result you want, not the steps to compute it. The database's query planner figures out the best way to satisfy your request. This is why a single SQL query can be far faster than equivalent procedural code — the engine knows about indexes, statistics, and parallelism that your loop does not.

Try It Yourself

  • Write a query that returns all products under $5, sorted alphabetically by name
  • Add a category column and select only products in the "office" category
  • Use LIKE 'P%' to find every product whose name starts with the letter P

Code Playground

Edit the code below and click Run to see the output. Switch between languages using the tabs.

Loading editor...

Enjoying the lesson? Unlock the full Databases & SQL from $4.99/mo.

See plans →