SQL:SQL Data Types and CAST Function with Examples
SQL•Type Casting

SQL Data Types and CAST Function with Examples

Learn SQL storage types and explicit type conversion using CAST(column AS type).

Syntax

SELECT CAST(string_col AS INTEGER) FROM table;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
CAST(expr AS type)FunctionConverts expression to target SQL type.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

CREATE TABLE raw_logs (
    id INTEGER PRIMARY KEY,
    event_name TEXT,
    response_code_text TEXT
);

INSERT INTO raw_logs VALUES
    (1, 'login', '200'),
    (2, 'upload', '201'),
    (3, 'auth_fail', '401');

-- Explicitly cast text column to INTEGER for numeric comparison
SELECT 
    event_name,
    CAST(response_code_text AS INTEGER) AS response_code
FROM raw_logs
WHERE CAST(response_code_text AS INTEGER) >= 400;
Expected Output:
event_name  response_code
----------  -------------
auth_fail   401          

How It Works: Step-by-Step

  • Lines 7-10: Stores HTTP status codes as text strings.
  • Lines 13-17: CASTs response_code_text to INTEGER for numeric filtering.

Key Concepts

  • CAST converts types explicitly across text, integer, and real types.

Common Mistake: Comparing numbers stored as TEXT using greater-than (> )

In text sorting, "100" is less than "20" (alphabetical comparison). Cast to INTEGER first.

❌ Incorrect
WHERE text_num > "20" // "100" < "20" alphabetically!
✅ Correct
WHERE CAST(text_num AS INTEGER) > 20

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler