ts_headline Highlights Full-Text Matches
Build highlighted search snippets with ts_headline, websearch_to_tsquery, and custom StartSel and StopSel markers.
Code
CREATE TABLE articles (
id int PRIMARY KEY,
title text NOT NULL,
body text NOT NULL
);
INSERT INTO articles (id, title, body)
VALUES
(1, 'Indexing Postgres', 'A Postgres index speeds up lookups. Choose the index type carefully.'),
(2, 'Query Planning', 'The planner compares sequential scans with index scans.');
SELECT title,
ts_headline(
'english',
body,
websearch_to_tsquery('english', 'postgres index'),
'StartSel=<mark>, StopSel=</mark>, MaxWords=18, MinWords=8'
) AS snippet
FROM articles
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'postgres index');
-- Highlight every match instead of one fragment
SELECT ts_headline(
'english',
body,
websearch_to_tsquery('english', 'index'),
'HighlightAll=TRUE, StartSel=[, StopSel=]'
) AS full_highlight
FROM articles
WHERE id = 1;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with articles among the objects involved.
The SQL constructs in play: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The articles table is the working surface here.
Statements that matter
SELECT title,
ts_headline(
'english',
body,
websearch_to_tsquery('english', 'postgres index'),
'StartSel=<mark>, StopSel=</mark>, MaxWords=18, MinWords=8'
) AS snippet
FROM articles
WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'postgres index');
INSERT INTO articles (id, title, body)
VALUES
(1, 'Indexing Postgres', 'A Postgres index speeds up lookups. Choose the index type carefully.'),
(2, 'Query Planning', 'The planner compares sequential scans with index scans.');
SELECT ts_headline(
'english',
body,
websearch_to_tsquery('english', 'index'),
'HighlightAll=TRUE, StartSel=[, StopSel=]'
) AS full_highlight
FROM articles
WHERE id = 1;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which objects does the SQL touch?
- `articles`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.