websearch_to_tsquery User Query Parsing
Parse user-typed search strings with websearch_to_tsquery, which tolerates quoted phrases, OR, and -excluded terms without failing.
Code
-- websearch_to_tsquery parses user-typed input with forgiveness:
-- "quoted phrase" for phrases, OR for alternation, -word for exclusion; malformed input never raises
CREATE TABLE articles (
article_id int PRIMARY KEY,
title text NOT NULL,
search_vector tsvector NOT NULL
);
INSERT INTO articles VALUES
(1, 'Backup and restore', to_tsvector('english', 'Backup point in time restore for postgres clusters')),
(2, 'Deprecated backup guide', to_tsvector('english', 'Old backup procedure, deprecated in 2023')),
(3, 'Replication overview', to_tsvector('english', 'Streaming replication setup and failover'));
-- one input uses all three syntaxes: backup or replication, the phrase "point in time", and -deprecated as exclusion
SELECT article_id, title,
ts_rank(search_vector, websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')) AS rank
FROM articles
WHERE search_vector @@ websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')
ORDER BY rank DESC;How it works
SELECT / INSERT / CREATE statements share the script, touching articles.
Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Run the statement against the articles table.
Core lines
SELECT article_id, title,
ts_rank(search_vector, websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')) AS rank
FROM articles
WHERE search_vector @@ websearch_to_tsquery('english', 'backup or replication "point in time" -deprecated')
ORDER BY rank DESC;
CREATE TABLE articles (
article_id int PRIMARY KEY,
title text NOT NULL,
search_vector tsvector NOT NULL
);
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.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.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- Which tables does the SQL touch?
- `articles` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.