Logical Operators

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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

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

  1. SELECT empno,emp_first_name,designame,salary  
  2. FROM employee  
  3. WHERE deptno=25  
  4. AND designame='SALESMAN';  

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

  1. SELECT empno,emp_first_name,designame,salary  
  2. FROM employee  
  3. WHERE deptno=25  
  4. OR deptno=45;  

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

  1. SELECT empno,emp_first_name,designame,salary,deptno  
  2. FROM employee  
  3. WHERE  NOT deptno=25;  

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

  1. SELECT empno,emp_first_name,designame,salary,deptno  
  2. FROM employee  
  3. WHERE  NOT deptno=25  
  4. AND NOT deptno=15;