PostgreSQL Logical Operators : AND, OR, NOT
Logical Operators
The AND, OR, and NOT keywords are PostgreSQL's Boolean operators. These keywords are mostly used to join or invert conditions in a SQL statement, specifically in the WHERE clause and the HAVING clause.
The truth table of AND, OR, NOT operators
The table explains the Boolean values returned for the AND, OR, and NOT keywords, with each possible value for a Boolean field (true, false, or NULL).
x | y | x AND y | x OR y | NOT x | NOT y |
---|---|---|---|---|---|
true | true | true | true | false | false |
true | false | false | true | false | true |
true | NULL | NULL | true | false | NULL |
false | false | false | false | true | true |
false | NULL | false | NULL | true | NULL |
NULL | NULL | NULL | NULL | NULL | NULL |
The sample table
![postgresql sample table employee example1](https://www.w3resource.com/w3r_images/pgsql-sample-table-employee.gif)
PostgreSQL AND operator example
If we want to display the list of employees with columns empno, emp_first_name, designame and salary from employee table whose deptno is 25 and belongs to the designation 'SALESMAN', the following SQL can be used.
SQL
Code:
SELECT empno,emp_first_name,designame,salary
FROM employee
WHERE deptno=25
AND designame='SALESMAN';
Output:
![postgresql logical operatro and example1](https://www.w3resource.com/w3r_images/postgresql-logical-operator-and-example1.gif)
PostgreSQL OR operator example
If we want to display the list of employees with columns empno, emp_first_name, designame, salary and deptno from employee table whose deptno is either 25 or 45, the following SQL can be used.
SQL
Code:
SELECT empno,emp_first_name,designame,salary
FROM employee
WHERE deptno=25
OR deptno=45;
Output:
![postgresql logical OR operator](https://www.w3resource.com/w3r_images/postgresql-logical-operator-or-example1.gif)
PostgreSQL NOT operator example
If we want to display the list of employees with columns empno, emp_first_name, designame, salary and deptno from employee table who is not belonging into the deptno 25, the following SQL can be used.
SQL
Code:
SELECT empno,emp_first_name,designame,salary,deptno
FROM employee
WHERE NOT deptno=25;
Output:
![postgresql logical NOT operator](https://www.w3resource.com/w3r_images/postgresql-logical-operator-not-example1.gif)
PostgreSQL NOT, AND operator example
If we want to display the list of employees with columns empno, emp_first_name, designame, salary and deptno from employee table who is not belonging into the deptno 25 and 15, the following SQL can be used.
SQL
Code:
SELECT empno,emp_first_name,designame,salary,deptno
FROM employee
WHERE NOT deptno=25
AND NOT deptno=15;
Output:
![postgresql logical not and operator](https://www.w3resource.com/w3r_images/postgresql-logical-operator-not-and-example.gif)
Previous: AVG
Next: Comparison Operators
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics