Module lessons (4/4)
CAST and Type Conversions
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 theexpr::tiposhorthand. - 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 roundingnumeric::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
- 11. Mental Model: Cast Syntax and Behavior
- 22. Progressive & Annotated Examples
- 33. Interactive Laboratory: When to Apply Cast in the Query
- 44. Diagnostic Verification (Quiz)
- 55. Progressive Practical Laboratory
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.