SQL AND, OR, and NOT Operators
Credit:  Image by Freepik
The SQL AND
, OR
, and NOT
operators are used to combine multiple conditions in a WHERE clause for more complex queries. These operators allow you to filter records based on various criteria.
Demo Database Table: Customers
Let's consider a sample database table called "Customers" with the following structure:
CustomerID | CustomerName | City | PostalCode |
---|---|---|---|
1 | John Doe | New York | 10001 |
2 | Jane Smith | Los Angeles | 90001 |
Using the AND Operator
The AND
operator allows you to combine multiple conditions, and all conditions must be true for a record to be selected. Here's an example:
SELECT * FROM Customers WHERE City = 'New York' AND PostalCode = '10001';
This query retrieves all customers from the "Customers" table whose city is 'New York' and postal code is '10001'.
Using the OR Operator
The OR
operator allows you to combine multiple conditions, and at least one condition must be true for a record to be selected. Here's an example:
SELECT * FROM Customers WHERE City = 'New York' OR City = 'Los Angeles';
This query retrieves all customers from the "Customers" table whose city is either 'New York' or 'Los Angeles'.
Using the NOT Operator
The NOT
operator is used to negate a condition. It selects records that do not match the specified condition. Here's an example:
SELECT * FROM Customers WHERE NOT City = 'New York';
This query retrieves all customers from the "Customers" table whose city is not 'New York'.
Example: Combining Operators
You can combine multiple operators to create complex conditions. Here's an example:
SELECT * FROM Customers WHERE City = 'New York' AND (PostalCode = '10001' OR PostalCode = '10002');
This query retrieves all customers from the "Customers" table whose city is 'New York' and postal code is either '10001' or '10002'.
Database Table: Customers (100 Records)
Here's a demo database table with 100 customer records:
CustomerID | CustomerName | City | PostalCode |
---|
Use this table as a reference or replace it with your own data.
The SQL AND, OR, and NOT operators provide a flexible way to combine conditions and filter records based on various criteria. By understanding how to use these operators, you can construct complex queries to retrieve specific data from your database tables.
0 Comments