w3resource

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

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

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

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

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

Previous: AVG
Next: Comparison Operators



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/postgresql-logical-operators.php