Filtering Text and Numeric Columns by Their Types

Comparison uses a column's type and declared rules. A string reading number digits can produce a different order or match from a numeric field.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a mistaken sort
  2. Choose a schema deliberately
  3. Compare visibly different orderings on concrete rows
  4. Validate before converting legacy values

Trace a mistaken sort

Text values 2 and 12 may sort with 12 earlier under common lexicographic rules. Numeric values order two earlier than twelve. See lexicographic and numeric order.

Choose a schema deliberately

An identifier with leading zeros can be text. A quantity used with thresholds should have numeric interpretation. Column types and domain rules describe that design boundary.[1]

Compare visibly different orderings on concrete rows

Text labels seven and twelve can sort as "12" before "7" under simple lexical ordering. Numeric values sort seven first. A where filter should use the comparison appropriate to the stored type and domain. See text versus numeric ordering.

Text labels "12","7" → lexical order 12,7
Integer values 12,7 → numeric order 7,12
If "007" is an identifier, parsing it as a number loses leading zeros

Validate before converting legacy values

One malformed text value can cause a numeric conversion query to fail. Plan cleaning and indexing appropriate to the database you use. Test leading zeros and nonnumeric text.

References

  1. PostgreSQL Global Development Group, Queries ↩