Basic Queries

Basic Queries

Imagine walking into a library and wanting to find a book. You wouldn't take every book home — instead, you'd tell the librarian: "I'd like to find science fiction novels published after 2020, sorted by publication date from newest to oldest, and show me the first 5." This process corresponds to the core steps of an SQL query: selecting data, filtering conditions, sorting, and limiting quantity.

In the previous lesson, we learned how to create databases and tables, and insert data. This lesson will learn how to precisely query the data we need from a database.


Core Concepts

1. SELECT Statement

SELECT is the most commonly used statement in SQL, used to retrieve data from database tables. Its basic structure is:

SQL
SELECT column1, column2, ...
FROM table_name;

2. Querying Specific Columns vs. All Columns

Query specific columns (recommended):

SQL
SELECT name, salary FROM employees;

Query all columns:

SQL
SELECT * FROM employees;
💡 Tip: In actual development, it's recommended to explicitly specify the column names you need rather than using *. This improves query efficiency and makes the code clearer.

3. WHERE Condition Filtering

The WHERE clause is used to filter records, returning only rows that meet the conditions:

SQL
SELECT column1, column2
FROM table_name
WHERE condition;

4. Comparison Operators

Operator Description Example
= Equal to salary = 50000
<> or != Not equal to status <> 'Inactive'
> Greater than salary > 50000
< Less than age < 30
>= Greater than or equal to salary >= 50000
<= Less than or equal to age <= 30

5. Logical Operators: AND / OR

SQL
SELECT name, salary, department_id
FROM employees
WHERE salary > 50000 AND department_id = 1;

SELECT name, salary, department_id
FROM employees
WHERE department_id = 1 OR department_id = 2;
💡 Tip: When AND and OR are mixed, AND has higher priority. Use parentheses () to clarify priority and avoid ambiguity.

6. IN / BETWEEN / LIKE

IN — Match any value in a set:

SQL
SELECT name, department_id
FROM employees
WHERE department_id IN (1, 2, 3);

BETWEEN — Match values within a range (inclusive of boundaries):

SQL
SELECT name, salary
FROM employees
WHERE salary BETWEEN 40000 AND 80000;

LIKE — Fuzzy string matching:

SQL
-- Employees whose names start with "J"
SELECT name FROM employees WHERE name LIKE 'J%';

-- Employees whose names are 4 characters long and start with "John"
SELECT name FROM employees WHERE name LIKE 'John_';

7. ORDER BY Sorting

ORDER BY is used to sort the result set:

SQL
-- Sort by salary from high to low
SELECT name, salary
FROM employees
ORDER BY salary DESC;

-- Sort by department ascending, then by salary descending
SELECT name, department_id, salary
FROM employees
ORDER BY department_id ASC, salary DESC;

8. LIMIT Row Limiting

LIMIT is used to restrict the number of returned records:

SQL
-- Return only the first 5 records
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;

-- Skip the first 5, return the next 5 (pagination)
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 5;
💡 Tip: LIMIT is typically used with ORDER BY; otherwise, the order of returned records is undefined.


Basic Syntax/Usage

Complete Structure of a Query Statement

SQL
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column [ASC|DESC]
LIMIT count [OFFSET offset];

The writing order of clauses must be strictly followed:

Order Clause Purpose
1 SELECT Specify columns to query
2 FROM Specify the source table
3 WHERE Filter rows
4 ORDER BY Sort results
5 LIMIT Limit number of returned rows

Common Techniques

SQL
-- Use aliases to make column names more readable
SELECT name AS employee_name, salary AS employee_salary
FROM employees;

-- Remove duplicate values
SELECT DISTINCT department_id
FROM employees;

-- Use expressions in SELECT
SELECT name, salary, salary * 12 AS annual_salary
FROM employees;
💡 Tip:

  • Aliases can use Chinese characters, but English is recommended for team collaboration
  • DISTINCT deduplicates based on the combination of all selected columns
  • Expressions don't modify the original data; they only affect the display of query results

Examples

Example: Query Employees in a Specific Department

Requirement: Query all employee names and salaries in department ID 1, sorted by salary from high to low.

SQL
SELECT name, salary
FROM employees
WHERE department_id = 1
ORDER BY salary DESC;
▶ Try it Yourself

Expected Output:

TEXT
+----------+--------+
| name     | salary |
+----------+--------+
| John     |  85000 |
| Bob      |  62000 |
| Alice    |  55000 |
+----------+--------+

Explanation:

Example: Multi-condition Query

Requirement: Query employees with salary between 60000 and 90000, and department ID is 1 or 2. Show name, department ID, and salary. Sort by department ID ascending, then salary descending.

SQL
SELECT name, department_id, salary
FROM employees
WHERE salary BETWEEN 60000 AND 90000
  AND department_id IN (1, 2)
ORDER BY department_id ASC, salary DESC;
▶ Try it Yourself

Expected Output:

TEXT
+----------+---------------+--------+
| name     | department_id | salary |
+----------+---------------+--------+
| John     |             1 |  85000 |
| Bob      |             1 |  62000 |
| Jane     |             2 |  75000 |
+----------+---------------+--------+

Explanation:

Example: Fuzzy Query and Pagination

Requirement: Find employees whose names contain "J", sorted by hire date descending, showing only records 2 to 3.

SQL
SELECT name, hire_date, salary
FROM employees
WHERE name LIKE '%J%'
ORDER BY hire_date DESC
LIMIT 2 OFFSET 1;
▶ Try it Yourself

Expected Output:

TEXT
+--------+------------+--------+
| name   | hire_date  | salary |
+--------+------------+--------+
| Jane   | 2022-03-15 |  68000 |
| Julia  | 2021-08-20 |  52000 |
+--------+------------+--------+

Explanation:


Scenarios

Scenario 1: Filter High-Salary Employees by Salary Range

HR needs to export a list of employees earning more than 70000, including name, department, and salary, sorted by salary from high to low.

SQL
SELECT e.name AS employee_name,
       d.name AS department_name,
       e.salary AS salary
FROM employees e
JOIN departments d ON e.department_id = d.id
WHERE e.salary > 70000
ORDER BY e.salary DESC;

Notes:

Scenario 2: Paginated Employee List

A web application's employee list page shows 10 records per page. When the user clicks page 3, it needs to skip the first 20 records and display records 21-30.

SQL
-- Page 3, 10 records per page
SELECT id, name, department_id, salary
FROM employees
ORDER BY id ASC
LIMIT 10 OFFSET 20;

Pagination Formula: OFFSET = (page_number - 1) × records_per_page

Page LIMIT OFFSET
Page 1 10 0
Page 2 10 10
Page 3 10 20

❓ FAQ

Q: What's the difference between SELECT * and specifying column names? A: SELECT * returns all columns in the table, while specifying column names returns only the columns you need. In production environments, it's recommended to explicitly specify column names — queries are faster, more readable, and less prone to errors when table structures change.

Q: Can I use aliases in WHERE? A: No. SQL's execution order is FROMWHERESELECTORDER BY. When WHERE executes, aliases haven't been generated yet. If you need to filter by an alias, use a subquery or HAVING (covered in later lessons).

Q: Does BETWEEN include boundary values? A: Yes. BETWEEN 10 AND 20 is equivalent to >= 10 AND <= 20. Both endpoint values are included in the results.

Q: Is LIKE case-sensitive? A: It depends on the database's collation. MySQL is case-insensitive by default, while PostgreSQL is case-sensitive by default. To enforce case sensitivity, PostgreSQL can use LIKE, and MySQL can use the BINARY keyword.


📖 Summary

This lesson covered the core skills of SQL querying:

  1. SELECT — Specify columns to query; use * to query all columns
  2. WHERE — Filter rows with conditions, supporting comparison operators (=, >, <, <>, >=, <=)
  3. Logical OperatorsAND (both), OR (either); use parentheses to control priority
  4. IN — Match any value in a set
  5. BETWEEN — Match values within a range (inclusive of boundaries)
  6. LIKE — Fuzzy matching; % matches multiple characters, _ matches a single character
  7. ORDER BY — Sort; ASC ascending (default), DESC descending
  8. LIMIT / OFFSET — Limit returned rows, enabling pagination

Query statement writing order: SELECTFROMWHEREORDER BYLIMIT


📝 Exercises

Exercise 1: Basic Query

Query all records in the departments table, showing only the name and location columns.

Exercise 2: Condition Filtering and Sorting

Query employees in the employees table with salary greater than or equal to 60000 and hire date after January 1, 2022. Show name, salary, and hire date, sorted by salary descending.

Exercise 3: Comprehensive Query

Query employees in the employees table with department ID 1 or 3, and names not starting with "J". Show name, department ID, and salary. Sort by department ID ascending, salary descending. Return only the first 3 records.


Next Lesson: Data Operations: INSERT, UPDATE, DELETE

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏