SQL.What is the difference between CHAR, VARCHAR, and TEXT, and when would you choose each?

Short answer (what to say first)

CHAR is fixed-length and space-padded, VARCHAR is variable-length with a limit, and TEXT is variable-length without a defined limit.
In practice, VARCHAR is the default choice, CHAR is for truly fixed-size values, and TEXT is for large or unbounded content.

1️⃣ CHAR(n)

What it is

  • Fixed-length string
  • Always uses n characters
  • Right-padded with spaces
CHAR(10)

Example

'abc' → 'abc       '

When to use

  • Truly fixed-size data:
    • ISO country codes (CHAR(2))
    • Fixed flags
    • Legacy schemas

Pros / Cons

✅ Predictable size
❌ Wastes space
❌ Easy to misuse

Interview note

CHAR rarely improves performance in modern DBs.

2️⃣ VARCHAR(n)

What it is

  • Variable-length string
  • Enforced maximum length
  • No padding
VARCHAR(255)

Example

'abc' → 'abc'

When to use (most cases)

  • Names
  • Emails
  • Codes with max length
  • API input validation at DB level

Pros / Cons

✅ No wasted space
✅ Length constraint protects data
❌ Slight length overhead (negligible)

Interview note

Default choice for application data.

3️⃣ TEXT

What it is

  • Variable-length
  • No declared limit (technically very large)
  • Stored like other varlena types in Postgres
TEXT

When to use

  • Long descriptions
  • JSON blobs (sometimes)
  • Logs
  • Comments / messages

Pros / Cons

✅ No artificial limit
❌ Harder to reason about size
❌ Sometimes discouraged in strict schemas

Interview note

TEXT and VARCHAR have similar performance in PostgreSQL.

TypeFixedMax lengthPaddingTypical use
CHAR(n)YesYesCountry codes, legacy
VARCHAR(n)YesNoMost app fields
TEXTNoNoLarge free text

5️⃣ Performance & indexing (important)

  • Postgres treats TEXT and VARCHAR almost identically
  • Index performance is the same
  • Length limit is a semantic constraint, not a performance one

Bad myth:

VARCHAR(255) is faster than TEXT

❌ False in Postgres.


6️⃣ When NOT to use each

❌ Don’t use CHAR(n) for names or emails
❌ Don’t use TEXT when business rules require a max length
❌ Don’t pick VARCHAR(255) blindly “because everyone does”


7️⃣ Interview-ready final answer (2–3 sentences)

CHAR is fixed-length and space-padded, suitable only for truly fixed-size values.
VARCHAR is variable-length with a maximum and is the default choice for most application fields.
TEXT has no declared limit and is used for large or unbounded content; in PostgreSQL it performs similarly to VARCHAR.”


Senior bonus insight ⭐

In well-designed schemas:

  • Length limits express business constraints
  • Not performance tuning
This entry was posted in Без рубрики. Bookmark the permalink.