SQL (Structured Query Language) is how programs talk to databases. Its most-used command is SELECT, which asks a table for rows and columns. Learn SELECT with WHERE, ORDER BY, LIMIT and GROUP BY, and you can answer most everyday questions about your data.
In this lesson you will learn
- What a table, row and column are
- How to choose columns with
SELECT - How to filter rows with
WHERE - How to sort and limit results
- How to count and average with
GROUP BY - How
NULLbehaves
The Sample Table
A database stores data in tables. Each row is one record and each column is one field. All examples here use this students table; one student, Nadia, has no CGPA recorded yet, which SQL stores as NULL. The outputs were produced by running each query in SQLite.
Choosing Columns With SELECT
SELECT name, city, cgpa FROM students;
Output
+--------+------------+------+
| name | city | cgpa |
+--------+------------+------+
| Nusrat | Dhaka | 3.82 |
| Arif | Chattogram | 3.41 |
| Tania | Dhaka | 3.95 |
| Imran | Khulna | 3.1 |
| Mitu | Sylhet | 3.67 |
| Rafi | Dhaka | 2.98 |
| Sabbir | Rajshahi | 3.55 |
| Nadia | Chattogram | NULL |
+--------+------------+------+
(8 rows)
List the columns you want after SELECT and the table after FROM. SELECT * returns every column, which is handy for exploring but wasteful in real programs.
Filtering Rows With WHERE
SELECT name, dept, cgpa
FROM students
WHERE city = 'Dhaka' AND cgpa >= 3.5
ORDER BY cgpa DESC;
Output
+--------+------+------+
| name | dept | cgpa |
+--------+------+------+
| Tania | CSE | 3.95 |
| Nusrat | CSE | 3.82 |
+--------+------+------+
(2 rows)
WHERE keeps only rows that match the condition. Combine conditions with AND, OR and NOT. Text values go in single quotes. Rafi is in Dhaka too, but his CGPA is below 3.5, so he is filtered out. ORDER BY cgpa DESC sorts from highest to lowest.
| Operator | Example |
|---|---|
=, <>, <, >= | cgpa >= 3.5 |
BETWEEN | cgpa BETWEEN 3 AND 3.5 |
IN | city IN ('Dhaka', 'Sylhet') |
LIKE | name LIKE 'N%' (starts with N) |
IS NULL | cgpa IS NULL |
DISTINCT, LIMIT and NULL
SELECT DISTINCT dept FROM students ORDER BY dept;
SELECT name, cgpa FROM students ORDER BY cgpa DESC LIMIT 3;
SELECT name, city FROM students WHERE cgpa IS NULL;
Output
+------+
| dept |
+------+
| BBA |
| CSE |
| EEE |
+------+
(3 rows)
+--------+------+
| name | cgpa |
+--------+------+
| Tania | 3.95 |
| Nusrat | 3.82 |
| Mitu | 3.67 |
+--------+------+
(3 rows)
+-------+------------+
| name | city |
+-------+------------+
| Nadia | Chattogram |
+-------+------------+
(1 row)
DISTINCTremoves duplicate rows, giving each department once.ORDER BY ... LIMIT 3gives a top-three list. (SQL Server writesSELECT TOP 3instead.)NULLmeans “unknown”, socgpa = NULLnever matches anything. Always writeIS NULLorIS NOT NULL.
Counting and Averaging With GROUP BY
SELECT dept, COUNT(*) AS students, ROUND(AVG(cgpa), 2) AS avg_cgpa
FROM students
GROUP BY dept
ORDER BY avg_cgpa DESC;
Output
+------+----------+----------+
| dept | students | avg_cgpa |
+------+----------+----------+
| CSE | 4 | 3.81 |
| BBA | 2 | 3.33 |
| EEE | 2 | 3.2 |
+------+----------+----------+
(3 rows)
GROUP BY dept makes one result row per department. Aggregate functions summarise each group: COUNT, SUM, AVG, MIN and MAX. AS names the result columns. Look closely at CSE: COUNT(*) counts all 4 students, but AVG(cgpa) averages only the 3 non-NULL values. To filter groups afterwards, use HAVING, for example HAVING COUNT(*) >= 3.
The Order of a SELECT Statement
Clauses must be written in this order:
SELECT columns
FROM table
WHERE row_condition
GROUP BY columns
HAVING group_condition
ORDER BY columns
LIMIT n;
Common SELECT Mistakes
- Double quotes around text. Standard SQL uses single quotes for text:
'Dhaka'. = NULLinstead ofIS NULL. It silently returns no rows.- Selecting a column that is not grouped. With
GROUP BY dept, every other selected column must be inside an aggregate. - Using
WHEREon an aggregate.WHERE COUNT(*) > 2fails; useHAVING. SELECT *in production code. Name the columns you need.
Practice Exercises
Exercise 1. Write a query for the names of all students from Chattogram.
Show answer
SELECT name FROM students WHERE city = 'Chattogram';
It returns Arif and Nadia.
Exercise 2. Count how many students each city has.
Show answer
SELECT city, COUNT(*) AS students FROM students GROUP BY city;
Exercise 3. Which students have a CGPA between 3.0 and 3.5?
Show answer
SELECT name, cgpa FROM students WHERE cgpa BETWEEN 3.0 AND 3.5;
Arif (3.41) and Imran (3.10).
Frequently Asked Questions
Is SQL case-sensitive?
Keywords are not: select and SELECT are the same. Writing keywords in capitals is a common style. Whether text comparisons are case-sensitive depends on the database.
Which database should I practise on?
SQLite needs no server and is built into Python, so it is ideal for learning. MySQL and PostgreSQL are the most common free choices for websites.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping; HAVING filters groups after aggregation.
Summary
SELECT columns FROM tablereads data;WHEREfilters rows.ORDER BYsorts,LIMITcaps the number of rows,DISTINCTremoves duplicates.GROUP BYwithCOUNT,AVGand friends summarises groups;HAVINGfilters them.- Test for missing values with
IS NULL, never= NULL.
