EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL WHERE Clause
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL WHERE Clause

By Sohel SayyadSohel Sayyad

PostgreSQL WHERE Clause

Introduction on PostgreSQL WHERE Clause

The PostgreSQL WHERE clause is used to control a query. The WHERE clause eliminates all rows from the output that do not meet the condition. It is generally used with SELECT, UPDATE and DELETE statements to filter the results. It returns the specific result only when the condition is satisfied. The WHERE clause specifies a condition while fetching data from a table or joining multiple tables. WHERE condition can be used with logical operators such as >, <, =, LIKE, NOT, OR, etc.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

WHERE search_conditions

Parameter:

Parameter Description
search_conditions A value expression. It returns a value of type boolean.

How does the WHERE clause work in PostgreSQL?

The condition must evaluate as true, false, or unknown. It can be a Boolean expression or a combination of Boolean expressions using AND and OR operators. The query returns the rows that satisfy the condition in the WHERE clause. In other words, only rows that cause the condition.

Check OR condition if one of the condition is null check like this:

WHERE {user_id} IS NULL OR sr.user_id = {user_id}

The WHERE clause evaluates as follow:

If the user_id is empty, then the WHERE clause evaluates to true; hence nothing filtered. If user_id is not empty, it checks the next OR condition.

Examples of PostgreSQL WHERE Clause

Let’s practice with some examples of using the WHERE clause with conditions. We will use the student table.

Create Table

Code:

CREATE TABLE student (
rollno int PRIMARY KEY,
firstname VARCHAR (50) NOT NULL,
lastname VARCHAR (50) NOT NULL,
branch VARCHAR (50) NOT NULL,
result boolean,
joining_date DATE NOT NULL
);

Insert data

Code:

INSERT INTO student (rollno, firstname, lastname, branch, result, joining_date)
values
('101', 'Oliver','Jake', 'Civil', false, '2020-06-01'),
('102', 'Jack','Connor', 'Civil', false, '2020-06-01'),
('103', 'Harry','Callum', 'Civil', false, '2020-06-01'),
('104', 'Jacob','John', 'Civil', false, '2020-06-01'),
('105', 'Thomas','David', 'Civil', false, '2020-06-01');
SELECT * FROM student;

Data available in the table:

PostgreSQL WHERE Clause

Example #1 – Equal (=) operator

If you want to get all students, whose first names are ‘Thomas.’

Code:

SELECT lastname, firstname
FROM student
WHERE firstname = 'Thomas';

Output:

PostgreSQL WHERE Clause

Example #2 – AND operator

The following example finds the student whose first name is Thomas and last names are David by using the AND logical operator to combine two Boolean expressions.

Code:

SELECT lastname, firstname
FROM student
WHERE firstname = 'Thomas' AND lastname = 'David';

Output:

PostgreSQL WHERE Clause

Example #3 – OR operator

This example finds the students whose ‘lastname’ is ‘David’ or ‘firstname’ is ‘Jacob’ by using the OR operator.

Code:

SELECT firstname, lastname
FROM student
WHERE lastname = 'David' OR firstname = 'Jacob';

Output:

PostgreSQL WHERE Clause

Example #4 – IN operator

If you want to match a string with any string in a list, you can use the IN operator. For example, the following statement returns students whose ‘firstname’ is ‘Oliver’, ‘Jack’, ‘Harry.’

Code:

SELECT firstname, lastname
FROM student
WHERE firstname IN ('Oliver', 'Jack', 'Harry');

Output:

PostgreSQL WHERE Clause

Example #5 – LIKE operator

To find a string that matches a specified pattern, you use the LIKE operator. The following examples return all students whose names start with the string ‘Ja.’

Code:

SELECT firstname, lastname
FROM student
WHERE firstname LIKE 'Ja%';

Output:

PostgreSQL WHERE Clause

The % is called a wildcard that matches any string. The ‘Ja%’ pattern matches any string that starts with ‘Ja’.

Example #6 – BETWEEN operator

The following example finds students whose first names start with the letter J and their lengths are between 3 and 5 by using the BETWEEN operator. Note that the BETWEEN operator returns true if a value is in a range of values.

Code:

SELECT firstname, LENGTH (firstname) namelength
FROM student
WHERE firstname LIKE 'J%' AND   LENGTH (firstname) BETWEEN 3 AND 5
ORDER BY namelength;

Output:

BETWEEN operator

In this example, we used the LENGTH () function returns the number of characters of the input string.

Example #7 – Not equal operator (<>) or (! =)

This example finds students whose first name starts with ‘Ja’ and the last name is notJohn.’

Code:

SELECT firstname, lastname
FROM student
WHERE firstname LIKE 'Ja%' AND lastname <> 'John';

Output:

Not equal operator (<>) or (! =)

Note that you can use != operator instead of <> operator. They have the same effect.

Example #8 – Combining AND & OR conditions

Execute the following query

Code:

SELECT *
FROM student
WHERE (lastname = 'David' AND firstname = 'Thomas') OR (rollno >= 103);

Output:

Combining AND & OR conditions

Example #9 – Joining Tables

Execute the following query

Code:

SELECT student.firstname, temp_student.result
FROM student
INNER JOIN temp_student
ON student.rollno = temp_student.rollno
WHERE student.firstname = 'Oliver';

Output:

Joining Tables

The above WHERE clause is used to join multiple tables together in a single SELECT statement. This SELECT statement would return all firstname and result values where there is a matching record in the student and temp_student tables based on rollno and where the firstname is ‘David’.

Conclusion

The PostgreSQL WHERE clause is used with SELECT, INSERT, UPDATE, or DELETE statement to filter rows. This article intends to introduce you to where clause in PostgreSQL.

Recommended Articles

This is a guide to PostgreSQL WHERE Clause. Here we discuss the introduction, How do the WHERE clause work in PostgreSQL and respective examples. You can also go through our other suggested articles to learn more–

  1. Python Magic Method
  2. Unix Operators
  3. PowerShell Set-Location
  4. Matlab AND Operator
  5. Matlab OR Operator | Working | Examples
  6. PostgreSQL Versions with Features
  7. Learn the PostgreSQL Architecture
  8. Complete Guide to Primary Key in SQL
  9. Indexes in PostgreSQL | How to Create?
Popular Course in this category
MS SQL Training (16 Courses, 11+ Projects)
  16 Online Courses |  11 Hands-on Projects |  70+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more