Friday, September 22, 2023

How do you filter rows using the WHERE clause?

 Filtering rows using the WHERE clause is a fundamental operation in SQL (Structured Query Language) that allows you to select specific rows from a database table based on a specified condition. The WHERE clause is commonly used in SQL statements such as SELECT, UPDATE, and DELETE to filter records.

Here's how you use the WHERE clause to filter rows:


  1. SELECT Statement: When you want to retrieve data from a table based on specific criteria, you use the WHERE clause with the SELECT statement. For example:

    SELECT column1, column2 FROM table_name WHERE condition;
    • SELECT specifies the columns you want to retrieve.
    • table_name is the name of the table you're querying.
    • condition is the filtering condition.

    Example:

    SELECT first_name, last_name FROM employees WHERE department = 'HR';

    This SQL statement would retrieve the first and last names of employees who work in the HR department.

  2. UPDATE Statement: The WHERE clause is also used when you want to update specific rows in a table. It ensures that the update only affects rows that meet the specified condition. For example:

    UPDATE table_name SET column1 = new_value WHERE condition;

    Example:

    UPDATE products SET price = 15.99 WHERE category = 'Electronics';

    This SQL statement would update the price of products in the 'Electronics' category to $15.99.

  3. DELETE Statement: The WHERE clause is used with the DELETE statement to remove specific rows from a table. It ensures that only the rows matching the condition are deleted. For example:

    DELETE FROM table_name WHERE condition;

    Example:

    DELETE FROM customers WHERE last_purchase_date < '2022-01-01';

    This SQL statement would delete customer records whose last purchase date is before January 1, 2022.

The condition in the WHERE clause can be quite complex, using logical operators (e.g., AND, OR) and comparison operators (e.g., =, <, >, !=, LIKE, etc.), as well as functions and subqueries to specify the filtering criteria for the rows you want to retrieve, update, or delete.

Remember to be careful when using the WHERE clause, especially with the DELETE statement, to ensure you are targeting the correct rows, as it can result in data loss if used improperly. Always double-check your conditions before executing SQL statements with a WHERE clause.

No comments:

Post a Comment

If you have any doubts. Please let me know

How can you create an alias for a table in a SQL query?

In SQL, you can create an alias for a table in a query to give the table a temporary, alternative name that you can use in the query. Table ...