In Parts 1 through 4 of this series, we assumed our tables were already clean—aggregating numeric columns and joining normalized keys without friction. In real-world analytics and audit workflows, raw exports from Excel or CSV files rarely arrive that tidy: numbers contain commas or currency symbols, dates show up as MM/DD/YYYY text strings, and join keys carry trailing spaces or inconsistent casing.
Before running
SUM,GROUP BY, orJOINoperations on raw imports, you need to enforce strict data types, standardize timestamps, and sanitize text fields directly inside your query.
1. SQL Data Types & Explicit Type Casting
Every column in a relational database has an underlying storage type that dictates which functions can operate on it. While COUNT() works on any column, mathematical functions like SUM() and AVG() require the column to be stored as a numeric type—not merely look like numbers.
If an uploaded CSV contains commas ("1,250.50") or dollar signs ("$189.20"), most SQL engines fall back to storing that column as a text string (VARCHAR), causing arithmetic queries to fail.
Core SQL Storage Types
| Logical Category | Common SQL Type | Storage Rules & Precision | Typical Use Case |
|---|---|---|---|
| String | VARCHAR(n) / TEXT |
Variable-length character strings up to n characters |
Tickers, descriptions, raw unparsed dates |
| Whole Number | INTEGER / BIGINT |
Exact whole numbers with no decimal places | Share volume, row counts, IDs |
| Decimal / Float | NUMERIC(p,s) / DOUBLE PRECISION |
Exact fixed-point decimals (NUMERIC) or up to 15–17 significant digits (DOUBLE PRECISION) |
Stock prices, financial ratios, percentages |
| Date & Time | DATE / TIMESTAMP |
Calendar date (YYYY-MM-DD) or date + time (YYYY-MM-DD hh:mm:ss) |
Trade execution dates, filing timestamps |
| Boolean | BOOLEAN |
Strict TRUE or FALSE states |
Audit flags, active status indicators |
| Duration | INTERVAL |
Span of time resulting from date/timestamp subtraction | Holding period, time-to-settlement |
Changing Column Types with CAST and ::
When a numeric or date column is stored as text, convert it explicitly in your SELECT or WHERE clause. Most SQL dialects support two equivalent syntaxes:
- ANSI Standard:
CAST(column_name AS target_type)(portable across PostgreSQL, MySQL, BigQuery, Snowflake, and Impala) - PostgreSQL Shorthand:
column_name::target_type(concise and readable in complex transformations)
SELECT
symbol,
CAST(close_price_raw AS NUMERIC(10, 2)) AS close_price,
trade_volume_raw::BIGINT AS trade_volume,
trade_date_clean::DATE AS trade_date
FROM staging.aapl_raw_import;
Watch Out for Dirty Characters Before Casting: Calling
CAST('$1,420.00' AS NUMERIC)will throw a conversion error. Strip symbols and delimiters with string functions first, then cast the cleaned string to a numeric type.
2. Working with Dates & Times
Dates are the single most common source of silent bugs in SQL pipelines—especially when upstream spreadsheets localize dates into MM/DD/YYYY or DD-MM-YYYY text formats.
Why ISO 8601 (YYYY-MM-DD) Is Mandatory
When dates are stored as strings in MM-DD-YYYY or DD-MM-YYYY order, ORDER BY sorts alphabetically by month or day rather than chronologically (01-15-2026 comes before 12-31-2024).
Formatting dates as YYYY-MM-DD (ISO 8601) solves this completely: year-first strings sort in exact chronological order whether they are stored as VARCHAR or DATE.
-- Chronological sorting works reliably on ISO-formatted dates
SELECT
trade_date_iso,
close_price
FROM market.aapl_daily
ORDER BY trade_date_iso ASC;
Date Arithmetic & INTERVAL
Once columns are properly typed as DATE or TIMESTAMP, you can perform calendar arithmetic directly:
- Subtracting two timestamps produces an
INTERVALrepresenting the exact duration between them. - Adding or subtracting an
INTERVALshifts a date forward or backward using plain-English units ('7 days','1 week','6 months','1 year').
SELECT
company_name,
ipo_date::DATE AS ipo_date,
acquisition_date::DATE AS acquisition_date,
acquisition_date::DATE - ipo_date::DATE AS days_to_acquisition,
ipo_date::DATE + INTERVAL '1 year' AS one_year_anniversary,
NOW() - acquisition_date::TIMESTAMP AS time_since_acquisition
FROM market.tech_acquisitions
WHERE ipo_date IS NOT NULL;
Deconstructing & Bucketing Dates (EXTRACT and DATE_TRUNC)
For time-series reporting (weekly volume, monthly returns, or day-of-week seasonality), use EXTRACT to pull individual integer components and DATE_TRUNC to round timestamps down to the start of a calendar bucket:
SELECT
trade_timestamp,
-- Pull individual numeric components
EXTRACT('year' FROM trade_timestamp) AS trade_year,
EXTRACT('month' FROM trade_timestamp) AS trade_month,
EXTRACT('dow' FROM trade_timestamp) AS day_of_week, -- 0 = Sunday, 6 = Saturday
-- Round down to the first instant of the period for GROUP BY
DATE_TRUNC('week', trade_timestamp)::DATE AS week_start,
DATE_TRUNC('month', trade_timestamp)::DATE AS month_start
FROM market.aapl_intraday;
Current Time & Time Zone Normalization
Database servers typically run in UTC. When comparing live system timestamps (NOW(), CURRENT_DATE, CURRENT_TIMESTAMP) against local market hours, convert time zones explicitly with AT TIME ZONE:
SELECT
CURRENT_TIMESTAMP AS utc_now,
CURRENT_TIMESTAMP AT TIME ZONE 'America/New_York' AS nyse_local_time,
CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Jakarta' AS wib_local_time;
3. SQL String Functions for Data Cleaning
When raw fields arrive with wrapped parentheses, inconsistent capitalization, or embedded timestamps, combine SQL’s core string functions to isolate and standardize the exact text you need.
Slicing & Measuring: LEFT, RIGHT, SUBSTR, and LENGTH
LEFT(string, n)extracts the firstncharacters from the left.RIGHT(string, n)extracts the lastncharacters from the right.SUBSTR(string, start_pos, length)extracts a slice starting at a 1-based character index.LENGTH(string)returns total character count—useful for dynamicRIGHT()slicing when field lengths vary.
-- Example raw string: '2026-11-30 14:35:00.123456+00'
SELECT
raw_timestamp,
LEFT(raw_timestamp, 10) AS iso_date_part,
SUBSTR(raw_timestamp, 12, 8) AS time_part,
RIGHT(raw_timestamp, LENGTH(raw_timestamp) - 11) AS full_time_and_tz
FROM staging.trade_logs;
Stripping Wrapper Characters: TRIM
Beyond removing whitespace, TRIM can strip any specified characters from the LEADING (start), TRAILING (end), or BOTH sides of a string:
-- Strip outer parentheses from coordinate strings like '(-6.2088, 106.8456)'
SELECT
raw_coords,
TRIM(BOTH '()' FROM raw_coords) AS clean_coords
FROM staging.branch_locations;
Locating Delimiters: POSITION and STRPOS
When delimiters appear at variable positions (such as commas, hyphens, or @ symbols), locate their index dynamically. Both functions are case-sensitive and return 0 if the substring is not found:
SELECT
raw_coords,
POSITION(',' IN raw_coords) AS comma_idx_ansi,
STRPOS(raw_coords, ',') AS comma_idx_pg
FROM staging.branch_locations;
Combining & Normalizing Case: CONCAT, ||, UPPER, LOWER
Standardize text casing before grouping or joining so 'aapl', 'AAPL', and 'Aapl' map to a single key:
SELECT
UPPER(TRIM(ticker)) AS clean_ticker,
LOWER(TRIM(exchange_name)) AS clean_exchange,
CONCAT(UPPER(TRIM(ticker)), ' - ', exchange_name) AS label_concat,
UPPER(TRIM(ticker)) || ' (' || exchange_name || ')' AS label_pipe
FROM staging.watchlist;
Reconstructing Dirty Date Strings into True DATE Values
A classic data-wrangling pattern combines SUBSTR, LEFT, and || to rearrange an Excel-exported MM/DD/YYYY string into ISO YYYY-MM-DD, then casts it to a native DATE:
-- Converts '02/21/2026' (MM/DD/YYYY) -> '2026-02-21'::DATE
SELECT
raw_us_date,
(
SUBSTR(raw_us_date, 7, 4) || '-' ||
LEFT(raw_us_date, 2) || '-' ||
SUBSTR(raw_us_date, 4, 2)
)::DATE AS standardized_date
FROM staging.legacy_filings;
4. Handling Missing Values with COALESCE
NULL represents unknown or missing data—and in SQL, any arithmetic expression involving NULL evaluates to NULL (150.00 + NULL = NULL). After performing a LEFT JOIN (covered in Part 3 and Part 4), unmatched rows also introduce NULLs into your result set.
COALESCE(val_1, val_2, ..., fallback) evaluates its arguments in order and returns the first non-null value:
SELECT
d.trade_date,
d.ticker,
COALESCE(d.dividend_per_share, 0.00) AS dividend_amount,
COALESCE(m.sector_name, 'Unclassified Sector') AS sector
FROM market.aapl_daily d
LEFT JOIN market.company_metadata m
ON UPPER(TRIM(d.ticker)) = UPPER(TRIM(m.ticker));
5. Putting It Together: An End-to-End Cleaning CTE
In production queries, isolate all type casting, string cleanup, date parsing, and null-handling inside a dedicated staging CTE (cleaned_trades) before running aggregations or joins downstream:
WITH cleaned_trades AS (
SELECT
UPPER(TRIM(raw_ticker)) AS ticker,
(
SUBSTR(TRIM(raw_date), 7, 4) || '-' ||
LEFT(TRIM(raw_date), 2) || '-' ||
SUBSTR(TRIM(raw_date), 4, 2)
)::DATE AS trade_date,
REPLACE(TRIM(BOTH '$' FROM raw_price), ',', '')::NUMERIC(10, 2) AS close_price,
COALESCE(NULLIF(TRIM(raw_volume), '')::BIGINT, 0) AS volume
FROM staging.raw_stock_feed
WHERE raw_date IS NOT NULL
)
SELECT
ticker,
DATE_TRUNC('month', trade_date)::DATE AS trading_month,
COUNT(*) AS trading_days,
ROUND(AVG(close_price), 2) AS avg_close_price,
SUM(volume) AS total_monthly_volume
FROM cleaned_trades
GROUP BY 1, 2
ORDER BY ticker, trading_month;
Quick Reference Summary
| Cleaning Task | Primary SQL Function(s) | Example |
|---|---|---|
| Convert string to number/date | CAST(x AS type) / x::type |
'42'::INTEGER |
| Standardize text casing | UPPER(), LOWER() |
UPPER(TRIM(ticker)) |
| Strip spaces or wrapper symbols | TRIM(BOTH '...' FROM x) |
TRIM(BOTH '()' FROM coords) |
| Slice fixed-width text | LEFT(), RIGHT(), SUBSTR() |
SUBSTR(date_str, 7, 4) |
| Find delimiter position | POSITION(), STRPOS() |
STRPOS(email, '@') |
| Bucket dates by week/month/year | DATE_TRUNC('unit', ts) |
DATE_TRUNC('month', trade_date) |
| Shift dates forward or backward | INTERVAL |
trade_date + INTERVAL '7 days' |
Replace NULL with default value |
COALESCE(col, fallback) |
COALESCE(volume, 0) |
Read next
-
From Intermediate SQL
Intermediate SQL 4 : Advanced SQL Joins and UNION — WHERE vs. ON, Multi-Key Joins, Self Joins, and Stacking Tables: A Practical ReferenceReady to level up past basic joins? In this post, we untangle the subtle difference between filtering in WHERE vs. ON, use comparison operators and...
-
From Intermediate SQL
Intermediate SQL 3 : SQL Joins Explained — INNER, LEFT, RIGHT, and FULL OUTER: A Practical ReferenceTime to connect the dots across multiple tables! In this post, we break down how relational joins work under the hood and walk through INNER, LEFT,...
-
From Intermediate SQL
Intermediate SQL 2 : SQL Aggregate Functions and DISTINCT: A Practical ReferenceMoving from raw rows to real summaries! In this post, we break down COUNT, SUM, MIN, MAX, AVG, and DISTINCT using our Apple (AAPL) stock dataset—in...
-
From Intermediate SQL
Intermediate SQL 1 : Getting Started & The DatasetKicking off the Intermediate SQL series! Moving past basic SELECT queries, multiple ways to solve problems, and exploring the Apple stock dataset.
-
More Data Engineering
Introduction SparkLet’s learn how to use Spark with Python by using the pyspark library! Make sure to view the video lecture explaining Spark and RDDs before continu...
-
Reader favourite
Dota 2 Patch 7.42 : Item Potency, 15-Minute Tormentors, and Day 1 Meta ShiftsDota 2 Patch 7.42 kills passive high-ground stalling, nerfs spell burst, and adds Item Potency. Here is a full breakdown plus Day 1 pick and win ra...
-
Reader favourite
How to Research Anything (Even When You Have a Full-Time Job)You don't need a PhD or endless free time to do deep research. Here is a practical system to scope questions, filter sources, and actually finish w...
-
Reader favourite Predicting BBRI Stocks with Meta’s ProphetThe IHSG so shit recently not gonna lie/ Have you ever wondered how businesses predict future sales, how weather apps forecast the temperature, or ...
Leave a comment