Problems displaying this newsletter? View online.
SQL Server Central
Featured Contents
Question of the Day
The Voice of the DBA
 

Formatting Dates and Times: The SQL Dialect Divide

If you’ve ever had to format dates and times in SQL, you’ve probably come across one of the most jarring realities of working across platforms: every major RDBMS does it differently and sometimes confusingly.  What’s a TO_CHAR() in Oracle becomes FORMAT() or CONVERT() in SQL Server, and its sort of the same in PostgreSQL… but not exactly.

Let’s break down the two key players in date and time formatting and conversion, starting with Oracle, which are:

·      TO_CHAR

·      TO_DATE

Depending on the reason for the format, joins, etc., one of these are often used and how they compare across Oracle, SQL Server, and PostgreSQL will be different.

Oracle: The Source of TO_CHAR and TO_DATE

Oracle is where TO_CHAR and TO_DATE originated and where they’re used most heavily.  I remember being very frustrated while learning how to format and how often I'd discovery code that would convert, then convert again and convert back a third time as part of processes, wondering why no one checked the original format of dates, timestamps, etc.

• TO_CHAR(date, format) is used to format a date or timestamp to a string:

SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') FROM dual;

• TO_DATE(string, format) is used to convert a string into a DATE datatype:

SELECT TO_DATE('2025-07-07', 'YYYY-MM-DD') FROM dual;

Oracle does give rich control with hundreds of formatting tokens.  It supports multiple timestamp types (DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE), and a default option, which is often set by the code called in the PL/SQL.

SQL Server: CONVERT, FORMAT, and Implicit Magic

SQL Server doesn’t use TO_CHAR or TO_DATE, as these are functions built into Oracle. Instead, it gives you two formatting functions and plenty of implicit casting.  Some of this is considered helpful, some may consider it frustrating or even dangerous.

Formatting a date to string is efficient and simple, using CONVERT() and FORMAT():

• CONVERT() with style codes (fast but cryptic):

SELECT CONVERT(VARCHAR, GETDATE(), 120);  -- 'YYYY-MM-DD HH:MI:SS'

• FORMAT() (slow but readable and flexible):

SELECT FORMAT(GETDATE(), 'yyyy-MM-dd HH:mm:ss');

We are able to do converting (in most cases) of a string to a date (like TO_DATE):

• SQL Server does it implicitly in many cases:

SELECT CAST('2025-07-07' AS DATETIME);

• Or explicitly with CONVERT():

SELECT CONVERT(DATETIME, '2025-07-07', 120);

SQL Server is the most “magical” of the three, often guessing what you meant, which can cause regional or cultural format issues (e.g., MM/DD/YYYY vs. DD/MM/YYYY) unless you’re very specific.

PostgreSQL: Clean, Predictable, Familiar

PostgreSQL embraces the TO_CHAR and TO_DATE functions into it’s own platform, just like Oracle, but with a more concise, Linux-like sensibility.

• Format date to string:

SELECT TO_CHAR(NOW(), 'YYYY-MM-DD HH24:MI:SS');

• Convert string to date:

SELECT TO_DATE('2025-07-07', 'YYYY-MM-DD');

PostgreSQL also excels in interval handling and arithmetic, allowing you to perform clean operations like NOW() + INTERVAL '3 days', something which is trickier in SQL Server.

Function Mapping Across Platforms

Interesting enough, it's not just TO_CHAR or TO_DATE, but we also have a third, in the area of convert to string, which I've added into the below table.  It's an additional option available in the three platforms:

Intent Oracle SQL Server PostgreSQL
Format date → string TO_CHAR(date, format) FORMAT(date, format) or CONVERT() TO_CHAR(date, format)
Convert string → date TO_DATE(string, format) CAST(string AS DATETIME) or CONVERT() TO_DATE(string, format)
Stringify any value TO_CHAR(value) CAST(value AS VARCHAR) or FORMAT() TO_CHAR(value) or ::text

Definitely Know Your Dialect

The way SQL handles dates is a perfect reflection of its underlying design philosophy.  Each platform has its structure and flexibility, which goes hand-in-hand with the database platform:

• Oracle is strict, detailed, and expects you to be explicit.

• SQL Server is flexible to a fault, even leaning heavily on implicit behavior unless you opt into formatting.

• PostgreSQL strikes a nice balance, which is clean, powerful, and consistent.

For database professionals working across environments, understanding these differences is essential.  It’s not just for ensuring correct formatting, but for writing portable code, debugging date issues, and avoiding painful localization bugs. Mastering date/time conversions may not feel glamorous, but it’s one of the clearest signs of a seasoned engineer.

After all, it’s not the flashy queries that trip you up, but the datetime strings that won’t behave.

 

Peace out,

DBAKevlar

Join the debate, and respond to today's editorial on the forums

 
  Featured Contents
SQLServerCentral Article

Revolutionizing Efficiency: The Power of Custom Automation Software Development

sofiya khan from SQLServerCentral

With the ever-increasing pace of the digital era, companies are continuously looking for opportunities to enhance efficiency, cut costs, and optimize operations. The most viable way to accomplish these is through Custom Automation Software Development.

SQLServerCentral Article

SQL Server and AI: Integrating Machine Learning Services

AR from SQLServerCentral

Get a quick glimpse of using AI in SQL Server by implementing a machine learning system.

Blog Post

From the SQL Server Central Blogs - Measuring and Improving SQL Server Query Plan Cache Efficiency

SQLPals from Mission: SQL Homeostasis

Measuring and Improving SQL Server Query Plan Cache Efficiency

The query plan cache hit ratio in SQL Server indicates the percentage of queries that are executed...

Blog Post

From the SQL Server Central Blogs - Communicate to the Individual

K. Brian Kelley from Databases – Infrastructure – Security

I may think I'm trying to reach the crowd, but I'm really trying to reach each person within the crowd. The "crowd" doesn't actually exist.

Technical Article

Query Plan Regressions --

dbakevlar from SQLServerCentral

 

Architecting Power BI Solutions in Microsoft Fabric

Steve Jones - SSC Editor from SQLServerCentral

Business Intelligence (BI) tools like Power BI are used by a wide range of professionals, creating diverse and complex scenarios, and finding the right solution can be daunting, especially when multiple approaches exist for a single use case. The author distills his 17 years of experience on various data platform technologies in this book to walk you through various Power BI usage scenarios.

 

  Question of the Day

Today's question (by dbakevlar):

 

Query Plan Regressions --

For the Question of the day, I am going to go deep, but try to be more clear, as I feel like I didn't give enough info last time, leading folks to guess the wrong answer... :)

For today's question:  You’re troubleshooting a performance issue on a critical stored procedure. You notice that a previously efficient query now performs a full table scan instead of an index seek. Upon investigating, you find that an NVARCHAR parameter is being compared to a VARCHAR column in the WHERE clause. What is the most likely cause of the query plan regression?

Think you know the answer? Click here, and find out if you are right.

 

 

  Yesterday's Question of the Day (by dbakevlar)

Has the PK been used --

You're analyzing a query execution plan in SQL Server to determine whether the query optimizer chose to use a primary key index.

Which Dynamic Management View (DMV) would you use to verify the usage of the primary key in the plan?

Answer: sys.dm_exec_query_plan

Explanation:

To determine if a primary key was used in the execution plan, you must examine the actual or estimated plan XML, which can be retrieved using sys.dm_exec_query_plan. This DMV provides the full execution plan associated with a specific query hash or plan handle, where you can look for Index Seek or Index Scan operations tied to a primary key index.

  • A provides runtime I/O stats for indexes but doesn't show whether a primary key was used in the plan.

  • B contains aggregate query execution statistics but no plan details.

  • D tracks how often indexes are used but doesn’t show if a specific index was used in a particular plan.

Discuss this question and answer on the forums

 

 

 

Database Pros Who Need Your Help

Here's a few of the new posts today on the forums. To see more, visit the forums.


SQL Server 2019 - Administration
Each database having its own disk? - Good morning, Once again, I find myself Sr. DBA for a company.  As I review this latest environment, I see something interesting. I see one of the main production servers is configured a little differently than I've seen before.  I usually place my MDF files in a Data Directory and place LDFs on a Log […]
SQL Server 2019 - Development
Report Table/view or SP in SQL to handle various reports - I have an Access database with a SQL backend with tables, views, SP's. I have reports to run based on rptArea and I am currently using MSAccess vba but wondering if it's better to use a report table, view or SP to hold the report table criteria. For instance, sample vba code: if rptArea is […]
how to move all SP from one db to another db? - Hi everyone I have two db - one is test and other is archive.  In the test db I have SP that begin with "WIP" and "z".  WIP means work in progress and z means retired.  I want to move all SP that begin with "WIP" or "z" from test db to archive db.  Is […]
Analysis Services
the value of the effectiveusername xml for analysis property is not valid - I'm experiencing odd behaviour when using Analysis Services as a data source in Excel when sharing the file with other users, however it works successfully for me. The connection string is updated to include a user as this is an RLS feature to filter data accordingly: Provider=MSOLAP.8;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=TabularModel;Data Source=Server\Instance;MDX Compatibility=1;Safety Options=2;EffectiveUserName=Domain\FirstName.LastName;MDX Missing […]
the value of the effectiveusername xml for analysis property is not valid - I'm experiencing odd behaviour when using Analysis Services as a data source in Excel when sharing the file with other users, however it works successfully for me. The connection string is updated to include a user as this is an RLS feature to filter data accordingly: Provider=MSOLAP.8;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=TabularModel;Data Source=Server\Instance;MDX Compatibility=1;Safety Options=2;EffectiveUserName=Domain\FirstName.LastName;MDX Missing […]
Integration Services
Need Help to implement the De Duplication - Dear All, Good Day. I have a requirement to implement de-duplication on customer data in our policy system before loading it into the target, ensuring data is clean. I initially suggested using SSIS Fuzzy Lookup, but the client is not satisfied with this approach. Could you please suggest alternative methods or tools to implement de-duplication […]
Editorials
In Praise of Simplicity or The Power of Plain Language in a Buzzword World - Comments posted to this topic are about the item In Praise of Simplicity or The Power of Plain Language in a Buzzword World
The Mindset of a Database Administrator: A Love Letter to Risk Aversion - Comments posted to this topic are about the item The Mindset of a Database Administrator: A Love Letter to Risk Aversion
The Long Weekend - Comments posted to this topic are about the item The Long Weekend
Article Discussions by Author
How a Legacy Logic Choked SQL Server in a 30-Year-Old Factory - Comments posted to this topic are about the item How a Legacy Logic Choked SQL Server in a 30-Year-Old Factory, which is is not currently available on the site.
Has the PK been used -- - Comments posted to this topic are about the item Has the PK been used --, which is is not currently available on the site.
Has the PK been used -- - Comments posted to this topic are about the item Has the PK been used --
PostgreSQL Aggregate Functions - Comments posted to this topic are about the item PostgreSQL Aggregate Functions
Cloning Master Admin User Permissions in Amazon RDS for SQL Server with Fine-Grained Control - Comments posted to this topic are about the item Cloning Master Admin User Permissions in Amazon RDS for SQL Server with Fine-Grained Control
Unmasking CXPACKET and CXCONSUMER in SQL Server: What Your Execution Plan Isn’t Telling You - Comments posted to this topic are about the item Unmasking CXPACKET and CXCONSUMER in SQL Server: What Your Execution Plan Isn’t Telling You
 

 

RSS FeedTwitter

This email has been sent to newsletter@newslettercollector.com. To be removed from this list, please click here. If you have any problems leaving the list, please contact the webmaster@sqlservercentral.com. This newsletter was sent to you because you signed up at SQLServerCentral.com.
©2019 Redgate Software Ltd, Newnham House, Cambridge Business Park, Cambridge, CB4 0WZ, United Kingdom. All rights reserved.
webmaster@sqlservercentral.com

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -