PostgreSQL LIKE Operator



PostgreSQL LIKE Operator

The PostgreSQL LIKE operator is used to match a string against a pattern using wildcard characters. This operator is essential for pattern matching and text searching tasks.


Syntax

string LIKE pattern

The LIKE operator has the following components:

  • string: The string to be matched.
  • pattern: The pattern to match against, which can include the following wildcard characters:
    • %: Matches any sequence of characters.
    • _: Matches any single character.

Example PostgreSQL LIKE Queries

Let's look at some examples of PostgreSQL LIKE operator queries:

1. Basic LIKE Example

SELECT 'Hello, World!' LIKE 'Hello%' AS result;

This query checks if the string 'Hello, World!' matches the pattern 'Hello%', which it does, so the result is true.

2. LIKE with Single Character Wildcard

SELECT 'Hello, World!' LIKE 'H_llo, World!' AS result;

This query checks if the string 'Hello, World!' matches the pattern 'H_llo, World!', which it does, so the result is true.

3. LIKE with Column Values

SELECT id, name, name LIKE 'A%' AS is_like
FROM users;

This query retrieves the id, name, and a boolean indicating whether the name matches the pattern 'A%' for each row in the users table.


Full Example

Let's go through a complete example that includes creating a table, inserting data, and using the LIKE operator to match patterns in text data.

Step 1: Creating a Table

This step involves creating a new table named users to store user data.

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT
);

In this example, we create a table named users with columns for id and name.

Step 2: Inserting Data into the Table

This step involves inserting some sample data into the users table.

INSERT INTO users (name)
VALUES ('Alice'),
       ('Bob'),
       ('Charlie');

Here, we insert data into the users table.

Step 3: Using the LIKE Operator

This step involves using the LIKE operator to match patterns in the text data in the users table.

-- Basic LIKE
SELECT 'Hello, World!' LIKE 'Hello%' AS result;

-- LIKE with Single Character Wildcard
SELECT 'Hello, World!' LIKE 'H_llo, World!' AS result;

-- LIKE with Column Values
SELECT id, name, name LIKE 'A%' AS is_like
FROM users;

These queries demonstrate how to use the LIKE operator to match patterns in the text data in the users table, including basic usage and handling column values.

Conclusion

The PostgreSQL LIKE operator is a fundamental tool for pattern matching and text searching by matching a string against a pattern using wildcard characters. Understanding how to use the LIKE operator and its syntax is essential for effective text data manipulation in PostgreSQL databases.