MySQL : WHERE Clause

In MySQL, the WHERE clause is used in conjunction with the SELECT statement to filter rows based on specified conditions. It allows you to narrow down the result set to only include rows that meet certain criteria. Here's the basic syntax of the SELECT statement with the WHERE clause:


SELECT column1, column2, ...
FROM table_name
WHERE condition;

 

Where:

  • column1, column2, etc. are the names of the columns you want to retrieve.
  • table_name is the name of the table from which you want to retrieve data.
  • condition is the expression that specifies the criteria for filtering rows.

Here are some common examples of conditions that can be used in the WHERE clause:

1. Equal to: This condition filters rows where the specified column is equal to a specific value.


SELECT * FROM table_name WHERE column1 = 'value';
 

2. Not equal to: This condition filters rows where the specified column is not equal to a specific value.


SELECT * FROM table_name WHERE column1 != 'value';
 

3. Greater than: This condition filters rows where the specified column is greater than a specific value.


SELECT * FROM table_name WHERE column1 > value;
 

4. Less than: This condition filters rows where the specified column is less than a specific value.


SELECT * FROM table_name WHERE column1 < value;
 

5. Greater than or equal to: This condition filters rows where the specified column is greater than or equal to a specific value.


SELECT * FROM table_name WHERE column1 >= value;
 

6. Less than or equal to: This condition filters rows where the specified column is less than or equal to a specific value.


SELECT * FROM table_name WHERE column1 <= value;
 

7. IN: This condition filters rows where the specified column's value matches any value in a list.


SELECT * FROM table_name WHERE column1 IN ('value1', 'value2', 'value3');
 

8. LIKE: This condition is used to match patterns in a column's value using wildcards `%` (matches zero or more characters) and `_` (matches a single character).


SELECT * FROM table_name WHERE column1 LIKE 'pattern%';
 

9.  AND, OR, NOT: You can combine multiple conditions using logical operators such as AND, OR, and NOT to create complex filtering criteria.


SELECT * FROM table_name WHERE condition1 AND condition2;
 

These are some examples of how the WHERE clause can be used to filter rows in MySQL queries. It's a powerful tool for retrieving specific data from a database based on specified conditions.