0
0
PostgreSQLquery~30 mins

SIMILAR TO for regex-lite matching in PostgreSQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Using SIMILAR TO for Simple Pattern Matching in PostgreSQL
📖 Scenario: You work at a bookstore database. You want to find books whose titles match simple patterns, like starting with certain letters or containing specific words.
🎯 Goal: Build a SQL query using SIMILAR TO to filter book titles by simple patterns.
📋 What You'll Learn
Create a table called books with columns id (integer) and title (text).
Insert exactly these three rows into books: (1, 'Learn SQL Basics'), (2, 'Advanced SQL Queries'), (3, 'SQL for Data Science').
Create a variable pattern with the value 'Learn%' to match titles starting with 'Learn'.
Write a SELECT query to get all columns from books where title SIMILAR TO pattern.
Add a final query to select titles matching a pattern that contains 'SQL' anywhere.
💡 Why This Matters
🌍 Real World
Filtering and searching text data in databases is common in many applications like bookstores, libraries, or content management systems.
💼 Career
Knowing how to use pattern matching in SQL helps database developers and analysts efficiently query and analyze text data.
Progress0 / 4 steps
1
Create the books table and insert data
Create a table called books with columns id as integer and title as text. Then insert these rows exactly: (1, 'Learn SQL Basics'), (2, 'Advanced SQL Queries'), and (3, 'SQL for Data Science').
PostgreSQL
Need a hint?

Use CREATE TABLE to define the table and INSERT INTO to add rows.

2
Define the pattern variable for matching titles starting with 'Learn'
Create a variable called pattern and set it to the string 'Learn%' to match titles starting with 'Learn'.
PostgreSQL
Need a hint?

Use \set pattern 'Learn%' in psql to define a variable.

3
Write a SELECT query using SIMILAR TO with the pattern variable
Write a SELECT query to get all columns from books where title SIMILAR TO :pattern using the variable pattern.
PostgreSQL
Need a hint?

Use WHERE title SIMILAR TO :pattern to filter rows.

4
Add a query to select titles containing 'SQL' anywhere using SIMILAR TO
Write a SELECT query to get all columns from books where title SIMILAR TO '%SQL%' to find titles containing 'SQL' anywhere.
PostgreSQL
Need a hint?

Use SIMILAR TO '%SQL%' to match titles containing 'SQL'.