DEV Community

Malik M
Malik M

Posted on

Use of WHERE clause in PostgreSQL

In this tutorial, I will be explaining how can we return rows which satisfies a specific condition using WHERE clause.
SYNTAX of Postgres WHERE statement

SELECT list
FROM table_name
WHERE condition
Enter fullscreen mode Exit fullscreen mode

As from syntax it is clear that WHERE clause comes right after the FROM clause. The condition part of the WHERE clause returns the filtered rows from the SELECT statement. The condition must result to true, false or unknown. Either it can be a boolean expression or the combination of boolean expressions using different operators as OR or AND operators.

This query will return only the rows which satisfies the condition of WHERE clause.
Before looking into the example, To form the condition in the WHERE clause, we use comparison and logical operators:
Some of the operators we can use are:

Image description

Example
Let's see example of the WHERE clause with EQUAL, AND and OR operator.
Suppose we have the customer table with following attributes in the database:

Image description
*1. Using WHERE clause with the equal (=) operator *

SELECT
    last_name,
    first_name
FROM
    customer
WHERE
    first_name = 'Jamie';
Enter fullscreen mode Exit fullscreen mode

The above query returns the result as the customers which has first_name as Jamie.

OUTPUT
Image description

*2. Using WHERE clause with the AND operator *

SELECT
    last_name,
    first_name
FROM
    customer
WHERE
    first_name = 'Jamie' AND 
        last_name = 'Rice';
Enter fullscreen mode Exit fullscreen mode

The above query returns the customers whose first_name and last_name are Jamie and Rice.

OUTPUT

Image description

3. Using WHERE clause with OR operator:

SELECT
    first_name,
    last_name
FROM
    customer
WHERE
    last_name = 'Rodriguez' OR 
    first_name = 'Adam';
Enter fullscreen mode Exit fullscreen mode

The above query returns the customers whose last_name is ROdriguez or the first_name is Adam.

OUTPUT

Image description

Conclusion
In this tutorial we learnt about the use of WHERE clause in PostreSQL. Also we learnt about how logical and comparison operators can be used in the WHERE clause.

Top comments (0)