Logical Operators in SQL for Data Analytics
🎓 Who Is This For?
This guide is designed for fresh graduates and aspiring data analysts who are just starting with SQL. If you have basic SQL knowledge and want to harness the power of logical operators to enhance your queries, you’re in the right place!
🔍 What Are Logical Operators in SQL?
Logical operators in SQL help us filter records by applying logic to the conditions in a query. They are essential when you want to retrieve data that satisfies multiple conditions.
Common Logical Operators in SQL:
- AND – Returns records that satisfy all specified conditions.
- OR – Returns records that satisfy at least one condition.
- NOT – Excludes records that meet a specified condition.
- BETWEEN, IN, LIKE – These also fall under logical filtering but aren’t boolean operators strictly.
📘 Why Logical Operators Matter in Analytics
Imagine you’re analyzing customer data, and you want to filter only those customers who:
- Have made a purchase in the last month AND
- Are located in New York OR California
Without logical operators, writing such conditional queries would be impossible. These operators bring in the power of decision-making to your SQL statements.
📌 The SQL WHERE Clause Revisited
Logical operators are primarily used inside the WHERE clause. Here’s a basic example:
SELECT * FROM customers
WHERE state = 'California' AND last_purchase_date > '2024-05-01';
🔗 Operator #1: AND
The AND operator ensures that all conditions in the WHERE clause must be true for a record to be included.
Retrieve employees who work in the ‘Sales’ department and earn more than $50,000.
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
🧠 How It Works
The query returns only those rows where both conditions are satisfied. If even one is false, the row is excluded.
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000 AND experience_years > 5;
⚖️ Truth Table for AND
| Condition A | Condition B | A AND B |
|---|---|---|
| TRUE | TRUE | TRUE ✅ |
| TRUE | FALSE | FALSE ❌ |
| FALSE | TRUE | FALSE ❌ |
| FALSE | FALSE | FALSE ❌ |
💡 Real-world Example
As a junior data analyst, your team may ask you to generate a report of all products that:
- Have inventory count less than 100 AND
- Were last restocked more than 30 days ago
You can use AND to solve this efficiently!
Stay tuned! In Part 2, we’ll dive into the OR operator and explore how combining conditions changes your data outcomes dramatically.
👉 Type “Yes” to get Part 2 of this blog.
