Using to_tsquery for Full-Text Search in PostgreSQL
📖 Scenario: You are building a simple search feature for a library database. Users want to find books by searching for keywords in the book titles.
🎯 Goal: Create a PostgreSQL table to store book titles, then use to_tsquery to search for books matching specific search terms.
📋 What You'll Learn
Create a table called books with columns id (integer) and title (text).
Insert exactly three books with given titles.
Create a search query variable using to_tsquery with the term 'data & science'.
Write a SELECT query that uses to_tsquery to find books whose titles match the search query.
💡 Why This Matters
🌍 Real World
Full-text search is used in many applications like library catalogs, online stores, and document management systems to help users find relevant information quickly.
💼 Career
Knowing how to use PostgreSQL full-text search functions like to_tsquery and to_tsvector is valuable for database developers and backend engineers working on search features.
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 three rows exactly: (1, 'Data Science Handbook'), (2, 'Introduction to Databases'), (3, 'Science and Technology').
PostgreSQL
Hint
Use CREATE TABLE to define the table and INSERT INTO to add the rows.
2
Create a search query using to_tsquery
Create a variable called search_query that uses to_tsquery with the search term 'data & science'.
PostgreSQL
Hint
Use to_tsquery('data & science') to create the search query.
3
Write a SELECT query using to_tsquery to search titles
Write a SELECT query that returns id and title from books where the title matches the to_tsquery('data & science') search query. Use the to_tsvector function on title for matching.
PostgreSQL
Hint
Use to_tsvector(title) @@ to_tsquery('data & science') in the WHERE clause to filter matching rows.
4
Complete the search query with an alias
Modify the SELECT query to add an alias search_query for to_tsquery('data & science') in the SELECT list, and keep the WHERE clause filtering with the same to_tsquery.
PostgreSQL
Hint
Add to_tsquery('data & science') AS search_query to the SELECT list.
Practice
(1/5)
1. What does the to_tsquery function do in PostgreSQL?
easy
A. It converts search terms into a format for full-text search queries.
B. It creates a new table for storing search terms.
C. It updates text columns with search keywords.
D. It deletes rows that match search terms.
Solution
Step 1: Understand the purpose of to_tsquery
to_tsquery converts plain search words into a special query format that PostgreSQL can use for full-text searching.
Step 2: Compare options with the function's role
Only It converts search terms into a format for full-text search queries. correctly describes this conversion role. Other options describe unrelated database actions.
Final Answer:
It converts search terms into a format for full-text search queries. -> Option A
Quick Check:
to_tsquery = converts search terms [OK]
Hint: Remember: to_tsquery prepares search words for text search [OK]
Common Mistakes:
Thinking it creates or modifies tables
Confusing it with data update or delete operations
Assuming it returns raw text instead of a query format
2. Which of the following is the correct syntax to create a to_tsquery for searching the words 'cat' AND 'dog' using the explicit AND operator?
easy
A. to_tsquery('cat | dog')
B. to_tsquery('cat & dog')
C. to_tsquery('cat dog')
D. to_tsquery('cat && dog')
Solution
Step 1: Recall the AND operator in to_tsquery
The AND operator is represented by & in to_tsquery syntax.
Step 2: Match the correct syntax
to_tsquery('cat & dog') uses & correctly between 'cat' and 'dog'. to_tsquery('cat | dog') uses OR, C misses operator, and D uses invalid &&.
Final Answer:
to_tsquery('cat & dog') -> Option B
Quick Check:
AND = & in to_tsquery [OK]
Hint: Use & for AND, | for OR in to_tsquery strings [OK]
Common Mistakes:
Using spaces without operators to mean AND
Using double ampersands (&&) instead of single &
Confusing OR (|) with AND (&)
3. Given the query: SELECT to_tsquery('fast & !slow'); What is the expected output?
medium
A. 'fast' | !'slow'
B. Syntax error
C. 'fast' & !'slow'
D. 'fast slow'
Solution
Step 1: Understand the operators in the query
The query uses AND (&) between 'fast' and NOT (!) 'slow'. This means search for 'fast' but exclude 'slow'.
Step 2: Check the output format of to_tsquery
PostgreSQL returns the query as a string with words quoted and operators preserved. So output is 'fast' & !'slow'.
Final Answer:
'fast' & !'slow' -> Option C
Quick Check:
AND = & and NOT = ! in output [OK]
Hint: NOT is !, AND is & in to_tsquery output [OK]
Common Mistakes:
Confusing OR (|) with AND (&)
Expecting raw words without quotes
Thinking the query causes syntax error
4. Identify the error in this query: SELECT to_tsquery('apple & | orange');
medium
A. Syntax error due to consecutive operators & |
B. No error, valid query
C. Error because words must be uppercase
D. Error because to_tsquery needs two arguments
Solution
Step 1: Analyze the operator usage in the query string
The string has & | operators consecutively without a word between them, which is invalid syntax.
Step 2: Confirm PostgreSQL behavior
PostgreSQL will raise a syntax error because operators must separate valid search terms, not each other.
Final Answer:
Syntax error due to consecutive operators & | -> Option A
Quick Check:
Operators must separate words, not each other [OK]
Hint: Avoid placing operators consecutively without words [OK]
Common Mistakes:
Assuming multiple operators in a row are allowed
Thinking case of words matters
Believing to_tsquery requires multiple arguments
5. You want to search for documents containing the word 'run' but not 'running'. Which to_tsquery expression correctly achieves this?
hard
A. to_tsquery('run ! running')
B. to_tsquery('run | !running')
C. to_tsquery('run & !run')
D. to_tsquery('run & !running')
Solution
Step 1: Understand the requirement
You want documents that contain 'run' but exclude those that contain 'running'. This means AND 'run' and NOT 'running'.
Step 2: Choose the correct operator usage
AND is & and NOT is !. to_tsquery('run & !running') uses these correctly. to_tsquery('run | !running') uses OR which is wrong. to_tsquery('run & !run') excludes 'run' itself. to_tsquery('run ! running') has invalid syntax (missing operator between 'run' and '!').
Final Answer:
to_tsquery('run & !running') -> Option D
Quick Check:
AND = & and NOT = ! for correct filtering [OK]
Hint: Use & for AND, ! for NOT to exclude terms [OK]
Common Mistakes:
Using OR instead of AND for inclusion
Excluding the main word accidentally
Missing operators between words
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.