by jeltz · 13y ago · 0 comments
The CHAR type is not what most people think it is. It is a blank padded string, not a fixed length one. Inserting 'a' into a CHAR(2) results in 'a ' being stored and retrieved from the database. You should always used VARCHAR or TEXT in PostgreSQL and never CHAR (at least I cannot think of a case when you would want it). CHAR is there for SQL standard compliance. Instead use one of these:
field VARCHAR(2) CHECK (length(field) = 2)
field VARCHAR CHECK (length(field) = 2)
field TEXT CHECK (length(field) = 2)
The rules for working with blank padded strings is in my personal experience a hell with non-obvious results when casting, sorting, comparing and other operations.EDIT: I can leave you with this little example.
$ SELECT length('ab '::char(4) || 'cd '::char(4));
length
--------
4
(1 row) CREATE DOMAIN currency_code ...If you care about semantics you should create a domain based on VARCHAR.
The CHECK constraint you illustrated earlier can just as well be placed on a CHAR (using trim() as well to adjust for padding). Then there's no chance of any blank padding issues either.
(which, fwiw, was written by someone who likely knows more than is healthy about RDBMS implementations of SQL)