how to query date in json? - json

create tabel test(json jsonb);
insert into test values('{"graductionDate": "Jun 1 2015 12:00AM"}')
insert into test values('{"graductionDate": "Jun 1 2016 12:00AM"}')
query result is incorrect:
select * from test where json>'{"graductionDate":"20151001 00:00"}'
I want get data with graductionDate after 20150101. But the above code gets all rows.

http://www.postgresql.org/docs/current/static/functions-json.html
Not having used json objects before I would guess you need to extract the date field from the object, treat it as a date and then compare it to another date.
select *
from test
where ((json->>'graductionDate')::timestamp) > ('20151001 00:00':: timestamp);
I havent tested this code.
Edit
From your comment it sounds like the ->> operator treats null as the empty string ''. You can convert '' to null using the nullif() function:
select *
from test
where (nullif(json->>'graductionDate', '')::timestamp) > ('20151001 00:00':: timestamp);
This code is still untested.

Related

Mysql returns some records null in field of date as date have multiple format

I am trying to analyze order_Date column and column have multiple date format i want to convert all those date in same format which wull make be easier to analyze the order_date.
I am trying to analyze the order_date however this column have multiple date format 2019/07/15 and 1/13/2014
Howeever, while converting different format date with one format yyyy/mm/dd with query.
select date_format(order_date, '%y/%m/%d'),orderid from superstore;
it shows null values like this.
i have tried to use `CAST as well but it shows every single value as null.
select case when order_date like '%Y' then date_format(order_date, '%Y/%m/%d') else null end as newdate from superstore;
date_format funtion is used to format a date datatype you should use https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date any null values returned by str_to_date either failed or started as null. You will need to examine these and adjust the str_to_date parameters appropriately. There is a catch though is 20/2/20 y/m/d or d/m/y (for example) and how can you differentiate month and day where both are <=12?
For example
drop table if exists t;
create table t
(dt varchar(10));
insert into t values
('1/1/2020'),('2020/1/12'),('12/12/12'),(null),('13-14-15');
select dt,
case when length(substring_index(dt,'/',-1)) = 4 then str_to_date(dt,'%d/%m/%Y')
when length(substring_index(dt,'/',1)) = 4 then str_to_date(dt,'%Y/%m/%d')
when length(substring_index(dt,'/',1)) = 2 then str_to_date(dt,'%y/%m/%d')
else str_to_date(dt,'%y/%m/%d')
end dateformatted
from t;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=553219f33ad9e9a4404fc4c0cb6571c9
note in no case can I identify month and day and sometimes year..

Postgresql json field has dates in both YYYY-MM-DD and 13 digit unix timestamp format

I am parsing a json array and one field I am pulling out is closedate. However closedate has two different date formats one is YYYY-MM-DD and the other is a 13 digit timestamp. I am trying to get consistent formatting of the dates as well as have it be an integer compared to a string. Right now the query returning the close date is:
json_array_elements(ld.data->'Table1'->'Details')->>'closeDate' as closedate
and it returns close date as a string:
id
closedate
1
2021-09-29
2
1606824000000
Someone was telling me to do something like a case statement with regex. But I am not familiar with regex function. Any help is appreciated.
Edit: I have
case when x.closedate::text ~* '^[0-9]{13}$' then
to_timestamp(x.closedate::bigint/1000)
when x.closedate = '0' then null
when x.closedate = '' then null
else
to_date(x.closedate,'MMDDYYYY') end as transactionclosedate
the case statement works for converting the 13 digit timestamp to a date but I am getting the error:
ERROR: date/time field value out of range: "2020-10-23"
when trying to convert the date strings in the correct format to dates in the else part of the case statement.
An example of one way to make this work. My regex skills are not strong so others may have a better solution:
create table regex_test (id int, fld_1 varchar);
insert into regex_test values (1, '1606824000000'), (2, '2021-09-29');
select * from regex_test ;
id | fld_1
----+---------------
1 | 1606824000000
2 | 2021-09-29
select
id,
case when fld_1 ~* '^[0-9]*$' then
to_timestamp(fld_1::bigint/1000)
else
fld_1::timestamp end as ts_fld
from
regex_test;
id | ts_fld
----+------------------------
1 | 2020-12-01 04:00:00-08
2 | 2021-09-29 00:00:00-07
I hope this query help you
with data as (
select
json_array_elements(data->'Table1'->'Details')->>'closeDate' as closedate
from your_table
)
select
case when closedate::text ~ '^[0-9]+$' then
to_timestamp(closedate::numeric / 1000)::date
else
closedate::date
end
from data;
Either of the other answers would be ok providing that only the specified formats exist. However, containing those formats requires a text field; which may contain anything. It is dangerous to assume if the content is not 13 digits then it is a valid formatted ISO date. I would validate that as well (and verify digits length).
select id,
, case when closedate ~* '^[0-9]{13}$' then
to_timestamp(closedate::bigint/1000)
when is_valid_iso_date(closedate) then
closedate::timestamp
else
'-infinity'::timestamp -- or whatever to indicate Invalid Date.
from <your table> ;
The problem being that is_valid_iso_date function. It turns out however I had to create just that a couple years ago, I'll make the result available here.
DISCLAIMER: While the function has given no known erroneous results it has NOT been exhaustively tested.

I want to fetch the date timestamp in Toad using SQL Query

I have a column in toad
CREATE_DATE='10/9/2020 2:05:10 AM'
I am trying to fetch this using the below SQL Query but it is giving me an error ''Not a valid Month'.
SELECT * FROM TABLE
WHERE
CREATE_DATE = '10/9/2020 2:05:10 AM'
can someone please help, how can i fetch this column
'
That looks like a DATE datatype column. If that's so, here's an example:
SQL> create table test (create_date date);
Table created.
SQL> insert into test values (sysdate);
1 row created.
Just to see what's in there:
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';
Session altered.
SQL> select * From test;
CREATE_DATE
-------------------
09.10.2020 09:15:12
OK; now, use a query which utilizes the TO_DATE function (as we'd want to provide a string to it) with appropriate format mask (so that Oracle knows what is what in that string; whether 09 represents a month, or a day).
For example:
SQL> select * from test
2 where create_date = to_date('09.10.2020 09:15:12', 'dd.mm.yyyy hh24:mi:ss');
CREATE_DATE
-------------------
09.10.2020 09:15:12
Or, another date format (the one you use):
SQL> select * from test
2 where create_date = to_date('10/9/2020 9:15:12 am', 'mm/dd/yyyy hh:mi:ss am');
CREATE_DATE
-------------------
09.10.2020 09:15:12
Basically, the keyword is to let the database know what you exactly want, not let it guess. Sometimes it'll succeed, but sometimes it'll fail - just like in your query.

STR_TO_DATE() returning NULL for some TIME values

In one of my projects, I was using the function STR_TO_DATE() to convert a string into a date value based on the fmt format string. For example to convert a string into a DATE value:
SELECT STR_TO_DATE('21-5-2013','%d-%m-%Y'); // returns 2013-05-21
But when I went to convert a time string into a TIME value, I get some strange behaviors:
SELECT STR_TO_DATE('203005','%h%i%s'); // returns null
SELECT STR_TO_DATE('19:30:05','%h:%i:%s'); // returns null
SELECT STR_TO_DATE('113005','%h%i%s'); // returns 11:30:05
SELECT STR_TO_DATE('01:30:05','%h:%i:%s'); // returns 01:30:05
One of the answers I found here in StackOverflow is that:
This is indeed because of the SQL mode NO_ZERO_DATE.
But I'm still intrigued by the behavior of the function. You could check easily what I'm talking about by following this link
The problem is the format you are setting, it recognises the time from 0-12, not 0-23. It should be
SELECT STR_TO_DATE('203005','%H%i%s');
SELECT STR_TO_DATE('19:30:05','%H:%i:%s');
Check the following link with the list of all available time and date formats.
https://www.techonthenet.com/mysql/functions/str_to_date.php
I ended up contat-ing the date doing something like this to avoid having a null.
SELECT STR_TO_DATE(
concat('01/01/2018', ' ', '19:30:05'),
'%d/%m/%Y %H:%i:%s'
),
'%H:%i:%s'
);

How to insert date in a table with a different format?

My problem here is that I have a date value as 05/09/2013 in a HTML text box which cannot be altered.
Now sql only accepts date format as yyyy/mm/dd. so while inserting this textbox value into sql database it does not support this format and throws an exception.
Therefore my question is how to insert a textbox value with different format into a sql database?
For instance my code would look like
insert into table (date) value('"& date& "')
input box has a calender type textbox and sends a date in 05/09/2013 format
UPDATE
For MySQL use STR_TO_DATE()
INSERT INTO Table1 (date)
SELECT STR_TO_DATE('05/09/2013', '%d/%m/%Y')
SQLFiddle
Based on your comments the query should look like
sql = "INSERT INTO shiftpatterns (siteNumber,shiftdate) SELECT '"&siteNumber&"', 'STR_TO_DATE('"&shiftdate&"','%d/%m/%Y')"
Original answer
For SQL Server use CONVERT
INSERT INTO Table1 ([date])
SELECT CONVERT(datetime, '05/09/2013', 103)
SQLFiddle
In both cases
SELECT * FROM table1
will give you:
| DATE |
------------------------------------
| September, 05 2013 00:00:00+0000 |
According to your tags you're using classic ASP, so we can assume that you're using a form to submit the data to the ASP page you're writing.
The most fault-tolerant way, if you cannot edit the client-side page, is to spool up a date object, parse the supplied value, and then extract your data from there. Or, you could just treat it as a string, test for the expected format, and then maniplate the string into the clearer form.
function fixDate(inStr)
if inStr like '99/99/9999' then
fixDate = LEFT(inStr,4) + "/" + RIGHT(inStr,4)
endif
end function