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

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.

Related

SQL Query for returning the latest date

If I consider the following:
Customer | Date
100 | 09-06-2021
100 | 17-03-2020
I am trying to find out the most recent date from the above, by using: select MAX(Date) from table, and it is returning 17-03-2020, which is wrong.
How do I get the most recent date as 09-06-2021?
What is wrong is that you are storing the date as a string, not a date.
You can fix your immediate problem by doing:
select max(str_to_date(date, '%d-%m-%Y'))
from t;
But you should really fix the data. Start by putting the date in a canonical format:
update t
set date = str_to_date(date, '%d-%m-%Y');
Then modify the column to the correct data type:
alter table t modify column date date;

Data truncation: Truncated incorrect date value error

I'm using MySQL version: 5.7.22
So I'm trying to have a table that contains a date column from string. The text field contains data in following DateTime format "d/m/YYYY h:m:s" format. e.g. "14/11/2018 20:10:04 +00:00".
I want to alter the table with a new column that is of the following format '%Y-%m-%d'. I get a
Data truncation: Truncated incorrect date value error
when I try to update the table. But I get the result when I just use a select statement to convert from string to date.
UPDATE BIG_DATA SET BIG_DATA.RealDate = ( SELECT x.d
From (SELECT (DATE_FORMAT(STR_TO_DATE(BIG_DATA.Date , '%d/%m/%Y'), '%Y-%m-%d')) as d
FROM BIG_DATA) as x);
Any help would be grateful!
The reason you are getting an error is that the warning for an incorrect date value (one that produces a value with zeros in it) that is produced by STR_TO_DATE on a SELECT is promoted to an error when you attempt to do an UPDATE. For example, if you do
SELECT STR_TO_DATE('14/11/2018 20:10:04 +00:00', '%d/%m/%Y');
SHOW WARNINGS
Your output will be:
2018-11-14
Warning 1292 Truncated incorrect date value: '14/11/2018 20:10:04 +00:00'
You can work around this by only supplying the date part (the leftmost 10 characters) of the string to STR_TO_DATE:
SELECT STR_TO_DATE(LEFT('14/11/2018 20:10:04 +00:00', 10), '%d/%m/%Y');
SHOW WARNINGS
Output is simply 2018-11-14
This then allows you to create your other column and UPDATE it from the date column:
ALTER TABLE big_data ADD
realdate DATE;
UPDATE big_data
SET realdate = STR_TO_DATE(LEFT(date, 10), '%d/%m/%Y');
SELECT * FROM big_data
Another possibility you might want to consider is using a generated column:
ALTER TABLE big_data ADD
realdate DATE AS (STR_TO_DATE(date, '%d/%m/%Y'));
SELECT * FROM big_data
In both cases the output is
date realdate
14/11/2018 20:10:04 +00:00 2018-11-14
Demo on dbfiddle

Max(Date) not working for nvarchar in SQL Server

I have a column name Endtime of type nvarchar(50) and i am trying to get the max(Endtime) by using the below query:
select COALESCE(CONVERT(nVARCHAR(50), MAX(EndTime), 103), '-') AS EndTime from dbo.vwJobHistory
The results are fine as long as Year is same (12/31/2015) but as soon as i put some data with year (01/22/2016) , the query still shows the Max. Date of 2015 instead of 2016.
I have tried Max(cast(endtime as DateTime)) but this also gives conversion error
How can I resolve this? Thanks in advance.
I can't find an error in your above query, but here's an alternative way how you could write the query:
select top 1 COALESCE(CONVERT(nVARCHAR(50), EndTime, 103), '-') AS EndTime
from dbo.vwJobHistory
order by endtime desc
Update 1 (clarifying table structure):
It is currently unclear if your datetime data is currently stored inside a nvarchar(50) field or if you want to cast your datetime data as nvarchar(50).
Could you run the following query and update your question with the result?
SELECT
COLUMN_NAME, DATA_TYPE, col.CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS col WHERE TABLE_NAME LIKE 'vwJobHistory'
Could you also post a sample row from your table using
SELECT endtime FROM dbo.vwJobHistory
Update 2 (convert string to datetime, apply sort on converted field)
Taken from your comment, it seems your date strings are stored with SQL format 109, so let's try to convert the nvarchar back to datetime, apply sort to it and output the result:
SELECT * FROM (
SELECT
convert(datetime, EndTime, 109) endtimeconverted,
*
FROM vwJobHistory
) xyz
ORDER BY endtimeconverted DESC

Change Time Portion Only Of A DateTime Field With Case Statement

I am wanting to use a case statement to change the time piece only of a datetime field in SQL Server 2008 I have a query that will change the time piece, but I need to know how to keep the date portion intact so only the time piece is altered. Meaning if the datetime is
01/01/2015 08:45:10.863
with my syntax I would want to alter it to
01/01/2015 08:30:00.000
This is my syntax which as I said will change the time portion but it does not retain the date. How can I keep the date and change the time portion only?
Create Table #Test
(
[charactername] varchar(100)
,[lefttabletime] datetime
)
Insert Into #Test Values
('Bob Goblin', '01/01/2015 08:14:23.000'),
('Grab Crab', '01/01/2015 08:30:56.023'),
('Mike Knight', '01/01/2015 08:45:10.863')
Select
[charactername]
,case when CAST([lefttabletime] As TIME) > '08:40:00.000' THEN '08:30:00.000'
else [lefttabletime]
FROM #Test
Drop Table #Test
EDIT Additional Syntax Attempted
This threw an error of:
Msg 241, Level 16, State 1, Line 10
Conversion failed when converting date and/or time from character string.
And I tried this syntax
Select
[charactername]
,case when CAST([lefttabletime] As TIME) > '08:40:00.000'
THEN CAST(CAST(CONVERT(DATE, [lefttabletime],101) AS VARCHAR)
+ '08:40:00.000' AS DATETIME) else [lefttabletime] end
FROM #Test
I find it easier if you split the leftabletime into a date and a time component first, the recombine them with the new time portion:
;WITH cte AS
(
SELECT charactername,
[date] = CAST(lefttabletime as date),
[time] = CAST(lefttabletime as time)
FROM #test
)
SELECT charactername,
CAST([date] as datetime)
+ CAST(CASE WHEN [time] > '08:40:00' THEN '08:30:00' ELSE [time] END as datetime)
FROM cte
You can merge the two statement together but I like the simplicity and clarity that a separate CTE provides.
I usually try to make datetime rounding problems fit the DATEADD/DATEDIFF pattern, and I've managed to do that here:
Create Table #Test
(
[charactername] varchar(100)
,[lefttabletime] datetime
)
Insert Into #Test Values
('Bob Goblin', '2015-01-01T08:14:23.000'),
('Grab Crab', '2015-01-01T08:30:56.023'),
('Mike Knight', '2015-01-01T08:45:10.863')
select charactername,
CASE WHEN DATEDIFF(minute,'20010101',lefttabletime)%60 >= 40 THEN
DATEADD(minute,((DATEDIFF(minute,'20010101',lefttabletime)/30)*30),'20010101')
ELSE lefttabletime END
from #Test
Drop Table #Test
The expression DATEADD(minute,((DATEDIFF(minute,'20010101',lefttabletime)/30)*30),'20010101') rounds the time of a datetime down to the nearest 30 minutes (20010101 is an arbitrary date and doesn't need to be adjusted in any way).
I also just use a separate DATEDIFF to find the required matching condition. Where possible, with datetime data, I try to keep it in datetime variables, or, at worst, ints. As soon as you convert to strings you have to start worrying about formats, etc, which I'd usually rather avoid.
Result:
charactername
--------------------- -----------------------
Bob Goblin 2015-01-01 08:14:23.000
Grab Crab 2015-01-01 08:30:56.023
Mike Knight 2015-01-01 08:30:00.000

I am trying to select all the values from a table using date in SQL Server 2008

I am trying to select all the values from a table using date in SQL Server 2008. The problem is the date column in the DB is in Datetime format. But the thing is I have to select all the values from the database by using date
I used the following query
select *
from Table
where subdate = '2012-12-12'.
It won't return any value....
My table is like this
Subdate val1 val2 val3 name
-------------- ----- ----- ---- -----
2012-12-12 12:32:12.000 2 1 2 ben
2012-12-27 15:17:32.533 2 1 2 yen
2012-12-27 15:20:06.660 2 1 2 sun
Thanks in advance.........
select * from Tble where subdate>='20121212' and subdate <'20121213'
would be my usual recommended approach(*). If it's a parameter, it would be:
select * from Tble where subdate>=#Parm and subdate <DATEADD(day,1,#Parm)
'2012-12-12' and '2012/12/12' can be subject to weird conversion issues, depending on your language/date settings on the server. '20121212' will always be converted as YYYYMMDD.
(*) I don't use BETWEEN for such comparisons, because you either include two midnights , or you have to calculate the last moment before midnight of the following day. Which would be at 23:59:59.997 if you're using datetime, but suddenly changes to being something else for datetime2.
SELECT *
FROM Table
WHERE CAST(subdate AS DATE)='2012-12-12'
Raj
The date in the table also contain Time so you have to convert that date to the format suitable for the date you enter.
You have to use: Sql Server Date Formats
select * from Tble where CONVERT(VARCHAR(10), subdate, 111) = '2012/12/12'
Demo SQLFiddle