Skip to main content
Module 6 · Lesson 4 of 424/57 in the course~12 min
Module lessons (4/4)

CAST and Type Conversions

Lesson preview5 hands-on exercises readySQL Course · Module 6 — Built-in Functions

Convert values explicitly between types with ::type and CAST(... AS ...).

What you'll learn in this lesson

  • Explicitly convert types using CAST(expr AS TIPO) and the expr::tipo shorthand.
  • Fix incorrect lexicographic sorting ('10' < '2') on numeric texts and concatenate numbers with ::text.
  • Prevent runtime crashes caused by dirty casts ('abc'::int) and understand rounding numeric::int.

Overview

SQL is strongly typed: each expression has a precise type (INTEGER, TEXT, NUMERIC, DATE, TIMESTAMP). When two operators don't match — or you want to change granularity or formatting — explicit casting comes into play.

Note in the stepper how casts into WHERE on the table column (ordered_at::date = ...) can slow down the use of indexes, while casts into the final SELECT or ORDER BY refine the output format:

Sections covered in this lesson

  1. 11. Mental Model: Cast Syntax and Behavior
  2. 22. Progressive & Annotated Examples
  3. 33. Interactive Laboratory: When to Apply Cast in the Query
  4. 44. Diagnostic Verification (Quiz)
  5. 55. Progressive Practical Laboratory
Pro Lesson · Module 6 — Built-in Functions

Unlock "CAST and Type Conversions" and the full SQL Course curriculum

Convert values explicitly between types with ::type and CAST(... AS ...).

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in SQL Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.