SQL FORMAT() Function

feature-41.jpg

While writing SQL queries, it is important to get the logic right behind that query because the readability and formatting make a significant difference while working on large queries. The queries that are well formatted are easier to understand, debug, and maintain. When your queries are well-organized, it is much easier to communicate your work with team members.

In this blog, we will discuss how to format SQL statements, the functions used for formatting data, and how you can make the data look better. So let’s start!

Table of Contents:

What is the FORMAT() Function in SQL Server?

There are two important aspects of formatting in SQL: First, format the code clearly, and second, format the result data that is returned by your queries. Both these aspects are equally important for writing efficient and professional SQL queries.

Formatting in SQL means arranging the statements by indenting them properly, using proper casing, and logical structure. This helps you to make your queries easy to understand. Also, formatting the output can be useful for focusing on how the data is presented. It helps you to generate reports, export data, and prepare information for the end-users. It presents the result in a readable and structured format so that it becomes easier for you to understand.

Syntax for FORMAT() function:

The syntax for the FORMAT() function is given below:

FORMAT(value, format, [culture])

where,

  • value: It refers to the number or date you want to format.
  • format: It refers to the string that is used to define the pattern of formatting. (e.g., ‘N2‘ is used for two decimal places, ‘yyyy-MM-dd‘ is used for the date format)
  • culture (optional): It is basically a locale code that is used to apply culture-specific formatting (e.g., ‘en-US‘, ‘de-DE‘).

Why Use the FORMAT() Function in SQL Server?

Below are a few reasons why it is important to format SQL code: 

  • Improves readability: A code that is well-structured is easier to understand, especially while you are dealing with complex or deeply nested logic. This helps you to go with the flow without getting confused.
  • Reduces Debugging Time: When your code is organized properly, it becomes easy for you to point out mistakes.
  • Ensures Consistency: To make your code look clean, you should apply proper casing, spacing, and naming to your SQL code. It also helps to avoid errors.
  • Enhances Maintainability: Formatting of SQL code allows you to make changes in the future without any effort.
  • Minimizes Need for Comments: When your  SQL code is clear, you do not need to depend on the comments. The structure of the code shows the logic of the query.
Start your SQL journey today
Enroll Now!
quiz-icon

How to Format Date and Time in SQL Server Using FORMAT()?

Handling date and time values is an important task while you are working with databases. It is important to have a good understanding of formatting date and time values in SQL because it will help you filter records by date, format dates for reports, and display timestamps in a readable format.

SQL consists of several built-in functions and formatting techniques for converting raw dates and time stamps into formats that can be easily understood by the user. This technique is called SQL date format or datetime formatting.

Why is Date and Time Formatting important in SQL?

  • It helps to present the results in a way that can be easily read by the user. 
  • Date and Time Formatting help you break a date into year, month, or day. This helps you to organize your search data more easily.
  • It can also be useful for showing dates in a format that is common in your country or specific to your application, like 06/06/2025 instead of 2025-06-06.
  • It can also be useful while you are preparing data for reports, dashboards, or exporting to Excel/CSV.

Comparison of SQL Date Format in Different Databases

Different functions are provided by different databases for date formatting. The most common ones are listed below in a tabular format:

Database Function Used
MySQL DATE_FORMAT()
SQL Server FORMAT() or CONVERT()
PostgreSQL TO_CHAR()

SQL Server DateTime Formatting Examples Using FORMAT()

Some examples regarding the implementation of Date and Time formatting in SQL Server are given below:

  1. Basic Date Formatting using FORMAT()

Example:

-- Step 1: Create a table with a DATE column
CREATE TABLE orders (
order_id INT,
customer_name VARCHAR(50),
order_date DATE
);

-- Step 2: Insert sample data
INSERT INTO orders (order_id, customer_name, order_date) VALUES
(1, 'C1', '2025-06-06'),
(2, 'C2', '2025-05-30');

-- Step 3: Format the order_date as DD-MM-YYYY using FORMAT()
SELECT
order_id,
customer_name,
FORMAT(order_date, 'dd-MM-yyyy') AS formatted_date
FROM
orders;

Output:

Basic Date sql Formatting using DATE_FORMAT()

Explanation:

The above SQL query is used to retrieve order details and then formats the order_date column into DD-MM-YYYY format. This is done using the DATE_FORMAT() function.

  1. Including Time with DATETIME

Example:

-- Step 1: Create the table with DATETIME column
CREATE TABLE logs (
log_id INT,
message VARCHAR(100),
log_time DATETIME
);

-- Step 2: Insert sample data
INSERT INTO logs (log_id, message, log_time) VALUES
(1, 'User logged in', '2025-06-06 09:15:30'),
(2, 'User logged out', '2025-06-06 17:45:00');

-- Step 3: Format datetime as DD/MM/YYYY HH:MM AM/PM
SELECT
log_id,
message,
FORMAT(log_time, 'dd/MM/yyyy hh:mm tt') AS formatted_log_time
FROM
logs;

Output:

Including Time with DATETIME for SQL formatting

Explanation:

The above query is used to retrieve the login and logout details and then formats the log_time column to display the date and time in the DD/MM/YYYY HH:MM:SS AM/PM format. This is done using the DATE_FORMAT() function.

  1. Extracting Date Parts in SQL

Sometimes, you might just need to extract the year, month, or day from a full date. The query to achieve that is given below:

Example:

-- Step 1: Create the 'orders' table with a DATE column
CREATE TABLE orders (
order_id INT,
customer_name VARCHAR(50),
order_date DATE
);

-- Step 2: Insert sample data into the 'orders' table
INSERT INTO orders (order_id, customer_name, order_date) VALUES
(1, 'C1', '2025-06-06'),
(2, 'C2', '2025-05-30');

-- Step 3: Extract the year, month, and day from the order_date
SELECT
order_id,
customer_name,
YEAR(order_date) AS order_year,
MONTH(order_date) AS order_month,
DAY(order_date) AS order_day
FROM
orders;

Output:

Extracting Date Parts in sql format function

Explanation:

The above query is used to retrieve order details and breaks the order_date into separate columns for year, month, and day by using the date functions in SQL.

Get 100% Hike!

Master Most in Demand Skills Now!

How to Format SQL Output Data Using Built-in Functions

While retrieving data from a database, raw values do not always appear in a user-friendly format. You have to restructure, format, or combine data by using various SQL functions. This helps you to improve the presentation of your code and also improve its readability.

Given below are some common formatting techniques that will help you to understand the concept better.

  1. Formatting Dates using FORMAT()

You can convert dates to a human-readable format like DD-MM-YYYY or include time as well.

Example:

-- Step 1: Create a table with a DATE column
CREATE TABLE orders (
order_id INT,
customer_name VARCHAR(50),
order_date DATE
);

-- Step 2: Insert sample data
INSERT INTO orders (order_id, customer_name, order_date) VALUES
(1, 'C1', '2025-06-06'),
(2, 'C2', '2025-05-30');

-- Step 3: Format order_date as DD-MM-YYYY
SELECT
order_id,
customer_name,
FORMAT(order_date, 'dd-MM-yyyy') AS formatted_date
FROM
orders;

Output:

Formatting Dates using DATE_FORMAT()

Explanation:

The above query is used to retrieve order details and then formats the order_date column. This helps to display dates in the DD-MM-YYYY format by using the FORMAT() function.

  1. Formatting Date and Time using DATETIME

You can also show the time in AM/PM format while working with DATETIME. The sample code is given below.

Example

-- Step 1: Create the logs table
CREATE TABLE logs (
log_id INT,
message VARCHAR(100),
log_time DATETIME
);

-- Step 2: Insert data
INSERT INTO logs (log_id, message, log_time) VALUES
(1, 'User logged in', '2025-06-06 09:15:30'),
(2, 'User logged out', '2025-06-06 17:45:00');

-- Step 3: Format datetime as DD/MM/YYYY HH:MM:SS AM/PM
SELECT
log_id,
message,
FORMAT(log_time, 'dd/MM/yyyy hh:mm:ss tt') AS formatted_log_time
FROM
logs;

Output:

Formatting Date and Time using DATETIME and using FORMAT() function in SQL

Explanation:

The above query is used to retrieve the login and logout details and then formats the log_time column to display the date and time in the DD/MM/YYYY HH:MM:SS AM/PM format. This is done using the DATE_FORMAT() function.

  1. Combining Strings with CONCAT()

Example:

-- Step 1: Create the table
CREATE TABLE employees (
emp_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50)
);

-- Step 2: Insert data
INSERT INTO employees VALUES
(1, 'FN1', 'LN1'),
(2, 'FN2', 'LN2');

-- Step 3: Combine the first and last names
SELECT
emp_id,
first_name + ' ' + last_name AS full_name
FROM
employees;

Output:

Combining Strings with CONCAT()

Explanation:

The above SQL query is used to create a table named employees. After that, you have to insert sample data and retrieve the employee ID of each of the employees along with their full name. You can do this by combining the first and last names by using the CONCAT function.

  1. Formatting numbers using the FORMAT() function in SQL Server

If you want to show numbers with commas, you can use the FORMAT() function.

Example:

-- At first, you have to create a sales table
CREATE TABLE sales (
    sale_id INT,
    amount DECIMAL(10,2)
);

-- Insert data
INSERT INTO sales VALUES
(1, 123456.789),
(2, 98765.4321);

-- After that, you have to format amount with 2 decimals and a comma separator
SELECT 
    sale_id,
    FORMAT(amount, 2) AS formatted_amount

FROM 
    sales;

Output:

Formatting numbers using the FORMAT() function

Explanation:

The above SQL query is used to create a table named sales. After that, data is inserted into it, and the sale ID is retrieved with the amount formatted to 2 decimal places. Commas are also used for better readability.

  1. Padding Numbers or Strings using RIGHT() and LEFT() combined with REPLICATE()

Example:

-- Step 1: Create the table with sample strings
CREATE TABLE sample_strings (
id INT,
val1 VARCHAR(10),
val2 VARCHAR(10)
);

-- Step 2: Insert data
INSERT INTO sample_strings (id, val1, val2) VALUES
(1, '123', 'AB'),
(2, '45', 'CD');

-- Step 3: Use padding logic to replicate LPAD and RPAD
SELECT
id,
-- Left pad val1 with zeros to make it 5 characters
RIGHT(REPLICATE('0', 5) + val1, 5) AS left_padded,

-- Right pad val2 with asterisks to make it 5 characters
LEFT(val2 + REPLICATE('*', 5), 5) AS right_padded
FROM
sample_strings;

Output:

Padding Numbers or Strings using LPAD() and RPAD()

Explanation:

The above SQL query is used to pad val1 on the left with zeros and pad val2 on the right with asterisks.

Using FORMAT() With Different Data Types in SQL Server

In SQL Server, the FORMAT() function helps you to format values like numbers, dates, and times in a particular string format. You can use this function when you need to present data in a format that can be easily read by humans. You can apply the FORMAT() function to different data types like DateTime, DECIMAL, and FLOAT, with the help of culture-based format strings (e.g., ‘en-US’ for U.S. English). You need to notice that the FORMAT() function returns an NVARCHAR result, which may not be ideal for further numeric calculations.

Example:

SELECT 
'Formatted Date: ' + FORMAT(GETDATE(), 'dddd, MMMM dd, yyyy', 'en-US') +
CHAR(13) + CHAR(10) +
'Formatted Currency: ' + FORMAT(CAST(1234567.89 AS MONEY), 'C', 'en-US') +
CHAR(13) + CHAR(10) +
'Formatted Percentage: ' + FORMAT(CAST(0.7564 AS FLOAT), 'P2') AS Output;

Output:

SQL format using different output

Explanation: The above SQL query is used to format and display the current date, currency value, and percentage. It uses the FORMAT() function for styling, and CHAR(13) + CHAR(10) to include line breaks so that all three values appear in one column.

Performance Impact of FORMAT() Function in SQL Server

1. High Overhead from .NET CLR Usage
FORMAT() is powered by .NET, making it slower than native SQL functions like CAST() and CONVERT(). It’s best avoided in heavy SQL formatting operations.

2. Increased CPU Consumption
Using the FORMAT() function in SQL on large datasets can spike CPU usage due to string rendering, especially when formatting currency or date format in SQL query outputs.

3. Reduced Query Scalability
Frequent use in SELECT statements or views can degrade performance in large-scale systems, limiting scalability when trying to format output data in SQL Server.

4. Slower Execution in Indexed Queries
Applying FORMAT() disables index usage, which leads to full table scans, this impacts read performance severely in reporting scenarios.

5. Poor Performance in Batch Jobs
Batch processes that use FORMAT() for transformation tasks (e.g., monthly invoices) run slower compared to using FORMAT vs CONVERT in SQL, especially at scale.

Numeric and Currency Formatting in SQL

While working with numeric data in SQL, it is important to format numbers to get better clarity and readability. That is why numeric and currency formatting is important in SQL. Some of the example use cases of Numeric and Currency Formatting are given below:

  1. Using the FORMAT() function

The FORMAT() function is used to format numbers as you wish.

Example:

-- Step 1: Create the sales table
CREATE TABLE sales (
sale_id INT,
amount DECIMAL(12, 4)
);

-- Step 2: Insert data
INSERT INTO sales VALUES
(1, 123456.789),
(2, 98765.4321);

-- Step 3: Format numbers with commas and 2 decimal places
SELECT
sale_id,
FORMAT(amount, 'N2') AS formatted_amount
FROM
sales;

Output:

Using the FORMAT() function

Explanation:

The above query is used to retrieve the ID of each sale. After that, it formats the amount with commas and 2 decimal places so that it becomes easier to read.

  1. Display Currency Symbols in SQL Output Using FORMAT() and CONCAT()

Although SQL doesn’t consist of built-in currency symbols in most databases, they can be concatenated manually.

Example:

-- Step 1: At first, you have to create the 'sales' table
CREATE TABLE sales (
    sale_id INT,
    amount DECIMAL(12, 2)

);

-- Step 2: After that, you have to insert sample data into the 'sales' table
INSERT INTO sales (sale_id, amount) VALUES
(1, 123456.78),
(2, 98765.43),
(3, 5000.00);

-- Step 3: After that, you have to write a query to format the amount as currency
SELECT 
    sale_id,
    CONCAT('$', FORMAT(amount, 2)) AS formatted_currency

FROM 
    sales;

Output:

Currency Symbol Formatting

Explanation:

The above query is used to store sales data. After that, it uses the CONCAT and FORMAT functions to show the amount field in a currency format.

  1. Round and Truncate Decimal Values in SQL Server

The ROUND() function can be used to round off numbers rather than formatting them.

Example:

-- Step 1: At first, you have to create the 'sales' table
CREATE TABLE sales (
    sale_id INT,
    amount DECIMAL(10, 3)
);

-- Step 2:After that, you have to insert sample data into the 'sales' table
INSERT INTO sales (sale_id, amount) VALUES
(1, 123.456),
(2, 98.765),
(3, 45.123);

-- Step 3: After that, you have to write the query to round the amount to 1 decimal place

SELECT 
    sale_id,
    ROUND(amount, 1) AS rounded_amount

FROM 
    sales;

Output:

Controlling Decimal Places

Explanation:

The above query shows the numeric formatting. It uses the ROUND() function, which helps in reporting and simplifying data presentation.

  1. Truncating Decimal

Example:

-- Step 1: Create the 'sales' table
CREATE TABLE sales (
sale_id INT,
amount DECIMAL(10, 4)
);

-- Step 2: Insert sample data
INSERT INTO sales (sale_id, amount) VALUES
(1, 123.4567),
(2, 98.7654),
(3, 45.1299);

-- Step 3: Truncate amount to 2 decimal places (no rounding)
SELECT
sale_id,
ROUND(amount, 2, 1) AS truncated_amount
FROM
sales;

Output:

Truncating Decimals

Explanation:

In the above query, the ROUND(amount, 2, 1) function is used in the SQL server to truncate the amount to 2 decimal places.

  1. Padding Numbers

Example:

-- Step 1: Create the 'sales' table
CREATE TABLE sales (
sale_id INT,
amount DECIMAL(10, 2)
);

-- Step 2: Insert sample data
INSERT INTO sales (sale_id, amount) VALUES
(1, 1500.50),
(23, 2399.99),
(456, 875.00);

-- Step 3: Pad sale_id to 5 digits with leading zeros
SELECT
sale_id,
RIGHT(REPLICATE('0', 5) + CAST(sale_id AS VARCHAR), 5) AS padded_id
FROM
sales;

Output:

Padding Numbers

Explanation:

The above query is used to pad each sale_id with leading zeros. This ensures that the output is 5 digits long using REPLICATE(), CAST(), and RIGHT().

FORMAT() vs CONVERT() vs CAST() – Which One to Use?

When to Use CAST() CONVERT() FORMAT()
Purpose – Use when converting between different SQL data types Use for simple, ANSI-SQL standard type conversions (e.g., int to varchar) Use for type conversions with formatting styles (e.g., date style codes) Use when you need to format output data in SQL Server for display
Localization & Culture – Need for culture-based formatting No support for localization Limited to predefined style formats Best for SQL formatting with full support for culture and localization
Syntax & Flexibility – Requirement for flexible formatting options Basic syntax with limited customization Supports style codes for certain types like datetime Accepts .NET-style format strings, great for FORMAT vs CONVERT in SQL use
Output – Whether a formatted string is needed or raw type conversion Returns converted value in specified type Returns converted value with optional format Always returns a string, ideal for SQL format function usage
Use Cases – Formatting, reporting, display, or integration output scenarios Use when writing portable queries across platforms Use for simple, ANSI-SQL standard-type conversions (e.g., int to varchar) Use for UI reports, currency display, padded numbers using FORMAT() function in SQL

Common Errors While Using FORMAT() in SQL Server and How to Fix Them

1. Using Invalid Format Strings
One of the most common mistakes developers make is using incorrect or non-.NET compliant format strings with the FORMAT() function in SQL. Unlike traditional SQL formatting functions, FORMAT() relies on .NET string formats. For example:

SELECT FORMAT(GETDATE(), 'DD-MM-YYYY') -- Incorrect

The correct version should be:

SELECT FORMAT(GETDATE(), 'dd-MM-yyyy') -- Correct

How to fix it: Refer to .NET formatting standards. Remember, ‘MM’ is for a month, ‘mm’ is for minutes, and ‘yyyy’ is for a year. If you’re using the FORMAT() function in SQL, ensure that you’re applying the correct format codes, especially when you work with date format in SQL query outputs.

2. Forgetting to Specify Culture When Needed
SQL developers often forget to include the culture parameter, which can lead to unexpected results, especially in applications dealing with international users. For example:

SELECT FORMAT(1234.56, 'C') -- Uses server's default culture

This could result in $1,234.56 in en-US, but something entirely different in another locale.
How to fix it: Always specify the culture if your application is intended for global audiences:

SELECT FORMAT(1234.56, 'C', 'fr-FR') -- Returns 1 234,56 €

Using culture settings helps you format output data in SQL Server reliably for different regions.

3. Applying FORMAT() on Unsupported Data Types
Not every SQL data type can be used with the FORMAT() function. It only works with data types that can be translated to .NET framework types such as numeric, date/time, or boolean. Trying to apply it on unsupported types (e.g., binary, image) will throw an error.

How to fix it: Before applying the function, ensure the column or value is cast to a compatible type. This is where understanding the difference between FORMAT vs CONVERT in SQL is essential—use CAST() or CONVERT() to prep the data if needed.

4. Overusing FORMAT() in Large Queries
Because the FORMAT() function in SQL Server uses the .NET CLR under the hood, it’s significantly slower than native functions like CAST() and CONVERT(). Using it excessively in large result sets or complex joins can drastically impact performance.

How to fix it: Use FORMAT() sparingly, especially in large data transformations. For basic conversions without the need for cultural or string-based formatting, rely on CAST() or CONVERT() for better performance and simpler SQL formatting needs.

5. Misunderstanding the Output Type of FORMAT()
FORMAT() always returns an NVARCHAR value, even if you format a number or date. This can break downstream logic expecting numeric or datetime types. For example:

SELECT FORMAT(SalesAmount, 'N2') + 100 -- Will cause an error

How to fix it: Always treat the result as a string. If you need to do math, use formatting after your calculations, not before. Knowing that FORMAT() is strictly for format output data in SQL Server, not for data computation, helps avoid such logic bugs.

SQL FORMAT() Function Use Cases in Real-World Scenarios

1. Regional Currency Formatting in Sales Reports
A global retail company generates monthly sales reports in SQL Server for different countries. Using the FORMAT() function, it displays currency values like $1,000.00 for US and €1.000,00 for Germany. This ensures accurate SQL formatting for financial data. It’s ideal for dashboards needing a culture-aware display. Stakeholders instantly recognize local monetary formats.

2. Custom Date Formats in HR Systems
An HR department tracks employee join dates and needs reports in different formats—dd/MM/yyyy for HR staff and MMMM dd, yyyy for management. The FORMAT() function in SQL helps apply these styles directly within queries. It avoids manual conversions or frontend adjustments. This is useful for date format in SQL query output consistency.

3. Invoice Number Padding for Accounting
A company needs invoice numbers in a fixed-width format like INV-000123. Instead of adding zeros manually, the SQL developer uses FORMAT() to zero-pad numbers. This simplifies formatting without complex string functions. It supports clean exports to PDFs and printed statements. Great for standardized document layouts using the SQL format function.

Start Learning SQL for Free
From Basics to Real-World Queries!
quiz-icon

Conclusion

It is important to master SQL output formatting because it will help you to create readable, understandable, and professional SQL queries. It involves formatting dates, numbers, and strings, and aligning outputs for reports. Application of these formatting techniques will help you to enhance the clarity of your data and also to streamline your data with both systems and users. Hence, it is important for you to develop this skill because it will help you to write efficient SQL queries and make your outputs more effective and user-friendly.

To learn more about SQL functions, check out this SQL Course and also explore SQL Interview Questions prepared by industry experts.

SQL Server FORMAT() Function- FAQs

Q1. How can formatting in SQL be improved by consistent indentation?

Straight and regular indentation makes it easy to distinguish the sections of your code from one another. This makes it easier to read SQL and debug.

Q2. Do I have to place each SQL clause on a new line?

Yes, since it will allow you to make your code simpler and better organized.

Q3. Is it better to use spaces or tabs for SQL formatting in SQL?

Yes, because they provide the same appearance across multiple editors.

Q4. How can formatting help while I am working with complex SQL queries?

Formatting is responsible for breaking down complex queries into simple parts. This makes the queries easier to understand.

Q5. Are there any industry standards for formatting in SQL?

No, but many people follow conventions like writing keywords in uppercase and aligning the clauses.

Q6. What does the FORMAT() function do in SQL Server?

It formats a value as a string using .NET style and optional culture settings.

Q7. How is FORMAT() different from CONVERT() and CAST() in SQL?

FORMAT() is for string display; CONVERT() and CAST() change data types.

Q8. Can I format currency using SQL FORMAT()?

Yes, use ‘C’ with locale like ‘en-IN’ to format currency.

Q9. Is FORMAT() available in MySQL or PostgreSQL?

No, but MySQL and PostgreSQL have their own format functions.

Q10. What is the difference between ROUND() and FORMAT() in SQL?

ROUND() controls numeric precision; FORMAT() affects string output format.

Q11. How to use FORMAT function in SQL Server?

Use FORMAT(value, format, culture) to convert values into formatted strings—e.g., SELECT FORMAT(GETDATE(), ‘dd-MM-yyyy’, ‘en-IN’) formats the current date.

About the Author

Data Engineer, Tata Steel Nederland

As a skilled Data Engineer, Sahil excels in SQL, NoSQL databases, Business Intelligence, and database management. He has contributed immensely to projects at companies like Bajaj and Tata. With a strong expertise in data engineering, he has architected numerous solutions for data pipelines, analytics, and software integration, driving insights and innovation.

business intelligence professional