Reading history

SQL CAST and Type Conversion

4 min read 0 views

Convert data types in SQL with CAST: avoid integer division, turn text into numbers, truncation versus rounding, typeof, and sorting numbers stored as text.

Why does 7 / 2 give 3 in SQL? Why do prices stored as text sort with 1200 before 15? Both problems come from data types. SQL sometimes converts types for you and sometimes does not, and the surprises cause wrong averages, wrong sorting and failed joins. This lesson shows how to convert types on purpose with CAST and how to avoid the common traps.

In this lesson you will learn

  • The CAST(value AS type) syntax
  • Integer division and how to avoid it
  • Converting text to numbers and numbers to text
  • Checking types with typeof
  • Sorting and comparing numbers stored as text

You should know SQL data types and math functions.

CAST and Integer Division

SELECT 7 / 2            AS int_division,
       7 / 2.0          AS real_division,
       CAST(7 AS REAL) / 2 AS cast_division,
       CAST('42' AS INTEGER) + 8 AS text_to_int,
       CAST(3.99 AS INTEGER)     AS truncated,
       ROUND(3.99)               AS rounded,
       CAST(2026 AS TEXT) || '-12' AS int_to_text;

SELECT typeof(42), typeof(4.2), typeof('42'), typeof(NULL), typeof(CAST('42' AS INTEGER));

Output

+--------------+---------------+---------------+-------------+-----------+---------+-------------+
| int_division | real_division | cast_division | text_to_int | truncated | rounded | int_to_text |
+--------------+---------------+---------------+-------------+-----------+---------+-------------+
| 3            | 3.5           | 3.5           | 50          | 3         | 4.0     | 2026-12     |
+--------------+---------------+---------------+-------------+-----------+---------+-------------+
(1 row)

+------------+-------------+--------------+--------------+-------------------------------+
| typeof(42) | typeof(4.2) | typeof('42') | typeof(NULL) | typeof(CAST('42' AS INTEGER)) |
+------------+-------------+--------------+--------------+-------------------------------+
| integer    | real        | text         | null         | integer                       |
+------------+-------------+--------------+--------------+-------------------------------+
(1 row)
  • When both numbers are integers, / does integer division and drops the fraction: 7 / 2 = 3. SQLite, PostgreSQL and SQL Server all do this; MySQL returns 3.5.
  • Making either side a decimal fixes it: 7 / 2.0 or CAST(7 AS REAL) / 2 both give 3.5.
  • CAST('42' AS INTEGER) turns text into a number so it can be added: 42 + 8 = 50.
  • CAST(3.99 AS INTEGER) truncates to 3; it does not round. Use ROUND when you want 4.
  • || joins text; casting 2026 to text first makes the intent clear.
  • typeof() is SQLite’s way to see what type a value really has.

Numbers Stored as Text

Data imported from spreadsheets or CSV files often arrives as text. It looks right but behaves wrongly.

-- Prices were imported as text: sorting goes wrong
CREATE TABLE products (name TEXT, price TEXT);
INSERT INTO products VALUES ('Pen','15'),('Bag','1200'),('Book','350'),('Ruler','8');

SELECT name, price FROM products ORDER BY price;                       -- text order
SELECT name, price FROM products ORDER BY CAST(price AS INTEGER);      -- number order

-- Average CGPA per department as a percentage of 4.0
SELECT dept,
       COUNT(cgpa) AS students,
       ROUND(AVG(cgpa) * 100 / 4, 1) AS pct_of_max
FROM students
GROUP BY dept
ORDER BY dept;

Output

+-------+-------+
| name  | price |
+-------+-------+
| Bag   | 1200  |
| Pen   | 15    |
| Book  | 350   |
| Ruler | 8     |
+-------+-------+
(4 rows)

+-------+-------+
| name  | price |
+-------+-------+
| Ruler | 8     |
| Pen   | 15    |
| Book  | 350   |
| Bag   | 1200  |
+-------+-------+
(4 rows)

+------+----------+------------+
| dept | students | pct_of_max |
+------+----------+------------+
| BBA  | 2        | 83.1       |
| CSE  | 3        | 95.3       |
| EEE  | 2        | 79.9       |
+------+----------+------------+
(3 rows)
  • Text sorts character by character, like a dictionary: “1200” comes before “15” because the second character 2 is less than 5.
  • ORDER BY CAST(price AS INTEGER) sorts by numeric value. The lasting fix is to store the column as a number.
  • In the last query, AVG(cgpa) * 100 / 4 is safe because cgpa is REAL, so the result keeps its decimals. CSE students average 95.3% of the maximum CGPA.

Common Target Types

TargetTypical namesUse
Whole numberINTEGER, INT, BIGINTCounts, IDs
DecimalREAL, DECIMAL(10,2), NUMERICPrices, averages; DECIMAL is exact for money
TextTEXT, VARCHAR(n)Joining with other text
DateDATE (PostgreSQL, MySQL); text in ISO form in SQLiteDate arithmetic

What happens with bad input differs. SQLite turns CAST('abc' AS INTEGER) into 0 without complaint, while PostgreSQL raises an error. Check data before converting it.

Common Mistakes

  1. Integer division in averages and percentages. SUM(a) / COUNT(*) on integers can lose the decimals; multiply by 1.0 first.
  2. Expecting CAST to round. It truncates toward zero.
  3. Joining an INTEGER column to a TEXT column. ‘7’ and 7 may not match; convert one side or fix the schema.
  4. Storing numbers as text “to be safe”. Sorting, totals and checks all become harder.

Practice Exercises

Exercise 1. Show each course’s share of all credits as a percentage with one decimal place.

Show answer
SELECT title, credits,
       ROUND(CAST(credits AS REAL) / (SELECT SUM(credits) FROM courses) * 100, 1) AS pct
FROM courses;

Total credits are 13, so Circuit Theory (4) is 30.8% and each 3-credit course is 23.1%. Without the cast, 3 / 13 would be 0.

Exercise 2. What do CAST(-2.7 AS INTEGER) and ROUND(-2.7) return?

Show answer

CAST truncates toward zero, giving −2. ROUND gives −3.0.

Frequently Asked Questions

What is the :: syntax I see in PostgreSQL?

price::integer is PostgreSQL’s short form of CAST(price AS integer). It does the same thing but does not work in other databases, so CAST is more portable.

What is implicit conversion?

It is when the database converts a type automatically, such as comparing the text ‘5’ with the number 5. Rules differ by database and can hide mistakes, so explicit CAST is clearer.

Summary

  • CAST(value AS type) converts a value on purpose.
  • Integer ÷ integer drops the fraction in most databases; use 2.0 or a cast.
  • CAST to INTEGER truncates; use ROUND to round.
  • Numbers stored as text sort wrongly; convert them or fix the column type.

Next: Cohort and Retention Analysis in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *