Simple way to standardize varchar "dates" to single date format in SQL? - sql

I have a table in a postgres database with a varchar date column that mixes MM/DD/YY with MM/DD/YYYY data formats. For example:
1/17/89
1/28/2018
12/30/2006
10/1/17
I'd like all of the dates to follow a MM/DD/YYYY format:
1/17/1989
1/28/2018
12/30/2006
10/1/2017
I'm aware it's not a best practice for dates to be in a varchar field, but I did not create this table and I cannot change the data type. Is it possible to use SQL to make this kind of change to my table?
I'm aware of similar questions like this one, but this seems a bit more than what I'm looking for, and I can't seem to extract an answer from it that's appropriate for my issue.
This question seems closer to what I'm looking for, but again, I can't seem to implement the answer. How would it know which table and field to make changes to? (I'm a total SQL noob if you can't tell).

You can try to use this code:
SELECT to_char(to_date(my_date,'MM/DD/YY')::TIMESTAMP, 'MM/DD/YYYY') as new_varchar_date FROM my_table;
-- for update the actual values
UPDATE my_table SET my_date = to_char(to_date(my_date,'MM/DD/YY')::TIMESTAMP, 'MM/DD/YYYY');
At first you need to convert the varchar to date, then to timestamp and then to varchar again.
Result should look like:
01/17/1989
01/28/2018
12/30/2006
10/01/2017

Related

Convert YYYYMMDD to MM/DD/YYYY in Snowflake

I need help in figuring out the date conversion logic in Snowflake. The documentation isn't clear enough on this.
In SQL Server, I would try
SELECT CONVERT(DATE, '20200730', 101)
and it gives me '07/30/2020'.
If I try the following in Snowflake,
to_varchar('20200730'::date, 'mm/dd/yyyy')
it gives me '08/22/1970'. Why would it give an entire different date? Need help in getting the logic with the correct date.
The issue with what you are doing is that you are assuming that Snowflake is converting your string of '20200730'::DATE to 2020-07-03. It's not. You need to specify your input format of a date. So, 2 options based on your question being a bit vague:
If you have a string in a table and you wish to transform that into a date and then present it back as a formatted string:
SELECT TO_VARCHAR(TO_DATE('20200730','YYYYMMDD'),'MM/DD/YYYY');
--07/30/2020
If the field in the table is already a date, then you just need to apply the TO_VARCHAR() piece directly against that field.
Unlike SQL Server, Snowflake stores date fields in the same format regardless of what you provide it. You need to use the TO_VARCHAR in order to format that date in a different way...or ALTER SESSION SET DATE_OUTPUT_FORMAT will also work.
Try select to_varchar(TO_DATE( '20200730', 'YYYYMMDD' ), 'MM/DD/YYYY'); which produces 2020-07-30
You may need to refer to https://docs.snowflake.com/en/user-guide/date-time-input-output.html#timestamp-formats

Casting nvarchar to date with a formatting in SQL-Server

I'm using SQL Server Management Studio. There is one table in my database containing dates which are stored as nvarchar(255). I want to migrate the data of this table to a new table which I call Converted_Dates and store this data as date. Also, I want them all to be formatted like this YYYY-MM-DD
Currently the Dates table looks like this:
**Dates**
15/6/2011
16/6/2011
2013-03-30
2013-04-16
...
I want the new table to look like this:
**Converted_Dates**
2011-06-15
2011-06-16
2013-03-30
2013-04-16
...
I execute this query but formatting of dates remains the same, only the data type changes from nvarchar(255) to date.
USE [reporting_database]
GO
INSERT INTO [dbo].[Converted_Dates]
SELECT
cast(Dates as date)
FROM [dbo].[Dates]
GO
Any advice on how to cast the data from the old table to a new one in a preferred format?
The value of date and datetime data type is not stored with format in sql server. If you want to see the date in a different format you can manipulate the way that date and datetime data types are displayed when converted to a varchar (or nvarchar,nchar,char) data type using some built in functions.
You should store your dates as date data type, and if you can format them at the application level, do so there. If you must format them in sql, then use convert() styles.
select convert(char(10),getdate(),120)
returns: 2017-05-01
In sql server 2012+ you can use format()
select format(getdate(),'yyyy-MM-dd')
returns: 2017-05-01
But format() is much slower, take a look here: format() is nice and all, but… - Aaron Bertrand

How to convert an integer field into a date in Netezza?

i have an integer field which has date values but i would like to convert it as date field. I have tried several methods but with no success. The field has Date values but is stored as an Integer. This is what i have tried:
cast(MYFIELD AS DATE) AS MYCOLUMN
but i get this error "Cannot cast type INT4 to DATE".
I have done several research but coul not find good solution for netezza.
You can concatenate 01 and then run a to_date
select to_date(201004||'01','YYYYMMDD')
I don't think this is something that you can do, not in an obvious way at least. There are hundreds of ways a human could represent a date as an int, so the conversion would not be built in.an int would be something like 20120415 or 04152013 or hundreds of other formats and a date would be something like '2012-04-15'
I suggest you look at the top answer for How i can get the first 3 digits in 123456 Numbers in sql? and extract your data manually. what you should do though, is convert the field into a real date field and edit the dependencies to expect that format.

How to update dates stored as varying character formats (PL/SQL)?

Problem: I have a large database table (~500k records) which has a list of dates stored in a varchar2(15) column. These dates are stored in varying formats, ie. some are yyyy-mm-dd, some are mm/dd/yyyy, some are dd/mm/yy, some are mm/dd/yy, etc. Ie:
1994-01-13
01/13/1994
01/13/94
13/01/94
13/01/1994
etc
I need to be able to shift these dates slightly, for example to add 30 days to each date. (This is an oversimplification of my objective but it's easier to explain this way).
If all the dates were formatted consistently, I would achieve this as follows:
UPDATE history_table
SET some_date_col =
to_char(to_date(some_date_col, 'mm/dd/yyyy')+30, 'mm/dd/yyyy')
WHERE some_date_col IS NOT NULL;
Due to the size of the database, I cannot afford to loop through the values one by one and parse the date value. Can anyone suggest a means to accomplish this without loops, ie with a mass UPDATE statement?
Are the formats of these dates really that important? They should be datetime columns. Then you could just use date math functions on that field.
well, you've got a real problem here.
07/07/1994 is valid for 'MM/DD/YYYY' and 'DD/MM/YYYY'
However, outside of that issue, you can try nesting decodes.
I entered the following dates into a varchar field:
01/12/2009, 01-12-2009, 2009-01-12, 01/12/09
and using the below, I was consistently returned 1/12/2009. You'll have to figure out all the patterns possible and keep nesting decodes. The other thing you could do is create a function to handle this. Within the function, you can check with a little more detail as to the format of the date. It will also be easier to read. You can use the function in your update statement so that should be faster than looping through, as you mentioned.
(for what its worth, looping through 500k rows like this shouldn't take very long. I regularly have to update row by row tables of 12 million records)
select mydate,
decode(instr(mydate,'-'),5,to_date(mydate,'YYYY-MM-DD'),3,to_date(mydate,'MM-DD-YYYY'),
decode (length(mydate),8,to_date(mydate,'MM/DD/YY'),10,to_date(mydate,'MM/DD/YYYY')))
from mydates;
and here is the update statement:
update mydates set revdate = decode(instr(mydate,'-'),5,to_date(mydate,'YYYY-MM-DD'),3,to_date(mydate,'MM-DD-YYYY'),
decode (length(mydate),8,to_date(mydate,'MM/DD/YY'),10,to_date(mydate,'MM/DD/YYYY')))
IMHO, you have a bigger problem:
If some dates are dd/mm/yyyy and some are mm/dd/yyyy how can you difference which format applies for certain date?
for example, how can I know if a value "12/09/2008" means December or September?

SQL date format issue in select query

I have an ASP page which will fetch records from a SQL server DB table. The table "order_master" has a field called order_date. I want to frame a select query to fetch order date > a date entered by user(ex : 07/01/2008)
I tried with convert and cast, but both are not working. The sample data in order_date column is 4/10/2008 8:27:41 PM. Actually, I dont know what type it is (varchar/datetime).
Is there any way to do that?
I'd check to make sure that the SQL datatype is a DateTime or SmallDateTime first, then I'd check to make sure that you're passing in a Date/DateTime value from the page.
If those are both correct, then you'd probably be better off following Joel's advice and explicitly convert both values to dates before trying the comparison. Also, check the precision of the time values that you're looking at; it seems obvious, but 1/1/2008 12:00:00.001 AM will not be equal to 1/1/2008 12:00:00.000 AM. Yes, I am speaking from experience. :P
the 07/01/2008 date is the British/French annotation, so all you need to do is:
SELECT myColumn FROM myTable WHERE myDateField >= convert(datetime, '07/01/2008 00:00:00', 103)
this code will get all rows where myDateField has the date 7th of January 2008, since 00:00:00 (hh:mm:ss) so, the first second on that day... in simple words, the entire day.
for more info, check Books online on MSDN
You could create a stored procedure like this
CREATE PROCEDURE GetOrders
#OrderDate DATETIME
AS
SELECT
*
FROM order_master
WHERE Order_Date > #OrderDate
GO
Then you can just convert the users input to a date before calling the stored procedure via your ASP code.
Edit
I just noticed the remark about the column type, you can run this command
sp_help order_master
to get column information to find the data type of order_date.
Have you tried CONVERT()'ing both values to a datetime type?
Remember that when comparing dates, 4/10/2008 8:27:41 PM is not equal to 4/10/2008. SQL Server will interpret 4/10/2008 to mean 4/10/2008 12:00:00 AM, and do an exact comparison down to the second. Therefore 4/10/2008 is LESS THAN 4/10/2008 8:27:41 PM
You state you don't know the field type. That would be the first problem to solve, find out. You can do that with:-
SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Order_Master' AND
COLUMN_NAME = 'Order_Date'
If its not one of the datetime types it should be converted, if that isn't your responsibility then get on to someone who does have the responsibility.
The fact that you are concerned about the 'format' of the date indicates that you may be building the SQL using concatenation. If so stop doing that. Use a command with a parameter and pass in the date as date type.
Now your issue is one of how the date is entered at the client end and getting it into an unambigous format that can be parsed as a date in the ASP code.
If that is not something you have solved add a comment to this answer and I'll expand this answer.