Combining AND, OR and NOT operators together in sql

Combining AND, OR and NOT operators together in sql

Blog Bustle 16/03/2020

AND, OR and NOT operators are used in sql to filter sql query result with where clause. We can use these operators together to join conditions in single sql query. We can use these operators in select, update and delete query.

Combining AND, OR and NOT operators together example

Let's look some examples to understand use of AND, OR and NOT operators together in sql.

I have employee table.

id name city country
1 justin New york US
2 robin Binghamton US
3 jessie Nottingham England
4 chris Manchester England

1. find all records where country is US and city is New york or Binghamton.

SELECT * FROM employee
WHERE country = 'US' AND (city = 'New york' OR city = 'Binghamton');

id name city country
1 justin New york US
2 robin Binghamton US

2. find all records where city is not New york and Binghamton.

SELECT * FROM table_name
WHERE NOT city = 'New york' AND NOT city = 'Binghamton';

id name city country
3 jessie Nottingham England
4 chris Manchester England

3. find all records where country is not US and city is Nottingham and Manchester.

SELECT * FROM employee
WHERE NOT country = 'US' AND (city = 'Nottingham' OR city = 'Manchester');

id name city country
3 jessie Nottingham England
4 chris Manchester England

Remember that first select database then run any sql query related to that database otherwise you will get 'no database selected' error.

So we can easily understand and use AND, OR and NOT operators together in sql by above examples. Hope you like this tutorial.

Other important links

Sql NOT operator

Sql OR Operator

Sql AND Operator

Sql LIKE Operator

Combining AND, OR and NOT operators together in sql searches:

Tags: #mysql