LTRIM And RTRIM Strip Any Set Character
Avoid prefix/suffix corruption from LTRIM and RTRIM treating arguments as character sets; strip literal prefixes and suffixes with REGEXP_REPLACE.
Code
WITH samples(url, filename) AS (
VALUES
('https://status.example.com', 'metrics.csv'),
('https://api.example.com', 'orders.csv')
)
SELECT
url,
-- LTRIM treats 'https://' as an unordered char set {h,t,p,s,:,/}, eating "st" from "status"!
LTRIM(url, 'https://') AS broken_ltrim,
-- RTRIM treats '.csv' as {.,c,s,v}, eating "cs" from "metrics"!
RTRIM(filename, '.csv') AS broken_rtrim,
-- Literal prefix and suffix removal via anchored regex or starts_with/substr
REGEXP_REPLACE(url, '^https://', '') AS safe_host,
REGEXP_REPLACE(filename, '\.csv$', '') AS safe_stem
FROM samples;Annotated execution — LTRIM And RTRIM Strip Any Set Character
The statement is SELECT, touching samples.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query.
Putting it to use
The samples table is the working surface here.
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.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.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 tables appear in this script?
- `samples`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.