Be able to use a single criterion, or multiple criteria to select subsets of data using a query
18 Databases – Selecting Data with Queries
What is a Query?
Think of a database as a huge digital library 📚. A query is like asking the librarian for a specific book or set of books. In SQL (the language most databases use), we write queries to select the data we need.
The SELECT Statement
The basic structure of a query is:
SELECT column1, column2, … FROM table_name WHERE condition;
SELECT tells the database which columns you want.
FROM tells it which table.
WHERE filters the rows based on a condition.
Single Criterion – One Condition
Suppose we have a table called Students:
| ID | Name | Grade | Age |
|---|---|---|---|
| 1 | Alice | A | 15 |
| 2 | Bob | B | 16 |
| 3 | Charlie | A | 15 |
To get all students who are in Grade A:
SELECT Name, Age FROM Students WHERE Grade = 'A';
This will return:
- Alice, 15
- Charlie, 15
Multiple Criteria – Combining Conditions
Sometimes you want to narrow down further. Use AND, OR, and NOT to combine conditions.
AND – All Conditions Must Be True
Students who are Grade A and Age 15:
SELECT Name FROM Students WHERE Grade = 'A' AND Age = 15;
OR – Any Condition Can Be True
Students who are Grade A or Age 16:
SELECT Name FROM Students WHERE Grade = 'A' OR Age = 16;
NOT – Exclude a Condition
All students who are NOT in Grade B:
SELECT Name FROM Students WHERE NOT Grade = 'B';
Comparison Operators
Use these to compare numeric values:
=equals<less than>greater than<=less than or equal to>=greater than or equal to!=not equal
Example: Students older than 15:
SELECT Name FROM Students WHERE Age > 15;
Special Operators – LIKE, IN, BETWEEN
LIKE is used for pattern matching (think of it as a wildcard search).
SELECT Name FROM Students WHERE Name LIKE 'A%';
IN lets you specify a list of acceptable values.
SELECT Name
FROM Students
WHERE Grade IN ('A', 'B');
BETWEEN checks if a value lies within a range.
SELECT Name FROM Students WHERE Age BETWEEN 15 AND 16;
Putting It All Together – A Complete Example
Find the names of students who are either in Grade A or B, are older than 15, and whose names start with the letter C:
SELECT Name FROM Students WHERE (Grade = 'A' OR Grade = 'B') AND Age > 15 AND Name LIKE 'C%';
Quick Practice
- Write a query to list all students who are exactly 16 years old.
- Modify the query to also show their grades.
- Change the query to exclude students with Grade
C.
💡 Tip: Think of each condition as a filter. The more filters you add, the smaller the group of results.
Key Takeaways
- Use
SELECTto choose columns. - Use
WHEREto filter rows. - Combine conditions with
AND,OR,NOT. - Use comparison operators for numeric data.
- Use
LIKE,IN, andBETWEENfor more advanced filtering.
Happy querying! 🚀
Revision
Log in to practice.