Fix Text Number Sorting With LPAD
Sort numeric codes stored as text correctly: LPAD adds leading zeros so lexicographic order matches numeric order, indexable as an expression.
Code
-- 编号是数字但存成了 text:字典序与数值序不一致
CREATE TABLE pallets (
code text PRIMARY KEY
);
INSERT INTO pallets VALUES ('9'), ('10'), ('100'), ('2'), ('27');
-- 直接排序:'10' 会排在 '2' 前面(逐字符比较)
SELECT code FROM pallets ORDER BY code;
-- lexicographic sorting breaks numeric text codes;LPAD 补前导零修正
SELECT LPAD(code, 4, '0') AS padded, code
FROM pallets
ORDER BY LPAD(code, 4, '0');
-- 排序高频时可直接建表达式索引(LPAD 是不可变函数,合法)
-- CREATE INDEX pallets_padded_idx ON pallets (LPAD(code, 4, '0'));How the snippet works
SELECT / INSERT / CREATE statements share the script, touching pallets.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the pallets table.
Statements that matter
SELECT LPAD(code, 4, '0') AS padded, code
FROM pallets
ORDER BY LPAD(code, 4, '0');
INSERT INTO pallets VALUES ('9'), ('10'), ('100'), ('2'), ('27');
CREATE TABLE pallets (
code text PRIMARY KEY
);
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.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
FAQ
- What objects does the SQL involve?
- `pallets` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.