SQL Practice Logo

SQLPractice Online

Data Types & Type Conversion: Concept

Module: SQL Fundamentals

Data types define what values a column can store and how SQL processes them. Type conversion transforms data from one type to another — explicitly (you control it with CAST) or implicitly (the database does it automatically, often breaking your indexes and causing 100× slowdowns).

**Five Core Type Families**

**1. Numeric Types — Pick the right precision:**

| Type | Storage | Range | Use |

|------|---------|-------|-----|

| TINYINT | 1 byte | 0–255 | Flags, status codes |

| SMALLINT | 2 bytes | ±32K | Age, year |

| INTEGER / INT | 4 bytes | ±2.1B | IDs, counts |

| BIGINT | 8 bytes | ±9.2 quintillion | Large IDs, timestamps |

| DECIMAL(p,s) | Variable | Exact | Money, prices |

| FLOAT / REAL | 4–8 bytes | Approximate | Scientific data only |

**2. String Types — Length discipline matters:**

- CHAR(n): Fixed-length, always padded to n — fast for fixed codes (ISO codes, country codes)

- VARCHAR(n): Variable-length, up to n — workhorse for names, emails, descriptions

- TEXT: Unlimited — no index by default; use VARCHAR for indexed columns

**3. Date & Time Types:**

- DATE: 2024-01-15 (date only, 4 bytes)

- TIME: 14:30:00 (time only, 8 bytes)

- TIMESTAMP / DATETIME: Date + time without timezone (danger zone for global apps)

- TIMESTAMPTZ (PostgreSQL): Stored as UTC, converted on read — the global app standard

**4. Boolean Types (cross-DB):**

- PostgreSQL: BOOLEAN — TRUE / FALSE / NULL

- SQL Server: BIT — 1 / 0

- MySQL: TINYINT(1) — 1 / 0 (no native BOOLEAN)

- Oracle: No native boolean in SQL — use CHAR(1) 'Y'/'N' or NUMBER(1)

**5. JSON / Semi-Structured:**

- PostgreSQL JSONB: Binary storage, GIN indexable, path operators (@>, ->>)

- MySQL JSON: Validated on insert, JSON_EXTRACT() path

- SQL Server: NVARCHAR(MAX) + JSON functions (no native JSON type until 2025)

- Oracle: JSON type (21c+), JSON_VALUE(), JSON_EXISTS()

**Type Conversion: Explicit vs Implicit**

**Explicit (safe — you control it):**

```sql

CAST(value AS INTEGER) -- SQL standard, portable

CONVERT(INTEGER, value) -- SQL Server syntax

value::INTEGER -- PostgreSQL shorthand

TRY_CAST(value AS INTEGER) -- Returns NULL on error (SQL Server / Snowflake)

```

**Implicit (dangerous — database does it automatically):**

```sql