AI Hints
Home›PostgreSQL Tutorial›Numbers, Text and Booleans
PostgreSQL · Lesson 11 of 120

Text Types

Text, varchar, char.

⏱ 2 min read▶ Video at 8:48🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

In Postgres, you can almost always just use text. It has no length limit, and it's just as fast as varchar. Let's see the useful text functions.

  • Just use text
  • No limit
  • Fast

Text functions

Double bars join text. Upper changes case. Length counts characters. And left takes the first few. Run it. Full names, shouted, measured and shortened.

query.sqlsql
SELECT first_name || ' ' || last_name AS full_name,
       upper(last_name)               AS shout,
       length(first_name)             AS letters,
       left(email, 6)                 AS start
FROM customers
LIMIT 3;
Output
  full_name  | shout  | letters | start
-------------+--------+---------+--------
 Tara Brown  | BROWN  |       4 | tara.b
 Grace Lopez | LOPEZ  |       5 |
 Finn Haddad | HADDAD |       4 | finn.h
(3 rows)

Text tips

Use text by default. Use varchar of n only when a real limit matters. Avoid char of n, which pads with spaces. And use a check constraint for rules like a minimum length.

keyvalue
textdefault choice
varchar(n)real limit only
char(n)avoid, pads
CHECKfor text rules

Summary

Use text for strings, and join and change them with functions. Next, booleans and casting.

Key takeaways
  • text
  • ||
  • Functions
Next up: Booleans and Casting — true, false, convert