Imagine you’re working at a retail company, and you’ve been asked to analyze customer purchases to make informed decisions for marketing campaigns. You have access to a database with customer and sales information. SQL logical operators can help you effectively filter and analyze this data to answer specific questions.
AND Operator
Data analytics question: Which customers have made a purchase above $100 and reside in California?
Example query:
In this query, the AND operator is used to combine two conditions in the WHERE clause. In this case, it helps us find customers who have made a purchase above $100 (purchase_amount > 100) and reside in California (state = ‘California’). Both conditions must be true for a row to be included in the result set.
OR Operator
Data analytics question: Which customers have made a purchase above $500 or have made more than 10 purchases?
Example query:
In this query, the OR operator is used to include rows where either of the conditions is true. In this example, we’re looking for customers who have made a purchase above $500 (purchase_amount > 500) or have made more than 10 purchases (COUNT(sales.sale_id) > 10). If either condition is true, the results will include the row.
NOT Operator
Data analytics question: Which customers have not made a purchase in the last 30 days?
Example query:
In this query, the NOT operator is used to negate a condition. In this case, we’re looking for customers who have not made a purchase in the last 30 days. The subquery selects customer IDs with purchases in the last 30 days, and the NOT IN operator filters out those customers from the main query, leaving us with customers who haven’t made a purchase in that time frame.
These three logical operators (AND, OR, NOT) can be combined and used in various ways to help you effectively filter and analyze data to answer specific business questions in your data analysis tasks.