Both MySQL and PostgreSQL offer tons of date and time functions, but the two SQL flavors differ in terms of syntax and functionality. In this blog post, we'll compare how these two popular databases engines handle common date/time operations, and note both the commonalities and differences.
Here's a quick table that summarizes the SQL syntax differences for getting the current Time/Date in MySQL vs. PostgreSQL:
Purpose | MySQL Syntax | PostgreSQL Syntax |
---|---|---|
Current timestamp | ||
Current date | ||
Current time | ||
Time zone aware | Limited support |
MySQL uses specific functions like and to calculate differences in dates or times. For example:
PostgreSQL achieves similar results using subtraction operators or the AGE() function for greater flexibility. For example:
MySQL provides dedicated functions like , , and to extract specific parts of a date. For example:
PostgreSQL uses the function, which offers more flexibility for retrieving date parts. For example:
Although I'm a HUGE PostgreSQL fan, I've got to admit – having be used is so awkward, since usually we use it when ing a certain table. Oh well, no person and no SQL flavor is perfect!
In MySQL, the and functions are used to add or subtract intervals. For example:
However, PostgreSQL makes the time interval math explicit, and allows using the and operators with INTERVAL:
Both MySQL and PostgreSQL have similar date/time formats. MySQL defaults to the YYYY-MM-DD format for dates and HH:MM:SS for time. PostgreSQL also defaults to YYYY-MM-DD and HH:MM:SS but provides the function for custom formatting.
MySQL uses the function for time zone conversions. For example:
PostgreSQL supports time zones natively with and the operator.
MySQL provides the function for calculating differences in specific units like days or months. For example:
PostgreSQL however uses the EXTRACT() function or simple arithmetic for similar calculations.
If you like the PostgreSQL syntax a lot more than MySQL – GOOD. I'm team PostgreSQL as well, and created a more detailed lesson on PostgreSQL Date-Time Functions as part of my free PostgreSQL Tutorial.
It's one thing to memorize syntax – and totally another level to actually USE the MySQL/PostgreSQL date-time functions. Go practice these new commands on 200+ SQL interview Questions which you can practice for free on DataLemur:
Each SQL interview question on DataLemur has multiple hints to guide you, step-by-step solutions and best of all, there is an interactive coding environment so you can right online code up your SQL query and have it checked.
You can also practice company-specific practice SQL questions from tech companies like: