MySQL WHERE


The WHERE clause in MySQL is used to filter records in a SQL query based on specified conditions. It helps you retrieve only the rows that meet certain criteria, which is essential for narrowing down your results and obtaining relevant data.

Syntax

The basic syntax of the WHERE clause is:

SELECT column1, column2, ... FROM table_name WHERE condition;
  • column1, column2, ...: The columns you want to retrieve.
  • table_name: The table from which to retrieve data.
  • condition: The condition that rows must meet to be included in the result set.

Examples

Here are some common uses of the WHERE clause with various conditions:

  1. Basic Filtering

    To retrieve rows where a column matches a specific value:

    SELECT name, salary FROM employees WHERE department = 'Sales';

    This retrieves the name and salary of employees who work in the 'Sales' department.

  2. Using Comparison Operators

    To filter rows based on comparisons:

    • Equal to:

      SELECT name, salary FROM employees WHERE salary = 60000;

      This retrieves employees with a salary exactly equal to 60,000.

    • Not equal to:

      SELECT name, salary FROM employees WHERE salary != 60000;

      This retrieves employees with a salary not equal to 60,000.

    • Greater than:

      SELECT name, salary FROM employees WHERE salary > 60000;

      This retrieves employees with a salary greater than 60,000.

    • Less than:

      SELECT name, salary FROM employees WHERE salary < 60000;

      This retrieves employees with a salary less than 60,000.

    • Greater than or equal to:

      SELECT name, salary FROM employees WHERE salary >= 60000;

      This retrieves employees with a salary of 60,000 or more.

    • Less than or equal to:

      SELECT name, salary FROM employees WHERE salary <= 60000;

      This retrieves employees with a salary of 60,000 or less.