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.

SqlData Integrity

Code

snippet
-- 编号是数字但存成了 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

FAQ

What objects does the SQL involve?
`pallets` — referenced directly, no join needed.