Basic Data Filtering with WHERE
In this step, we'll learn how to use the WHERE clause to filter data based on specific conditions. The WHERE clause is one of the most important features in SQL, allowing you to retrieve only the data that meets your criteria.
First, let's connect to MySQL and select our database:
sudo mysql -u root
Once connected:
USE bookstore;
Simple Comparison Operations
Let's start with basic comparison operators:
-- Books priced over $40
SELECT title, price
FROM books
WHERE price > 40;
You should see output like this:
+-------------------------+-------+
| title | price |
+-------------------------+-------+
| The MySQL Guide | 45.99 |
| Advanced Database Concepts | 54.99 |
| Database Administration | 49.99 |
| The Perfect Index | 42.99 |
+-------------------------+-------+
Common comparison operators include:
=
(equal to)
<>
or !=
(not equal to)
>
(greater than)
<
(less than)
>=
(greater than or equal to)
<=
(less than or equal to)
Let's try another example finding books published in a specific year:
SELECT title, author, publication_year
FROM books
WHERE publication_year = 2023;
Using AND and OR
We can combine multiple conditions using AND and OR:
-- Technical books published in 2023
SELECT title, genre, publication_year, price
FROM books
WHERE genre = 'Technical'
AND publication_year = 2023;
Let's try OR to find books that are either very new or very expensive:
SELECT title, publication_year, price
FROM books
WHERE publication_year = 2023
OR price >= 50;
Working with NULL and Boolean Values
To find books that are out of stock:
SELECT title, price, in_stock
FROM books
WHERE in_stock = FALSE;