Course contents · Lesson 7 of 17

SQL Basics: SELECT, WHERE and JOIN for Beginners

How Apps Are Built · Lesson 7 of 17 · 9 min Foundations

Search a shopping app for kettles under ₹2,000, cheapest first, and a list appears. Behind it, the backend often asks the database a short question in SQL. This lesson covers SQL basics: reading data with SELECT, filtering, sorting and counting it, joining two tables, and changing data safely.

SELECT and FROM: choose columns from a table

As What Is a Database? showed, a relational database keeps data in tables of rows and columns, and SQL (Structured Query Language) is how you ask it questions. Each question is a query, and its answer, the result, is itself a small table.

The examples use two illustrative tables. books has the columns id, title, year, copies (how many the library owns) and author_id, a foreign key holding an id from authors. That table has id and name: Jane Austen, Rabindranath Tagore, Premchand, and R. K. Narayan, who has no book listed yet.

The simplest query names the columns you want and the table that holds them: SELECT title, year FROM books;. Read it aloud: select the title and year, from books. You get every row, but only those two columns. The semicolon ends the statement, one complete instruction.

SELECT *, read "select star", means every column: SELECT * FROM books; returns the whole table. Handy for a first look, but apps usually name only the columns they need.

Keywords work in any letter case, and text values go in single quotes, as in 'Godan'.

Filter and sort: WHERE, ORDER BY and LIMIT

WHERE keeps only the rows that pass a condition, a test that is true or false for each row. WHERE year > 1900 keeps books published after 1900. Other tests include = and <> (not equal), and AND or OR combine two tests.

ORDER BY year sorts the result oldest first, because ascending is the default; add DESC (descending) for newest first. Without ORDER BY, the order is not guaranteed and can change.

LIMIT 3 returns at most three rows. Pair it with ORDER BY, or "the first three" means whichever three come out first. SQLite, PostgreSQL and MySQL accept LIMIT; some databases, such as Microsoft SQL Server, use other words.

The diagram runs SELECT title, year FROM books WHERE year > 1900 ORDER BY year DESC;. Notice that WHERE chooses rows and SELECT chooses columns: the result is where the two highlights cross, sorted newest first.

Before and after. The query SELECT title, year FROM books WHERE year greater than 1900 ORDER BY year DESC runs on an illustrative books table with columns id, title, year, copies and author_id. Pride and Prejudice, 1813, and Sense and Sensibility, 1811, are crossed out because they fail the test. Gitanjali, 1910, and Godan, 1936, are ticked and highlighted green. The title and year columns are outlined in purple. An arrow leads to the result: two rows, two columns, Godan 1936 then Gitanjali 1910
The result is the overlap of the rows WHERE keeps and the columns SELECT names.

Count and group: COUNT, SUM and GROUP BY

An aggregate function turns many rows into one value. SELECT COUNT(*) FROM books; counts the rows and returns 4. SELECT SUM(copies) FROM books; adds up a column and returns 10, the library's total copies.

GROUP BY splits the rows into groups that share a value and runs the aggregate once per group. SELECT author_id, COUNT(*) FROM books GROUP BY author_id; returns one row per author: author 1, Jane Austen, has 2 books; authors 2 and 3 have 1 each.

Select only grouped columns and aggregates: adding title makes no sense, since which of Austen's two titles would her one row show?

To filter groups, use HAVING: add HAVING COUNT(*) > 1 and only Austen's row remains. WHERE can't do this, because it runs before the groups exist. The flowchart shows the full order, which differs from the one you type.

Flowchart. At the top, the typed order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Below, the order the database works in, joined by arrows: 1 FROM, take the tables, joins happen here; 2 WHERE, keep rows that pass the test; 3 GROUP BY, gather rows that share a value; 4 HAVING, keep groups that pass the test; 5 SELECT, pick columns and compute values; 6 ORDER BY, sort the rows, ascending unless DESC; 7 LIMIT, keep the first N rows. A note says WHERE filters rows and HAVING filters groups. A banner says SELECT is typed first but runs fifth, and LIMIT runs last
You type SELECT first, but it runs fifth, and LIMIT always runs last.

This is the logical order: the engine may take shortcuts, but the answer is as if it ran these steps in turn. Because LIMIT comes after ORDER BY, "newest three" really is the newest three.

JOIN: combine two tables on a matching key

The books table stores an author_id, not a name. A join combines rows from two tables wherever a key matches: SELECT authors.name, books.title FROM authors JOIN books ON books.author_id = authors.id;. ON gives the matching rule. A prefix such as authors. says which table a column comes from, which matters because both tables have an id.

A plain JOIN is an INNER JOIN, the default kind: it returns only pairs that match. Narayan has no books, so he drops out. Jane Austen appears twice, because a join makes one row for each matching pair.

A LEFT JOIN keeps every row of the left table, the one named before JOIN, matched or not. Write FROM authors LEFT JOIN books ON … and Narayan stays, with NULL, SQL's marker for "no value", as his title. That suits questions about what is missing, such as customers who never ordered.

In the diagram, each circle is a table and the overlap is the matching pairs. A Venn diagram can't show repeated rows, so read the results under it too.

Two Venn diagrams of an illustrative authors table and books table, matched on books.author_id equals authors.id. Left, authors JOIN books: only the overlap is shaded, R. K. Narayan is dropped, and the result has four rows: Jane Austen with Pride and Prejudice, Jane Austen with Sense and Sensibility, Rabindranath Tagore with Gitanjali, Premchand with Godan. Right, authors LEFT JOIN books: the whole authors circle is shaded, and the result has the same four rows plus R. K. Narayan with NULL as the title. A banner says each matching pair is one row, so Austen appears twice
INNER JOIN keeps only matches; LEFT JOIN keeps every author and fills the gap with NULL.

Change data: INSERT, UPDATE and DELETE

SELECT only reads. Three other statements change what is stored. INSERT adds rows: INSERT INTO authors (id, name) VALUES (5, 'Mahasweta Devi');. UPDATE changes existing rows: UPDATE books SET copies = 5 WHERE id = 4; gives Godan 5 copies. DELETE removes rows: DELETE FROM books WHERE id = 2; removes Sense and Sensibility.

WHERE picks the rows to change, exactly as in SELECT. Leave it out and the statement changes every row: UPDATE books SET copies = 0; zeroes every book, and DELETE FROM books; empties the table. The database does not ask "are you sure?"

Two habits keep you safe. First, run the same WHERE in a SELECT to see which rows match. On real data, also use a transaction, which saves changes together or not at all: type BEGIN;, make the change, check it, then COMMIT; to keep it or ROLLBACK; to undo it.

Check yourself

You want the three newest books. Why is LIMIT 3 alone not enough?

LIMIT only caps the count, so without ORDER BY year DESC you may get any three rows. LIMIT runs after sorting, so adding ORDER BY makes them the newest three.

A plain JOIN of customers and orders leaves out a customer who never ordered. Why, and what would you change?

A plain JOIN is an inner join, which keeps only matching pairs, and that customer matches no order. Use customers LEFT JOIN orders: they appear, with NULL in the order columns.

Someone meant to fix one book and ran UPDATE books SET copies = 0; What happened, and how could they have prevented it?

With no WHERE, every book now shows 0 copies. A WHERE such as id = 4, tested first in a SELECT, would have limited it, and a transaction would have let them roll back.