Skip to main content
Zhimalab
中文
Lesson 1 / 21

Meet SQL

What databases and SQL are

A database is an organized collection of data, and MySQL is one of the most popular relational database systems.

SQL (Structured Query Language) is the standard language for working with databases. This course covers core operations such as querying, inserting, updating, and deleting data.

💡
This course simulates SQL execution right in your browser — no installation needed. Click the "Run" button on a code block to see the result.

Let's first see which tables the database has:

SQL
SHOW TABLES;

Take a look at the structure of the students table:

SQL
DESC students;
Quiz
What does SQL stand for?
A Structured Query Language
B Simple Query Language
C Standard Question Language
D System Query Logic
Lesson 2 / 21

SELECT Basics

Querying data from a table

SELECT retrieves data from a table, and * means all columns.

SQL
SELECT * FROM students;

You can also list specific column names, separated by commas:

SQL
SELECT name, age, gender FROM students;
Quiz
Which symbol selects all columns?
A *
B #
C %
D &
Lesson 3 / 21

Filtering with WHERE

Filter rows by condition

The WHERE clause filters rows that meet a condition.

SQL
SELECT * FROM students WHERE age > 20;

Supported comparison operators: = > < >= <= <> !=.

SQL
SELECT * FROM students WHERE gender = '';

Combine multiple conditions with AND / OR:

SQL
SELECT * FROM students WHERE age >= 20 AND gender = '';
Quiz
Which condition finds students whose age is not 20?
A WHERE age = 20
B WHERE age NOT 20
C WHERE age <> 20
D WHERE age IS NOT 20
Lesson 4 / 21

Sorting with ORDER BY

Sort the results

ORDER BY sorts by a column; ASC is ascending (the default) and DESC is descending.

SQL
SELECT * FROM students ORDER BY age DESC;

You can sort by multiple columns; priority goes from left to right:

SQL
SELECT * FROM students ORDER BY dept_id ASC, age DESC;
Quiz
What is the default sort direction?
A ASC (ascending)
B DESC (descending)
C Random
D By primary key
Lesson 5 / 21

LIMIT & Pagination

Limit the number of rows returned

LIMIT restricts how many rows are returned, and is often used for pagination.

SQL
SELECT * FROM students LIMIT 3;

Use LIMIT offset, count for paginated queries:

SQL
SELECT * FROM students LIMIT 2, 3;
Quiz
To fetch rows 4–6 (3 per page), what LIMIT do you write?
A LIMIT 4, 3
B LIMIT 3, 3
C LIMIT 3, 6
D LIMIT 6, 3
Lesson 6 / 21

Aggregate Functions

COUNT SUM AVG MAX MIN

Aggregate functions compute over a set of values and return a single value.

SQL
SELECT COUNT(*) FROM students;
SQL
SELECT AVG(age) FROM students;
SQL
SELECT MAX(score), MIN(score) FROM enrollments;
COUNT(*) counts rows, AVG computes the average, SUM adds values, and MAX/MIN find the extremes.
Quiz
Which function counts the total number of students?
A COUNT(*)
B SUM(*)
C COUNT(ALL)
D TOTAL(*)
Lesson 7 / 21

GROUP BY

Group and aggregate by column

GROUP BY groups rows by a column and is usually combined with aggregate functions.

SQL
SELECT dept_id, COUNT(*) FROM students GROUP BY dept_id;
SQL
SELECT gender, AVG(age) FROM students GROUP BY gender;
Quiz
To count students per department, what comes after GROUP BY?
A GROUP BY dept_id
B GROUP BY COUNT
C GROUP dept_id
D SPLIT BY dept_id
Lesson 8 / 21

Filtering Groups with HAVING

Filter grouped results

HAVING filters the results after grouping — think of it as WHERE for groups.

SQL
SELECT dept_id, COUNT(*) AS cnt FROM students GROUP BY dept_id HAVING cnt > 2;
⚠️
WHERE filters rows before grouping, while HAVING filters groups after grouping. Conditions on aggregates can only use HAVING.
Quiz
Which keyword filters conditions after grouping?
A WHERE
B HAVING
C LIMIT
D ORDER BY
Lesson 9 / 21

DISTINCT

Remove duplicate rows

DISTINCT removes duplicate rows from the query result.

SQL
SELECT DISTINCT gender FROM students;
SQL
SELECT DISTINCT dept_id, gender FROM students;
Quiz
Which is the correct way to get distinct age values?
A SELECT DISTINCT age FROM students
B SELECT UNIQUE age FROM students
C SELECT age DISTINCT FROM students
D SELECT DIFFERENT age FROM students
Lesson 10 / 21

INSERT

Add rows to a table

INSERT INTO adds rows to a table.

SQL
INSERT INTO students (name, gender, age, dept_id, enroll_year) VALUES ('测试同学', '', 20, 1, 2024);

Query to verify after inserting:

SQL
SELECT * FROM students ORDER BY id DESC LIMIT 1;
Quiz
Which statement inserts data?
A INSERT INTO
B ADD INTO
C INSERT TO
D PUT INTO
Lesson 11 / 21

UPDATE

Modify existing rows

UPDATE modifies rows that meet a condition.

SQL
UPDATE students SET age = 21 WHERE name = '赵小明';
⚠️
Without a WHERE clause, ALL rows will be updated — be very careful!
Quiz
Which statement sets age to 20 for all rows?
A UPDATE students SET age = 20 IF ALL
B UPDATE students SET age = 20
C UPDATE students ALL SET age = 20
D UPDATE ALL students SET age = 20
Lesson 12 / 21

DELETE

Delete rows

DELETE removes rows that meet a condition.

SQL
DELETE FROM students WHERE name = '测试同学';
⚠️
Without a WHERE clause, the whole table will be emptied!
Quiz
Which statement deletes rows where age is greater than 22?
A DELETE FROM students WHERE age > 22
B DELETE students WHERE age > 22
C REMOVE FROM students WHERE age > 22
D DROP FROM students WHERE age > 22
Lesson 13 / 21

CREATE and DROP TABLE

CREATE TABLE and DROP TABLE

CREATE TABLE creates a new table; you must define column names and types.

SQL
CREATE TABLE clubs (id INT, name VARCHAR, leader VARCHAR);

Look at the table you just created:

SQL
DESC clubs;

DROP TABLE deletes the entire table (structure and data):

SQL
DROP TABLE clubs;
Quiz
Which statement drops a whole table (including its structure)?
A DELETE TABLE
B DROP TABLE
C REMOVE TABLE
D CLEAR TABLE
Lesson 14 / 21

INNER JOIN

Combine data from multiple tables

INNER JOIN combines two tables on a join condition and returns only rows that match in both.

SQL
SELECT students.name, departments.name AS dept FROM students INNER JOIN departments ON students.dept_id = departments.id;

Use table aliases to keep the query short:

SQL
SELECT s.name, d.name AS dept FROM students s INNER JOIN departments d ON s.dept_id = d.id LIMIT 5;
Quiz
Which keyword introduces the join condition between two tables?
A ON
B WHERE
C BY
D WITH
Lesson 15 / 21

LEFT JOIN

Keep all rows from the left table

LEFT JOIN keeps all rows from the left table; when the right table has no match, the result is filled with NULL.

SQL
SELECT t.name, d.name AS dept FROM teachers t LEFT JOIN departments d ON t.dept_id = d.id;
Quiz
In a LEFT JOIN, what happens to left-table rows with no match in the right table?
A Filled with NULL
B Error
C Row skipped
D Filled with 0
Lesson 16 / 21

Joining Multiple Tables

Join three or more tables

Chaining multiple JOINs lets you combine several tables. Here is a report card (student name + course name + score):

SQL
SELECT s.name AS student, c.name AS course, e.score FROM enrollments e INNER JOIN students s ON e.student_id = s.id INNER JOIN courses c ON e.course_id = c.id ORDER BY e.score DESC LIMIT 5;
Quiz
How many JOINs do you need at minimum to connect 3 tables?
A 1
B 2
C 3
D 4
Lesson 17 / 21

Subquery Basics

A query inside a query

A subquery is a query nested inside another query, often used in WHERE conditions.

SQL
SELECT name FROM students WHERE age > (SELECT AVG(age) FROM students);

Find students older than the average age.

Quiz
Where can a subquery usually appear?
A In WHERE or SELECT clauses
B Only in FROM
C Only in LIMIT
D It cannot be nested
Lesson 18 / 21

IN and NOT IN

Match against a set

IN matches any value in a list; NOT IN matches values not in the list.

SQL
SELECT name FROM students WHERE dept_id IN (1, 2);

A list returned by a subquery can also be used with IN:

SQL
SELECT name FROM teachers WHERE dept_id IN (SELECT id FROM departments WHERE building = '理学楼');
Quiz
Which condition selects students whose dept_id is 1 or 2?
A WHERE dept_id IN (1, 2)
B WHERE dept_id = 1 OR 2
C WHERE dept_id IN 1, 2
D WHERE dept_id = (1, 2)
Lesson 19 / 21

Handling NULL

IS NULL and IS NOT NULL

NULL means missing data. You cannot test it with = NULL; you must use IS NULL.

SQL
SELECT * FROM students WHERE age IS NOT NULL;

COALESCE returns the first non-NULL value:

SQL
SELECT name, COALESCE(age, 0) AS age FROM students LIMIT 3;
Quiz
What is the correct way to test whether age is NULL?
A WHERE age IS NULL
B WHERE age = NULL
C WHERE age == NULL
D WHERE age EQUALS NULL
Lesson 20 / 21

Useful Functions

String and numeric functions

UPPER/LOWER change case, LENGTH returns the length, and CONCAT joins strings.

SQL
SELECT name, UPPER(name) AS upper_name, LENGTH(name) AS len FROM students LIMIT 3;

ROUND rounds a number and ABS returns the absolute value.

SQL
SELECT AVG(score) AS avg_score, ROUND(AVG(score), 2) AS rounded FROM enrollments;
Quiz
Which function converts a string to uppercase?
A UPPER()
B BIG()
C CAPITAL()
D TO_UPPER()
Lesson 21 / 21

Putting It All Together

Apply what you have learned

Get the average score of each course, sorted by the average in descending order:

SQL
SELECT c.name AS course, ROUND(AVG(e.score), 1) AS avg_score FROM enrollments e INNER JOIN courses c ON e.course_id = c.id GROUP BY c.name ORDER BY avg_score DESC;

Find the student with the highest average score:

SQL
SELECT s.name, AVG(e.score) AS avg_score FROM enrollments e INNER JOIN students s ON e.student_id = s.id GROUP BY s.name ORDER BY avg_score DESC LIMIT 1;
🎉
Congratulations — you have finished all 21 lessons! You now know the MySQL basics and can go on to advanced topics such as indexes, transactions, and views.
Quiz
For multi-table statistics and sorting, which combination should you use?
A JOIN + GROUP BY + ORDER BY
B INSERT + UPDATE
C CREATE + DROP
D LIMIT + OFFSET