Filtering, Sorting, and Pagination

Filter the records you need and return pages in a consistent order

🎯 Introduction

By the end of this article, you will be able to filter the records you need and return pages in a consistent order.


🛠 Prepare a fixed query dataset

Create a dedicated query table in blog_demo so that the insertion, update, and deletion exercises do not affect your results:

CREATE TABLE query_user (
    id INT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    age INT,
    city VARCHAR(50) NOT NULL,
    created_at DATETIME NOT NULL
);

Insert a fixed dataset. The aggregation, join, and performance articles will also use it:

INSERT INTO query_user VALUES
    (1, 'Xiao Ming', 25, 'Beijing', '2026-10-01 09:00:00'),
    (2, 'Xiao Hong', 30, 'Shanghai', '2026-10-02 09:00:00'),
    (3, 'Xiao Gang', 22, 'Beijing', '2026-10-03 09:00:00'),
    (4, 'Xiao Lin', 30, 'Shanghai', '2026-10-04 09:00:00'),
    (5, 'Xiao An', NULL, 'Hangzhou', '2026-10-05 09:00:00');

After insertion, query_user contains the following complete dataset:

idusernameagecitycreated_at
1Xiao Ming25Beijing2026-10-01 09:00:00
2Xiao Hong30Shanghai2026-10-02 09:00:00
3Xiao Gang22Beijing2026-10-03 09:00:00
4Xiao Lin30Shanghai2026-10-04 09:00:00
5Xiao AnNULLHangzhou2026-10-05 09:00:00

Initialize it only once. If the table already exists, check whether its data matches instead of deleting it. Run USE blog_demo whenever you reconnect the client.


🔎 Filter matching rows with WHERE

Find users in Beijing who are at least 23 years old:

SELECT id, username FROM query_user
WHERE city = 'Beijing' AND age >= 23;

Query result:

idusername
1Xiao Ming

AND requires both conditions to be true; OR requires either condition. Use parentheses to make grouping explicit when combining them:

SELECT id, username FROM query_user
WHERE (city = 'Beijing' OR city = 'Shanghai') AND age >= 25
ORDER BY id;

Query result:

idusername
1Xiao Ming
2Xiao Hong
4Xiao Lin

This selects users in Beijing or Shanghai, then excludes those younger than 25.


📍 Match multiple values with IN

SELECT id, username FROM query_user
WHERE city IN ('Beijing', 'Hangzhou') ORDER BY id;

Query result:

idusername
1Xiao Ming
3Xiao Gang
5Xiao An

IN matches a city against any value in the list, making it useful for filtering by multiple cities.


🔤 Match text patterns with LIKE

SELECT id, username FROM query_user WHERE username LIKE 'Xiao%';

Query result:

idusername
1Xiao Ming
2Xiao Hong
3Xiao Gang
4Xiao Lin
5Xiao An

% matches text of any length. To search for text anywhere in a value, put % on both sides, but evaluate the performance of these searches separately on large datasets.


🕳 Use IS NULL for missing values

SELECT id, username FROM query_user WHERE age IS NULL;

Query result:

idusername
5Xiao An

Do not write age = NULL. NULL represents an unknown value, and ordinary equality comparisons cannot detect missing values this way.

You can substitute a display value for an unknown age:

SELECT username, COALESCE(age, 0) AS display_age
FROM query_user WHERE id = 5;

Query result:

usernamedisplay_age
Xiao An0

COALESCE selects the first non-NULL value. It only changes the query result; it does not update the stored age to 0. A page could instead display “Not provided”.


🗓 Query a time range

Query records from October 2 and 3:

SELECT id, username FROM query_user
WHERE created_at >= '2026-10-02' AND created_at < '2026-10-04'
ORDER BY id;

Query result:

idusername
2Xiao Hong
3Xiao Gang

An inclusive start and exclusive end cover all times before the end boundary without constructing a timestamp ending in 23:59:59.


📄 Sort before paginating

Sort by age from highest to lowest, breaking ties by id from lowest to highest:

SELECT id, username, age FROM query_user
ORDER BY age DESC, id ASC LIMIT 2;

Query result:

idusernameage
2Xiao Hong30
4Xiao Lin30

DESC means descending order, and ASC means ascending order. Adding id gives records with the same age a deterministic order.

Read the next page using the same ordering:

SELECT id, username, age FROM query_user
ORDER BY age DESC, id ASC LIMIT 2 OFFSET 2;

Query result:

idusernameage
1Xiao Ming25
3Xiao Gang22

LIMIT 2 retrieves two records; OFFSET 2 skips the first two. With a page size of pageSize, the offset is (page - 1) × pageSize.

Deterministic sorting resolves ambiguous ordering among equal values. However, insertions or deletions between page requests can still cause offset pagination to repeat or skip records. The performance article covers continuously loading lists.


❓ Questions and Answers

Q1: Are results sorted by id without ORDER BY?

Do not rely on this behavior. The database does not guarantee a default result order. Specify ORDER BY whenever order matters.

Q2: How do I get a list of distinct cities?

Use SELECT DISTINCT city FROM query_user ORDER BY city. DISTINCT removes duplicates based on the combination of selected columns.

Q3: Can BETWEEN query dates?

Yes, but it includes both endpoints. For date-time queries, a range greater than or equal to the start and less than the end usually makes boundaries clearer.


🧪 Exercise

Query users in Shanghai, order by id descending, and retrieve one record. Expect Xiao Lin, with ID 4. Then query users whose age is missing.

-- Write your SQL or record your verification results here