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 Like
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 Like

By Priya PedamkarPriya Pedamkar

PostgreSQL Like

Introduction to PostgreSQL Like

Whenever you are dealing with string manipulation in PostgreSQL, it often needs to match the strings with a particular pattern and then perform some action and operation on the string if match successes are performed. This is one of the most common use-cases when it comes to string comparisons and manipulation. The traditional way to perform pattern matching that is used in SQL is by using the LIKE expression. Many other methods were introduced in PostgreSQL for pattern matching, such as POSIX regular expression matching and SIMILAR TO expressions that can also be used for pattern matching. This article will learn about the syntax of LIKE expression and how we can use it in PostgreSQL to perform pattern matching in strings.

Syntax of PostgreSQL Like

demoString LIKE anyPattern [ESCAPE characterThatNeedsToBeEscaped] demoString NOT LIKE anyPattern [ESCAPE characterThatNeedsToBeEscaped]

DemoString: It can be any string value or the column of the particular table that stores string and that you want to check whether matches a pattern or contains some characters or substring.

AnyPattern: The pattern is a particular string that you want to match with the demoString. It may contain the %(percentage) sign and _(underscore) sign that help in defining the pattern. The underscore sign mentions that any character might be present on that particular position of the pattern string, and % specifies the presence of one or more characters before or after or in-between the pattern string wherever it is being mentioned in the pattern string. We will discuss it in detail in the upcoming session and have examples to clarify the concept.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

CharacterThatNeedsToBeEscaped: Whenever you go for pattern matching, there are certain characters in the demoString that is the original string that you wish to skip while matching. These characters are called escape characters. By default, the backslash is considered to be an escape character that will be skipped while pattern matching. If you want to consider backslash in pattern matching, just specify double backslash as the escape character. You can specify any other character you want to skip in CharacterThatNeedsToBeEscaped parameter. This field is optional and has backslash as the default value.

Functions of PostgreSQL Like

When you use LIKE expression to match a certain string with the pattern, if the pattern matches, then true is returned; else, false is returned by the like expression. NOT LIKE expression behaves oppositely. It returns true when the string does match the pattern and false when the match is successful. demoString NOT LIKE anyPattern [ESCAPE characterThatNeedsToBeEscaped] is equivalent to NOT (LIKE anyPattern [ESCAPE characterThatNeedsToBeEscaped] ).

The pattern can be any string that you want to compare and contain underscore and percent signs to match multiple cases. When no such signs are mentioned in the pattern and are a plain string, then the Like behaves the same as that of an equal operator. When the underscore is there, then that position can be occupied by any other character in the original string to be matched. While the percent sign makes sure that there can be the presence of zero or more characters wherever it is mentioned. Let us study all these cases one by one.

Examples to Implement of PostgreSQL Like

Let us create one example and insert a few records in the table to learn how to use a LIKE expression for pattern matching. Open your PostgreSQL command-line prompt and enter the following command to create a table named educba:

Example #1

Query:

CREATE TABLE educba
(id INTEGER PRIMARY KEY,
technologies VARCHAR,
workforce INTEGER,
address VARCHAR);

Output:

PostgreSQL Like Example 1

Example #2

Let us insert some values in the educba table using the following statement:

Query:

INSERT INTO educba VALUES (1,'java',20,'satara'),(2,'javascript',30,'mumbai'),(3,'java',20,'satara'),(4,'psql',30,'mumbai'),(5,'mysql',20,'satara'),(6,'maven',30,'mumbai'),(7,'hibernate',20,'satara'),(8,'spring',30,'mumbai'),(9,'angular',20,'satara'),(10,'html',30,'mumbai'),(11,'css',20,'satara'),(12,'reddis',30,'mumbai');

Output:

PostgreSQL Like Example 2

Example #3

Let us create a simple select query statement to retrieve all the records from the educba table. Our query statement will be as follows.

Query:

SELECT * FROM educba;

Here, * represents all the columns to be retrieved and firing above query results in the following output:

Output:

educba table Example 3

Example #4 – String Matching a String

Let us take a pattern without any underscore or percent sign in it and match it with a LIKE expression.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,354 ratings)

Query:

SELECT technologies FROM educba WHERE technologies LIKE 'jav';

Output:

String Matching Example 4

As there is no record with a technologies column having jav value, it returns zero rows.

Example #5

Let us now fire the following query.

Query:

SELECT * FROM educba WHERE technologies LIKE 'java';

Output:

PostgreSQL Like Example 5

There are two records with java named technologies; hence two records are retrieved.

Example #6 – String Matching with _ in a Pattern

Now, we will retrieve all the records that will have underscore for the first position and then the string SQL for technologies column value. For this, we will fire the following query statement –

Query:

SELECT * FROM educba WHERE technologies LIKE '_sql';

that gives the following output: there is just one record with technologies value psql that matches the pattern.

Output:

String Matching Example 6

Example #7

Now, we will retrieve the records that have __ two underscores in the first and second position and then the string SQL using the following query statement.

Query:

SELECT * FROM educba WHERE technologies LIKE '__sql';

Output:

PostgreSQL Like Example 7

Only one record with MySQL technologies value is there that matches the pattern specified by us.

Example #8

Similarly, we can place underscore any number of times at any position we wish to build up our pattern. When we want to find records having technologies field value such that it contains one character previous and one character after the av substring, we will fire the query statement as follows –

Query:

SELECT * FROM educba WHERE technologies LIKE '_av_';

Output:

PostgreSQL Like Example 8

Example #9

Inserting one more _ in the above pattern gives the following query:

Query:

SELECT * FROM educba WHERE technologies LIKE '_av__';

Output:

PostgreSQL Like Example 9

Example #10 – String Matching with % in a Pattern

Suppose we want to retrieve all the records having string SQL in the ending and having any number of characters before it in the technologies field. Then we can make the use of the % sign that checks for zero or more character presence, and my query statement will be as follows:

Query:

SELECT * FROM educba WHERE technologies LIKE '%sql';

that results in the output containing psql as well as MySQL as there can be any number of characters before SQL string in the technologies field value.

String Matching Example 10

Example #11

Now, for retrieving records containing av in between the string and present anywhere in a technologies field value, we will have to mention % before and after av to search for substring av presence in an original string of technologies field value. Y query statement will be as follows.

Query:

SELECT * FROM educba WHERE technologies LIKE '%av%';

Output:

PostgreSQL Like Example 11

Conclusion

We can perform pattern matching using the LIKE expression in PostgreSQL to retrieve the records that match the particular pattern. Further, we can perform operations based on whether they match the pattern, such as splitting or replacing the original string’s substring.

Recommended Articles

This is a guide to PostgreSQL Like. Here we discuss the Introduction to PostgreSQL Like and its working along with practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. Introduction to PostgreSQL Timestamp
  2. How to Notify Works in PostgreSQL?
  3. PostgreSQL JSON (Examples)
  4. Introduction to PostgreSQL Timestamp
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
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

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

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

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

EDUCBA Login

Forgot Password?

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

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

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

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

Let’s Get Started

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