Menu

SQL Date, String and Data Type Conversion Functions

SQL Date, String and Data Type Conversion Functions

Data often arrives messy. Dates are stored as text, names have stray spaces and odd capitalization, and numbers sit inside text columns. Until you fix these, sorting, filtering and math will give wrong answers.

Text dates are the classic trap. Sorted as text, '10-01' lands before '9-01', because the comparison goes character by character. Once converted to a real DATE, the order is correct and you can do date math as well.

Cleaning a Messy Table in One Query

Here is a raw_orders table where everything was imported as text.

customer_name

order_date_text

amount_text

riya sharma2026-03-151250.50
ARJUN MEHTA2026-03-18899.00
SELECT INITCAP(TRIM(customer_name))              AS customer_name,
       CAST(order_date_text AS DATE)             AS order_date,
       amount_text::NUMERIC(8,2)                 AS amount,
       EXTRACT(MONTH FROM CAST(order_date_text AS DATE)) AS order_month
FROM raw_orders;

Output:

customer_name

order_date

amount

order_month

Riya Sharma2026-03-151250.503
Arjun Mehta2026-03-18899.003

Code Explanation:

  • TRIM strips the extra spaces around Riya’s name.
  • INITCAP then capitalizes the first letter of each word and lowers the rest, so ARJUN MEHTA becomes Arjun Mehta.
  • CAST(... AS DATE) turns the text into a true date, and ::NUMERIC(8,2) is PostgreSQL’s shorter way to convert text into a decimal number.
  • EXTRACT(MONTH FROM ...) pulls the month number out of the converted date.

INITCAP exists in PostgreSQL but not in MySQL. In MySQL, you would build the same effect with UPPER and LOWER on parts of the string.

Functions Worth Knowing

Type

Function

What It Does

StringUPPER, LOWERChanges letter case
StringLENGTHCounts characters
StringSUBSTRINGCuts out part of a text value
StringREPLACESwaps one piece of text for another
StringCONCAT or ||Joins text values together
DateCURRENT_DATEReturns today’s date
DateNOW()Returns the current date and time
DateDATE_TRUNCRounds a date down to a month, year and so on
ConversionCASTChanges a value to another data type
ConversionTO_CHARFormats a date or number as text

Dates can be subtracted directly. In PostgreSQL, DATE '2026-03-18' - DATE '2026-03-15' gives 3, the number of days between them.


SQL for Data Science

AP

Abhishek Pati



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details