w3resource logo


postgresql Logical Operators

PostgreSQL Logical Operators : AND, OR, NOT

rating Average rating 6 out of 10. Total 13 users rated.

<<PreviousNext>>

Description

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

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

SELECT empno,emp_first_name,designame,salary
FROM employee
WHERE deptno=25
AND designame='SALESMAN';
              

Output

postgresql logical operatro and example1

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

SELECT empno,emp_first_name,designame,salary
FROM employee
WHERE deptno=25
OR deptno=45;
              

Output

postgresql logical OR operator

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

SELECT empno,emp_first_name,designame,salary,deptno
FROM employee
WHERE  NOT deptno=25;
              

Output

postgresql logical NOT operator

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

SELECT empno,emp_first_name,designame,salary,deptno
FROM employee
WHERE  NOT deptno=25
AND NOT deptno=15;
              

Output

postgresql logical not and operator

photo credit: ykanazawa1999. Photo is used under creative Common License.



<<PreviousNext>>