Calculating... until our next FREE Code-Along Session. Secure your spot now

Build Your First Web App Today

Your 14-Day Free Trial Is Waiting To Be Activated
GET INSTANT ACCESS READ MORE ABOUT FIVE

TO_CHAR in SQL: Date and Number Formatting

Ryan Forrester
Sep 30th, 2024
Blog

Understanding TO_CHAR Function

The TO_CHAR function in SQL is a versatile tool for converting dates, numbers, and other data types into formatted strings.

It’s particularly useful when you need to present data in a specific format or when working with date and time values. Let’s explore how to use TO_CHAR effectively in your SQL queries.



Basic Syntax and Usage

The basic syntax of the TO_CHAR function is:

TO_CHAR(value, format_mask)

Where value is the date, number, or other data type you want to convert, and format_mask is a string that specifies the desired output format.

Let’s start with a simple example:

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') AS formatted_date
FROM DUAL;

This query might return:

formatted_date
--------------
15-JUN-2023

Here, SYSDATE is converted to a string in the format “DD-MON-YYYY”.


Formatting Dates with TO_CHAR

TO_CHAR offers a wide range of format elements for dates. Here are some common ones:

  • YYYY: Four-digit year
  • MM: Two-digit month
  • MON: Abbreviated month name
  • DAY: Full name of the day
  • HH24: Hour in 24-hour format
  • MI: Minutes
  • SS: Seconds

Let’s see these in action:

SELECT
    TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS standard_format,
    TO_CHAR(SYSDATE, 'DAY, DD MON YYYY') AS long_date,
    TO_CHAR(SYSDATE, 'DY, DD Month YYYY, HH:MI:SS AM') AS custom_format
FROM DUAL;

This might return:

standard_format       long_date              custom_format
--------------------  ----------------------  --------------------------------
2023-06-15 14:30:00   THURSDAY, 15 JUN 2023   THU, 15 June 2023, 02:30:00 PM

Working with Different Time Zones

TO_CHAR can also handle time zones:

SELECT
    TO_CHAR(SYSTIMESTAMP, 'YYYY-MM-DD HH24:MI:SS TZR') AS with_timezone,
    TO_CHAR(SYSTIMESTAMP, 'YYYY-MM-DD HH24:MI:SS TZD') AS with_timezone_name
FROM DUAL;

Output:

with_timezone              with_timezone_name
-------------------------  -----------------------------
2023-06-15 14:30:00 +01:00  2023-06-15 14:30:00 BST

Formatting Numbers with TO_CHAR

TO_CHAR isn’t just for dates; it’s also great for formatting numbers. Here are some useful format elements:

  • 9: Represents a digit
  • 0: Forces a leading or trailing zero
  • .: Decimal point
  • ,: Thousands separator
  • $: Dollar sign
  • L: Local currency symbol

Let’s see these in action:

SELECT
    TO_CHAR(1234567.89, '999,999,999.99') AS formatted_number,
    TO_CHAR(1234567.89, '$999,999,999.99') AS with_dollar,
    TO_CHAR(1234567.89, 'L999,999,999.99') AS with_local_currency
FROM DUAL;

This might return:

formatted_number   with_dollar        with_local_currency
-----------------  ------------------  --------------------
  1,234,567.89      $1,234,567.89       £1,234,567.89

Handling Different Locales

TO_CHAR can adapt to different locales. Here’s how you might format a date in French:

ALTER SESSION SET NLS_LANGUAGE = 'FRENCH';

SELECT TO_CHAR(SYSDATE, 'DAY, DD MONTH YYYY') AS french_date
FROM DUAL;

Output:

french_date
--------------------------------
JEUDI    , 15 JUIN      2023

TO_CHAR in SQL with a Rapid Database Builder

When working with SQL, executing efficient queries is straightforward, but sometimes more complex operations, like formatting and converting data types for specific outputs, require extra attention.

Rapid database builders like Five can greatly enhance your experience with SQL functions like TO_CHAR. Five provides a MySQL database for your application and generates an automatic UI, making it easier to interact with and manage your data, including formatted data.

Five allows you to create interactive forms, tables, dynamic charts, comprehensive PDF reports, and dashboards that are automatically generated based on your database schema. This makes it easier to visualize and analyze the results of queries.

Additionally, Five lets you write custom JavaScript and TypeScript functions, providing the flexibility to implement custom business logic that can interact with your data.

Once your application is ready, Five makes deployment easy with just a few clicks, allowing you to deploy your MySQL-based application to a secure, scalable cloud infrastructure. This lets you focus on developing, while Five handles the complexities of cloud deployment and infrastructure management.

If you’re serious about using SQL efficiently, give Five a try.

Sign up for free access to Five’s online development environment and start building your MySQL web application today.


Build Your Database In 3 Steps
Start Developing Today




Real-World Use Case: Sales Report

Let’s look at a practical example where TO_CHAR can be useful. Imagine you’re creating a sales report for an e-commerce platform:

CREATE TABLE sales (
    sale_id NUMBER PRIMARY KEY,
    sale_date DATE,
    amount NUMBER(10,2)
);

INSERT INTO sales VALUES (1, TO_DATE('2023-06-01', 'YYYY-MM-DD'), 1500.50);
INSERT INTO sales VALUES (2, TO_DATE('2023-06-15', 'YYYY-MM-DD'), 2750.75);
INSERT INTO sales VALUES (3, TO_DATE('2023-06-30', 'YYYY-MM-DD'), 3000.00);

SELECT
    sale_id,
    TO_CHAR(sale_date, 'DD-MON-YYYY') AS formatted_date,
    TO_CHAR(amount, '$9,999.99') AS formatted_amount
FROM sales
ORDER BY sale_date;

This query might return:

sale_id  formatted_date  formatted_amount
-------  --------------  ----------------
1        01-JUN-2023     $1,500.50
2        15-JUN-2023     $2,750.75
3        30-JUN-2023     $3,000.00

Advanced Usage: Custom Date Formats

Sometimes, you might need very specific date formats. TO_CHAR can handle these too:

SELECT
    TO_CHAR(SYSDATE, 'YYYY"年"MM"月"DD"日"') AS japanese_style_date,
    TO_CHAR(SYSDATE, 'DY "the" DDth "of" MONTH') AS verbose_date
FROM DUAL;

Output:

japanese_style_date  verbose_date
-------------------  ---------------------------
2023年06月15日        THU the 15th of JUNE

Handling NULL Values

When dealing with NULL values, TO_CHAR returns NULL. You can use NVL or COALESCE to provide a default value:

SELECT
    TO_CHAR(NULL, 'YYYY-MM-DD') AS null_date,
    NVL(TO_CHAR(NULL, 'YYYY-MM-DD'), 'N/A') AS handled_null_date
FROM DUAL;

Output:

null_date  handled_null_date
---------  ------------------
(null)     N/A

Performance Considerations

While TO_CHAR is incredibly useful, it’s important to be aware of its performance implications, especially when used on large datasets or in WHERE clauses.

Here’s an example of a potentially slow query:

SELECT *
FROM sales
WHERE TO_CHAR(sale_date, 'YYYY-MM-DD') = '2023-06-15';

This query prevents the use of an index on sale_date. A better approach would be:

SELECT *
FROM sales
WHERE sale_date = TO_DATE('2023-06-15', 'YYYY-MM-DD');

This allows the database to use an index on sale_date if one exists.


Common Pitfalls and How to Avoid Them

  1. Locale-Dependent Results: TO_CHAR results can vary based on NLS settings. Always specify the format explicitly if you need consistent results across different environments.
  2. Year Format: ‘YY’ for years can be ambiguous. Use ‘YYYY’ for four-digit years to avoid confusion.
  3. Performance in WHERE Clauses: As mentioned earlier, using TO_CHAR in WHERE clauses can lead to full table scans. Try to use date comparisons directly when possible.
  4. Padding with Spaces: TO_CHAR often pads results with spaces. Use TRIM if you need to remove these:
   SELECT TRIM(TO_CHAR(SYSDATE, 'Month')) AS trimmed_month
   FROM DUAL;
  1. Case Sensitivity: Format models are case-sensitive. ‘MM’ is not the same as ‘mm’.

Conclusion

The TO_CHAR function in SQL is a tool for formatting dates, numbers, and other data types. From basic date formatting to complex custom formats, it offers a wide range of possibilities for presenting data in a readable and consistent manner.

As you work with TO_CHAR, remember to consider performance implications, especially when dealing with large datasets or using it in WHERE clauses. Always test your queries with representative data volumes to ensure they perform well in production environments.

Whether you’re working on financial reports, log analysis, or any other data-intensive task, TO_CHAR can help you present your data in exactly the format you need.


Start developing your first application!

Get Started For Free Today

Sign Up Free Book a demo

Build Your Web App With Five

200+ Free Trials Started This Week

Start Free

Thank you for your message!

Our friendly staff will contact you shortly.

CLOSE