SQL TO_CHAR Function

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

TO_CHAR is a vital tool that converts DATE or DATETIME values into character strings based on specified date formats. Additionally, it transforms DATETIME or DATE values into LVARCHAR representations. When used with different data types such as DATE, TIMESTAMP, and INTERVAL, TO_CHAR produces a VARCHAR2 output according to specified formats. In case the format is skipped, the default conventions are applied like DATE follows the default date format, TIMESTAMP follows the default timestamp format, TIMESTAMP WITH LOCAL TIME ZONE uses the default timestamp format, and the Intervals are represented numerically.

Syntax

The Oracle/PLSQL TO_CHAR function syntax is as follows:

Parameters

The parameter values of the Oracle/PLSQL TO_CHAR function are as follows:

1. value:
The value parameter represents a numeric value or a date to be converted into a string.

2. format_mask:
This is an optional parameter that mentions the format to be applied during the conversion of 'value' to a string.

3. nls_language:
This is also an optional parameter that denotes the National Language Support language used in converting 'value' to a string.

The return value of a TO_CHAR function is a string value after the conversion process.

Functionality

The TO_CHAR function is widely used in SQL to convert various data types into character strings. This function is versatile and provides a powerful tool for formatting and presenting data in a human-readable form. It plays a crucial role in enhancing the readability and presentation of data in SQL queries.

Its flexibility in handling various data types and providing customizable formatting options makes it a handy tool for database professionals and developers. Whether dealing with dates, numbers, or custom strings, TO_CHAR helps to get the output according to specific requirements, improving the user experience.

Pros of TO_CHAR:

  • TO_CHAR is versatile and allows for flexible formatting of various data types, providing a wide range of options for customization.
  • It enhances the readability of output by converting dates, times, and numbers into user-friendly string representations.

Cons of TO_CHAR:

  • Applying TO_CHAR on large datasets may introduce performance overhead, as the conversion process can be resource-intensive.
  • Using TO_CHAR on indexed columns may hinder the database's ability to utilize indexes efficiently, leading to slower query performance.

When dealing with large datasets in performance-critical scenarios and utilizing the TO_CHAR function, it is crucial to carefully evaluate its impact on query performance. To mitigate potential drawbacks, consider adopting a selective approach by applying TO_CHAR only when necessary. Additionally, assess whether the performance trade-offs of using TO_CHAR on an indexed column outweigh its benefits. In certain scenarios, opting to perform the conversion after retrieving the data may lead to more efficient query execution.

Explore alternative methods such as using CAST or CONVERT functions instead of relying solely on TO_CHAR. Keep in mind that the performance characteristics of these alternatives may vary depending on the specific database system in use. Evaluating and choosing the most suitable function for the given context can contribute to optimizing overall query performance.

Examples

1. Data Type Conversion:

One of the primary functionalities of the TO_CHAR function is to convert different data types to character strings. This is particularly useful when you need to present data in a specific format.

Input:

Output:

In this example, the current timestamp is converted to a string in the YYYY-MM-DD HH:MI:SS format.

2. Date and Time Formatting:

TO_CHAR is commonly used for formatting date and time values. It allows users to represent dates and times in a variety of formats, such as 'DD-MON-YYYY' or 'HH AM'.

Input:

Output:

This query returns the order dates in a more readable DD-MON-YYYY format.

3. Number Formatting:

The TO_CHAR function helps users to format numbers with specific precision and thousands of separators while working with numeric data.

Input:

Output:

Here, the price column is formatted as a currency with two decimal places and a thousand separator.

4. Custom String Formatting:

TO_CHAR allows for custom string formatting, providing flexibility in presenting data as needed. Users can define their own patterns for string conversion.

Input:

Output:

This query formats the percentage values with two decimal places and includes a percentage symbol.

5. Handling NULL Values:

When applied to a NULL value, TO_CHAR handles NULL values gracefully. It returns a NULL result, ensuring consistent behavior in cases where data might be missing.

Input:

Output:

If the sale_date is NULL, the result will be NULL, preventing unexpected errors.

6. Localization:

The `TO_CHAR`` function often supports internationalization by allowing users to specify the language for formatting.

Input:

Output:

This query formats the order date in French.

7. Aggregate Functions with TO_CHAR:

TO_CHAR can also be used in combination with aggregate functions like GROUP BY to generate summarized and formatted results.

Input:

Here, TO_CHAR can be applied to the avg_price for custom formatting like this:

Output:

Next, let's see an example showing the use of the TO_CHAR function to convert an interval literal into a text literal.

Input:

Here, INTERVAL '123-2' YEAR(3) TO MONTH shows an interval literal denoting 123 years and 2 months. TO_CHAR is then applied to this interval literal, updating it into a text literal using a default format.

Output:

The output shows the interval in a formatted text representation. The + sign shows a positive duration, and the format follows the pattern YYYY-MM for years and months.

Let's explore a few more examples to enhance our understanding of converting different data types.

Input:

Output:

In this example, the TO_CHAR function is used to format it as MM/DD/YYYY.

Input:

Output:

The above example shows the time formatting in a 12-hour format.

Input:

Output:

In this example, we select a single date and a numeric value. Using the TO_CHAR function, we updated it to the default formatting of numeric value, its representation with commas, and its scientific notation.

Input:

Output:

In this example, we have a date and a numeric value, and the TO_CHAR function is used to represent the numeric value in its hexadecimal form.

The TO_CHAR function is often used with the TIMESTAMP WITH TIME ZONE data type to convert it into a string representation with a specified format. Here's an example:

Input:

Output:

output timestamp with time zone

The TO_CHAR function is then used to convert the 'event_timestamp' into a string representation with a specific format ('YYYY-MM-DD HH:MI TZR').

Conclusion

  • The TO_CHAR function helps in the conversion of various data types.
  • It enhances data readability with customizable formats, mainly useful for date, time, and numeric values.
  • It ensures consistent handling of NULL values, avoiding unexpected errors.
  • It also provides a localized user experience with the help of internationalization.