In SQL, we use the AND
and OR
clauses to write and combine multiple conditions. They are a crucial part of SQL when defining conditions to separate/filter the data we need from the remaining raw dataset.
These clauses are used along with standard SQL clauses, such as the WHERE
clause.
Using the code below, we can set up a sample data table.
-- Initialize a table named statesCREATE TABLE states(first_name varchar(255),state varchar(255),city varchar(255));-- Populate the table with sample dataINSERT INTO-- Table namestates-- Column names(first_name, state, city)-- Sample DataVALUES('Drake', 'California', 'Los Angeles'),('Josh', 'California', 'Los Angeles'),('Megan', 'Texas', 'Houston'),('Audrey', 'Texas', 'Dallas'),('Walter', 'Florida', 'Miami');-- Diplay the tableSELECT *FROM states;
When we run the code snippet above, we can see that we've successfully been able to declare and populate a table by the name of states.
AND
clauseSELECT *FROM statesWHERE state = 'California' AND first_name = 'Drake';
We've used the AND
clause to filter the data based on two conditions. The code above will return a table of people named Drake living in the state of California.
The AND
clause will only display records if all the stated conditions are successfully met.
OR
clauseSELECT *FROM statesWHERE state = 'Texas' OR state = 'Florida';
The code written above returns records matching either of the stated conditions. People currently living in the state of California or the state of Texas will show up in the output table.
Unlike the AND
clause, the OR
clause will display records that successfully meet any of the conditions stated.