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

Booleans and Casting

True, false, convert.

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

Postgres has a real boolean type, true or false. And it can convert values between types, using double colons. That's called casting.

  • true / false
  • Convert types
  • ::

Booleans and casts

Price over twenty is a boolean expression, so it gives true or false. Double colon integer turns the price into a whole number. And double colon text turns a number into text. Run it. True and false, and converted values.

query.sqlsql
SELECT title,
       price > 20      AS pricey,
       price::integer  AS rounded,
       stock::text || ' left' AS stock_note
FROM books
WHERE book_id IN (1, 9, 25);
Output
       title        | pricey | rounded | stock_note
--------------------+--------+---------+------------
 The Silent Orchard | f      |      15 | 58 left
 The Quiet Kitchen  | t      |      25 | 0 left
 The Glass Forest   | f      |      18 | 26 left
(3 rows)

Casting tips

Cast with double colons, or the standard cast function. Casting text to a number fails if the text isn't a number. Integer casts round to the nearest whole number. And booleans accept true, false, yes, no, one and zero.

keyvalue
::typePostgres style
CAST(x AS type)standard SQL
Bad textraises an error
Booleanstrue / false / yes / no

Summary

Booleans hold true or false, and double colons cast between types. Next, dates and times.

Key takeaways
  • boolean
  • ::
  • CAST
Next up: Dates and Times — date, time, timestamp