How to Get the Date from a String in SQL

How to Get the Date from a String in SQL

To extract the date from a string in SQL, use the STR_TO_DATE function.

This function takes two arguments: the string you want to convert and the format of the string. With this function, you can easily convert strings to dates in SQL.

For example, if you have a string in the format YYYY-MM-DD, you would use the following query:

SELECT STR_TO_DATE(string, '%Y-%m-%d') FROM table_name;

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called dates with the following data:

                                               
date_string
2020-01-01
2020-02-15
2020-03-31


If you wanted to convert these strings to dates, you would use the following query:

SELECT STR_TO_DATE(date_string, '%Y-%m-%d') FROM dates;

This query would return the result 2020-01-01, 2020-02-15, and 2020-03-31.

Additional Info

The STR_TO_DATE function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database.

Want to build your own LLM Apps with AirOps👇👇