Results day. Your college portal shows your marks, then the class topper, then how many students passed. Behind each of those screens, the portal asked its database one short question and got an answer back in a blink.

Those questions are written in one language, and it reads almost like English.

See it#

Here is a small students table, the one the rest of this lesson uses:

roll_nonamebranchmarksphone
101AshaCSE7298001
102RaviECE88NULL
103MeenaCSE6598003
104KiranME91NULL
105PriyaCSE8498005

NULL means nothing was recorded: Ravi and Kiran never gave a phone number. Section 2 shows how to test for it.

Now ask it a question: who scored above 80, highest first?

sql
namemarks
Kiran91
Ravi88
Priya84

Read the question out loud and it almost explains itself: pick the name and marks, from students, where marks are over 80, sorted by marks, highest first.

Name it#

That question was written in SQL. SQL (Structured Query Language) is the language you use to ask a relational database for data and to change the data in it. A question written in SQL is called a query.

Every RDBMS speaks it: MySQL, PostgreSQL, Oracle, SQL Server and SQLite. Each adds a few words of its own, but the queries in this lesson work in all of them, except where we say so. (What a relational database is: see What is a database.)

How it works#

1. SELECT picks the columns#

SELECT names the columns you want, and FROM names the table. SELECT name, marks FROM students returns all five rows, with just those two columns. SELECT * means every column.

2. WHERE keeps only the rows that match#

WHERE is a test that each row must pass. You can compare with =, <> (not equal), >, <, >= and <=, and join tests with AND and OR:

sql

That returns Asha and Priya. Meena is in CSE, but 65 fails the second test.

A missing value needs its own test. Ravi and Kiran have no phone number, so their phone is NULL, which means "unknown". Anything compared with an unknown is also unknown, never true, so WHERE phone = NULL matches no rows at all. The test made for it is IS NULL:

sql

That returns Ravi and Kiran. Its opposite is IS NOT NULL.

3. ORDER BY sorts the result#

Without ORDER BY, a database may return rows in any order it likes. ORDER BY marks sorts from lowest to highest, which is the default (ASC). Add DESC for highest first:

sql

That gives Kiran, Ravi, Priya, Asha, Meena: 91, 88, 84, 72, 65. Without DESC you'd get the same names the other way round.

4. DISTINCT drops repeats#

SELECT branch FROM students returns five rows: CSE, ECE, CSE, ME, CSE. SELECT DISTINCT branch FROM students keeps one copy of each different value, so it returns three rows: CSE, ECE and ME. A value that appears only once, like ME, still appears once.

5. Aggregates fold a column into one number#

Five functions turn many rows into a single answer:

FunctionWhat it givesOn our marks
COUNT(*)how many rows5
SUM(marks)the total400
AVG(marks)the average80
MIN(marks)the smallest65
MAX(marks)the largest91

The order matters: WHERE runs first, then the aggregate.

sql

WHERE keeps only the three CSE rows (72, 65 and 84), and then MIN picks 65. Kiran's 91 never reaches MIN, because ME was filtered out first. One more detail: COUNT(phone) counts only the rows where phone isn't NULL, so it gives 3, while COUNT(*) counts every row. (Getting one number per branch instead of one for the whole table is GROUP BY, later in the roadmap.)

That's results day in three queries: your marks are SELECT marks FROM students WHERE roll_no = 101;, the top mark is SELECT MAX(marks) FROM students; (91), and if the pass mark is 70, SELECT COUNT(*) FROM students WHERE marks >= 70; says 4 passed.

6. INSERT, UPDATE and DELETE change the data#

INSERT adds a row:

sql

UPDATE changes values in the rows that match. Asha's marks were rechecked:

sql

DELETE removes the rows that match:

sql

7. Four families of commands#

Every SQL command belongs to one of four families, sorted by what it touches:

FamilyWhat it doesCommands
DDL, Data Definition Languagedefines the structure: tables and columnsCREATE, ALTER, DROP, TRUNCATE
DML, Data Manipulation Languagereads and changes the rowsSELECT, INSERT, UPDATE, DELETE
DCL, Data Control Languagedecides who may do whatGRANT, REVOKE
TCL, Transaction Control Languagesaves or undoes a group of changesCOMMIT, ROLLBACK, SAVEPOINT

In What is a database's words: DDL changes the schema (the design), and DML changes the instance (the rows).

So REVOKE UPDATE ON students FROM intern is DCL: it changes no data and no structure, only the intern's permission to edit the students table. Some books give SELECT a family of its own, DQL (Data Query Language). (What COMMIT and ROLLBACK really protect is a later phase, Transactions.)

8. DELETE vs TRUNCATE vs DROP#

All three remove something. The difference is how much:

DELETETRUNCATEDROP
Removesthe rows that match a WHERE, or all rows without oneevery rowthe rows and the table itself
Can take a WHEREyesnono
The empty table is still thereyesyesno: queries on it now fail
FamilyDMLDDLDDL
Speed on a big tableslow: it removes rows one by onefast: it clears the table in one gofast

After TRUNCATE TABLE students, the table still exists, with its columns, and you can insert into it again. After DROP TABLE students, there's no table left: SELECT * FROM students gives an error. One more difference interviewers like: a DELETE can be undone with ROLLBACK before you commit, while TRUNCATE usually can't, depending on the database. (SQLite has no TRUNCATE. There, DELETE FROM students; with no WHERE does the same job.)

Why it matters#

Every app that shows you data runs SQL behind the screen. Swiggy's "your past orders" is a SELECT with a WHERE on your user id and an ORDER BY date. Placing an order is an INSERT. Editing your address is an UPDATE. Data analysts, backend developers and testers all write it every day.

In interviews, SQL questions come as "what does this query return?" on a small table, so practise reading queries row by row, the way you did above. The classic theory questions are:

Interviews askThe answer you saw
What's the difference between DELETE, TRUNCATE and DROP?some rows, all rows, or the table itself
Which family is GRANT?DCL: it controls access
Why doesn't = NULL work?NULL is unknown, so use IS NULL
Does WHERE run before an aggregate?yes: it filters the rows MIN or COUNT sees
What does DISTINCT do?keeps one copy of each different value

Code#

The table this lesson used, so you can try every query above in any SQL editor:

sql

What to remember#

  • SELECT picks columns, WHERE keeps matching rows, ORDER BY sorts (ASC by default, DESC for highest first), and DISTINCT drops repeats.
  • Test a missing value with IS NULL. = NULL is never true.
  • COUNT, SUM, AVG, MIN and MAX fold a column into one number, and WHERE filters the rows before they do.
  • INSERT adds rows, UPDATE changes them and DELETE removes them. Without a WHERE, UPDATE and DELETE hit every row.
  • DDL shapes tables, DML handles rows, DCL grants access and TCL commits or undoes. DELETE removes some rows, TRUNCATE all of them, DROP the whole table.