Convert Number type to Date in postgres SQL - sql

I have a numeric data in a column 20170930, need help in converting it into Date in PostgreSQL , tried multiple ways but non seems to work

You can convert to a string and then to a date:
select column::text::date
You can also express this using explicit cast() syntax:
select cast(cast(20170930 as text) as date)

Use one of the following :
SELECT cast(yourcol::varchar as date ) as dt1, yourcol::varchar::date as dt2
where dt1 and dt2 values of type date, and yourcol is a numeric value such as 20170930
Demo

The best thing is to change column datatype into Date type,
ALTER TABLE table_name
ADD column_name Date;
As shown above, PostgreSQL supports a full set of SQL date and time types, as shown in the table below. Dates are counted according to the Gregorian calendar. Here, all the types have a resolution of 1 microsecond / 14 digits except date type, whose resolution is day.

Please try below query
SELECT to_date(column::varchar,'YYYYMMDD')

For anybody who fell into my pitfall I tried this but my numeric was like a 'seconds past 01-01-1970 format' rather than YYYYMMDD
This worked
SELECT to_timestamp(yourcol) as numeric_column_now_date
from yourtable
see here
https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT

Related

"Conversion failed when converting" Is there a way to det. what row/ entry?

Is there a way to determine what row/ date entry SQL is having trouble converting ? There are 300k date entries and I'm unsure which one my code is having a problem with. This code has worked in the past.
Conversion failed when converting date and/or time from character
string
You could use TRY_CONVERT to search for invalid date literals:
SELECT *
FROM tab_name
WHERE TRY_CONVERT(DATE, col_name) IS NULL
AND col_name IS NOT NULL;
If necessary you could provide date time style.
db<>fiddle demo
You can check if the column was in a date format, using ISDATE():
select myColumnDate
from myTable
where ISDATE(myColumnDate) = 0

Convert from varchar into date in SQL Server

This looks easy solution but I can't seem to figure out as to why this is not working for me. I have a column that has data like this:
DateField
----------
12/16/2016
11/06/2016
All I want to do is to convert from varchar into a date column, but I am getting this error:
Conversion failed when converting date and/or time from character string.
Here is my simple query:
select convert (date, DateField) as convertedField
from myTable
Nothing wrong with the two examples you have given. There are some bad dates in your table which cannot be converted to date.
Use TRY_CONVERT function for bad dates it will return NULL
select TRY_Convert(date,DateField)
From myTable
You should always store dates in DATE/DATETIME datatype.
If you want to see the records which cannot be converted to date then
select DateField
From myTable
Where TRY_Convert(date,DateField) IS NULL
If working with a specific date format like mm/dd/yyyy You can specify it in Convert() function like the following
CONVERT(DATETIME,DATAFIELD,101)
If it still is not working, use TRY_CONVERT() to get which rows are throwing this exception:
SELECT *
FROM TBL
WHERE TRY_CONVERT(DATETIME, DATAFIELD, 101) IS NULL
This will return rows that cannot be converted
TRY_CONVERT() will return NULL if conversion failed
Read more about DateTime formats here:
SQL Server CONVERT() Function tutorial
Read TRY_CONVERT MSDN Article
You need to specify the format of date time while formatting. The date in your table is currently in U.S format so you should pass the third argument 101 in your convert function.
SELECT CONVERT(date,[DateField],101) FROM myTable;
Working Fiddle here http://rextester.com/NYKR49788
More info about date time style here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

SQL datetime LIKE select - why do I need an extra %?

Can someone explain to me why when I perform a LIKE select in SQL (T-SQL) on a varchar column I can do the following:
SELECT *
FROM Table
WHERE Name LIKE 'Th%'
to get names beginning with Th, but when I do the same on a datetime column I need a % before the year, like:
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
to get dates in 2013. The datetimes are stored in yyyy-MM-dd hh:mm:ss format. I know I could use a DATEPART style query but I was just interested in why I need the extra % here.
The DATETIME is converted to a VARCHAR before the comparison, and there definitely is no guarantee that the conversion will be in the pattern you mention. DATETIME is not stored internally as a VARCHAR but as a FLOAT.
You should stop wondering because the syntax is not useful.
SELECT *
FROM Table
WHERE Date LIKE '%2013%'
Will give you a full table scan because the date will be converted to a varchar when comparing. In other words, don't do it !
Use this syntax instead:
SELECT *
FROM Table
WHERE Date >= '2013-01-01T00:00:00'
and Date < '2014-01-01T00:00:00'
If the Date field is in timestamp:-
SELECT *
FROM Table
WHERE year(Date) = '2013'
The sql server converts datetime to this format (Jan 1, 1900 9:20AM.)Because of that reason We need to use an extra %.
If you want to search the records start with month Jan
you can use following query for date time
SELECT *
FROM Table
WHERE Date LIKE 'Jan%'.
No need of extra '%'.

How can I convert a varchar field (YYYYMM) to a date (MM/01/YY) in SQL?

I'm sure this is quite simple, but I've been stuck on it for some time. How can I convert a varchar field (YYYYMM) to a date (MM/01/YY) in SQL?
Thanks.
Edit: I'm using Open Office Base (HSQL), not MySQL; sorry for the confusion.
Try the str_to_date and date_format functions. Something like:
select date_format( str_to_date( my_column, '%Y%c' ), '%c/01/%y' ) from my_table
try :
SELECT STR_TO_DATE(CONCAT(myDate,'01'),'%Y%m%d')
FROM myTable
Use STR_TO_DATE:
From mysql.com:
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts.
The date, time, or datetime values contained in str should be given in the format indicated by format. For the specifiers that can be used in format, see the DATE_FORMAT() function description. If str contains an illegal date, time, or datetime value, STR_TO_DATE() returns NULL. Starting from MySQL 5.0.3, an illegal value also produces a warning.
Range checking on the parts of date values is as described in Section 11.3.1, “The DATETIME, DATE, and TIMESTAMP Types”. This means, for example, that “zero” dates or dates with part values of 0 are allowed unless the SQL mode is set to disallow such values.
mysql> SELECT STR_TO_DATE('00/00/0000', '%m/%d/%Y');
-> '0000-00-00'
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'
Get the year:
SUBSTRING(field FROM 2 FOR 2)
Get the month:
SUBSTRING(field FROM -2 FOR 2)
Compose the date:
CONCAT(SUBSTRING(field FROM -2 FOR 2), '/01/', SUBSTRING(field FROM 2 FOR 2))
This will convert from YYYYMM to MM/01/YY.
To be clear: if you're looking for method to convert some value of type Varchar/Text to value of type Date than solutions are:
using CAST function
CAST(LEFT('201205',4)||'-'||SUBSTRING('201205' FROM 5 FOR 6)||'-01' AS DATE)
starting from OpenOffice 3.4 (HSQLDB 2.x) new Oracle-like function TO_DATE supposed to be available
TO_DATE('201205','YYYYMM')
in addition to the written i can mention that you also can construct a string with ANSI/ISO 'YYYY-MM-DD' formatted representation of the date,- Base will acknowledge that and succesfully convert it to the Date type if necessary (e.g. INSERTing in Date typed column etc.)
Here is doc's on HyperSQL and highly recommended OO Base guide by Andrew Pitonyak

SQL query to convert Date to another format

Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.
The Column is paid_month and the values are below.
200901
200902
So,please help in writing SQL query to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .
Thanks
Rohit
Hi,
I am sorry for missing in giving the whole information.
1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902
3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.
4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy
I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.
**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**
It looks like YYYYMM - depending on your database variant, try STR_TO_DATE(paid_month, 'YYYYMM'), then format that.
Note: MM/DD/YYYY is not "normal" format - only Americans use it. The rest of the world uses DD/MM/YYYY
For MySQL check
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
Example:
SELECT DATE_FORMAT(NOW(), '%d/%m/%Y')
For MySQL, you would use the STR_TO_DATE function, see http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date
SELECT STR_TO_DATE(paid_month,'%Y%m');
Sounds like the column contains some normal dates and some YYYYMM dates. If the goal is to update the entire column, you can attempt to isolate the YYYYMM dates and update only those. Something like:
UPDATE YourTable
SET paid_month = DATE_FORMAT(STR_TO_DATE(paid_month, '%Y%m'), '%m/%d/%Y')
WHERE LENGTH(paid_month) = 6
SELECT (paid_month % 100) + "/01/" + (paid_month/100) AS paid_day
FROM tbl;
I'm not sure about how oracle concatenates strings. Often, you see || in SQL:
SELECT foo || bar FROM ...
or functions:
SELECT cat (foo, bar) FROM ...