Welcome to our comprehensive guide on the SQL WHERE Clause! In this tutorial, we'll learn how to filter and manipulate data using the WHERE clause, one of the most essential SQL commands for any data analyst or developer. 📝 Note: This tutorial is designed for beginners and intermediates, so let's start from the basics and gradually build up!
The WHERE clause in SQL allows you to filter the records in a database table based on specific conditions. This is extremely useful when you want to retrieve specific rows of data from a large dataset.
Simple Example:
Let's consider a table named employees with the following columns: id, name, age, and salary.
id | name | age | salary
----------------------------------
1 | John | 28 | 50000
2 | Jane | 30 | 60000
3 | Mark | 35 | 70000
4 | Alice | 25 | 45000
5 | Bob | 40 | 80000
6 | Samantha | 23 | 55000To filter employees with a salary greater than 55000, we can use the WHERE clause:
SELECT * FROM employees WHERE salary > 55000;This query will return the records for employees with a salary of 60000 and 80000.
Comparison operators allow you to compare data from two columns or values. Here are some common comparison operators:
= (Equal to)<> (Not equal to)> (Greater than)< (Less than)>= (Greater than or equal to)<= (Less than or equal to)Example:
To find employees who are older than 30, we can use:
SELECT * FROM employees WHERE age > 30;Logical operators let you combine multiple conditions in a WHERE clause using AND, OR, and NOT.
AND: Both conditions must be true.OR: At least one condition must be true.NOT: The opposite of the specified condition.Example:
To find employees who are either older than 30 or have a salary greater than 55000, we can use:
SELECT * FROM employees WHERE age > 30 OR salary > 55000;Let's test your understanding with a few exercises:
Which SQL query will return the employees with a salary less than or equal to 60000 and older than 25?
Which SQL query will return the employees who have a name starting with 'J' or 'A'?
Stay tuned for our next lesson on SQL AND, OR, and NOT Operators! 🚀