Having and Where clause in PostgreSQL

Photo by Caspar Camille Rubin on Unsplash

This article explains the difference between the and clause in PostgreSQL . While they both have similar function, they both serve different purposes.

Where clause

A clause allows us to filter rows based on specific conditions. The filtering occurs before any groupings are made.

The conditions in the clause can be formed using comparison and logical operators such as the =, >, <, !=, & and | e.t.c

When we have a query with the clause, the execution takes place in this order . The clause is used to sort the query.

Additionally, when a column alias is used in the clause, that same alias cannot be used in the clause because of the order of execution mentioned above.

The syntax of a clause in a select query:

Here is an example of how a clause works. Assuming we have a table called “Employee table” as shown below;


To find all employees whose last name starts with an “ A” and have transactions above $3.00, we can use the below query:

The query above would return;

Having Clause

The clause is used with the clause to filter groups or aggregates based on specific conditions and it usually comes after the clause. The clause is similar to the clause except that it operates on groups. It is valid to say that is the for groups.

The execution of a query with the clause takes place in this order; .

In addition, you cannot use column aliases in the clause since it is evaluated before the availability of the column alias in the statement.

The syntax of a clause in a query is as follows;

Below is a sample usage of the clause using the below Employees table;

In the above table, we can see that an can occur multiple times for each time the employee makes a transaction.

To find all the employees who have done transactions with combined amount > $3.00, we can use the query below:

and would return;

Sample Having clause usage

Thanks for reading.

Data Analyst | BI Analyst | Tableau Expert.