Sub topic 1
Character types: text, varchar and char(n)
This chapter covers the three string column types in PostgreSQL, how NULL affects string expressions, the joining and case functions, and how character counts differ from byte counts.
Prerequisites
This chapter assumes you can write basic SELECT, WHERE and GROUP BY queries, know that a column can hold NULL, and can run queries in psql or another SQL client.
Choosing a character type
PostgreSQL offers three types for text:
| Type | Limit | Padding | When to use |
|---|---|---|---|
| `text` | None | No | Default choice for most strings |
| `varchar(n)` | Up to n characters | No | When a length rule must be enforced |
| `char(n)` | Exactly n characters | Pads with spaces | Rarely; fixed-width codes |
In PostgreSQL, text and varchar have the same performance. Use varchar(n) only when the limit is a real business rule.
How NULL behaves
The || operator returns NULL if any operand is NULL. The concat function skips NULL arguments.
SELECT 'a' || NULL AS with_operator,
concat('a', NULL, 'b') AS with_concat;This returns NULL and 'ab'.
Joining strings
concat_ws joins with a separator and skips NULL values without adding a separator.
SELECT concat_ws(', ', 'x', NULL, 'z') AS with_separator;This returns 'x, z'.
Characters versus bytes
char_length counts characters. octet_length counts bytes. In a UTF8 database, accented letters take more than one byte.
SELECT char_length('héllo') AS chars,
octet_length('héllo') AS bytes;This returns 5 characters and 6 bytes.
Changing case
upper and lower convert every letter. initcap capitalizes the first letter of each word.
SELECT upper('postgres') AS up,
lower('SQL') AS low,
initcap('hello world') AS title;This returns 'POSTGRES', 'sql' and 'Hello World'.
> Note: Functions in this chapter return NULL for NULL input, so check for NULL before relying on their output.
Exercise
Exercise
What does SELECT concat_ws('-', 'a', NULL, 'b') return, and why?
Show answer
It returns 'a-b'. concat_ws skips NULL arguments entirely, so no separator is added for the NULL value.