We use the MySQL where keyword when we want to target only a particular set of data. That is, we might use it if we wanted to return all rows in a table where a particular condition holds.
The MySQL WHERE keyword is important when combined with queries to limit the set of data that the query will be performed on. Note that we can also combine the conditions we use with the where keyword using the MySQL And & Or operators.
We can use the where keyword with MySQL select queries, MySQL update queries, and MySQL delete queries. The MySQL tutorial below explains.
Suppose we have a database with a table called "employees" like this one:
first_name | last_name |
---|---|
Paul | Pitterson |
Francine | Beecham |
Raul | DiNozzo |
Anthony | DiNozzo |
Suppose we wanted to list all the persons with the last name "DiNozzo". We would do it like this:
SELECT * FROM employees WHERE last_name = 'DiNozzo';
That would return:
first_name | last_name |
---|---|
Raul | DiNozzo |
Anthony | DiNozzo |
So as we can see (and as we said above), the WHERE clause is used to limit the amount of rows which will be affected by our query. In other words, we use the WHERE clause to tell MySQL which set of records we want the query to run on.
The use of WHERE is similar even if we are using a different command. If we wanted to run a MySQL update query to make an update of first name based on last name we might do this:
UPDATE employees SET first_name = 'Vince' WHERE last_name = 'DiNozzo';
Once again, we can see how the WHERE clause is used to limit the rows affected by the update to only those which matched a particular last name criteria.
The wildcard for matching data in the database is the percent ( % ) symbol. We use it when we want to match any character or characters at the particular location where it is placed.
For example, if we wanted to match all the employees with a last name starting with the letter 'P' we would do this:
SELECT * FROM employees WHERE last_name LIKE 'P%';
This would return:
first_name | last_name |
---|---|
Paul | Pitterson |
If you look at the SQL, you will see that we specified the beginning character which was 'P' and then used the wildcard ( % ) symbol to indicate that we don't care what characters come next.
Using wildcards when performing queries is at the heart of searching for data. We simply tell MySQL the part that we know, and then from there, it is smart enough to get all data which matches our partial criteria.
You may want to check out our MySQL Select Query tutorial as SELECT statements are usually used with WHERE clauses.
We hope this MySQL tutorial was useful.