Ranking Search Results with ts_rank in PostgreSQL
📖 Scenario: You are building a simple search feature for a small library database. Users can search for books by keywords in the title and description. You want to rank the search results by how well they match the search terms.
🎯 Goal: Create a PostgreSQL table with book data, set up a full-text search vector, write a query that uses ts_rank to rank the books by relevance to a search query, and select the ranked results.
📋 What You'll Learn
Create a table called
books with columns id, title, and descriptionInsert 3 specific book records with given titles and descriptions
Add a column
search_vector that combines title and description for full-text searchWrite a query that uses
to_tsquery with the search term 'data & science'Use
ts_rank to rank the results by relevanceSelect
id, title, and the rank as rank ordered by rank descending💡 Why This Matters
🌍 Real World
Full-text search ranking is used in search engines, library catalogs, and any application where users search text data.
💼 Career
Knowing how to rank search results with ts_rank is valuable for database developers and backend engineers working with PostgreSQL.
Progress0 / 4 steps