Informix SQL Compare DateTime value on Where Statement - sql

I have a datetime field called entrytimestamp, with content of the field is for example: 2014-01-07 16:20:00. I would like to query all the data that has entrytimestamp after 09:00:00 o'clock, regardless what date it was.
I have a prototype query:
select *
from trading
where to_char(entrytimestamp, "%H%M%S") >= "090000"
But I think it is logically a mistake, because it will compare the text string, not the sequence value. What is the right way to do it?

Use the EXTEND() function to extract the time part:
select *
from mytable
where extend(entrytimestamp, hour to second) > '09:00:00'

I dont know if it performs well,
but you could compare directly with the time portion of the datetime,
i think a cast here should perform pretty fast (just cuts off the date)
select *
from (select getdate() as mydatetime) as data
where cast(mydatetime as time) > cast('09:00:00' as time)
EDIT, just noticed this was for Informix SQL, so not sure it works then, Sorry

Related

How to compare datetime in SQL Server?

I have to show the date 2018/01/30 if the datetime is between 2018/01/30 04:59:59.000 and 2018/01/31 04:59:59.000
I have a table called DataEntry. I want to move those records by date as per my criteria.
This DataEntry table have TransferTime that datatype is datetime.
As per my criteria if the TransferTime is 2018/01/30 01:30:59.000 then the date should be 2018/01/29
I think you can simply just write like this:
select
case when DATEPART(HOUR,'2018/01/30 01:30:59.000') >= 05 then cast('2018/01/30 01:30:59.000' as date)
else cast(dateadd(Dd,-1,'2018/01/30 01:30:59.000' )as date)
end
This is somewhat of a guess on vague logic, but perhaps using CONVERT and DATEADD?
WITH VTE AS(
SELECT CONVERT(datetime2(3),DT) AS DT
FROM (VALUES('20180130 04:59:59.000'),('20180131 01:00:34.000'),('20180130 01:30:59.000')) V(DT))
SELECT CONVERT(date, DATEADD(SECOND, -17999,DT)) AS D, DT
FROM VTE;
It's worth noting that you, oddly, state that '20180130 04:59:59.000' AND ''20180131 04:59:59.000' should both be on the same day, ('20180130'). This doesn't make any sense, as Days don't overlap like that. Thus the latter time would show '20180131', as it's exactly 24 hours later.
If the former time should actually be '20180129', then change -17999 to -18000, or SECOND,-17999 to HOUR, -5.
this will do too:
select cast(dateadd(second, -17999,Transfertime) as date)
being 17999 = 4hs59m59s in seconds

SQL Server : Comparing Time

I am trying to compare time in my SQL query. However, when I run the query, I get zero result but I can see that in the table, there are records that should appear.
The query is as such:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '26/08/2015'
AND StartTime <= CONVERT(varchar(5), GETDATE(), 108)
The StartDate is stored in the database as YYYY-MM-DD and it seems to work fine when I query only with the date.
However, when I add the StartTime is when things don't work. StartTime stores the value in the 24 hour clock format.
What am not doing right?
Thanks
Use a correct datetime format:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '2015-08-26' AND StartTime <= cast(GETDATE() as date)
Don't compare date/time values as strings. The data types are built into the language. Use them.
I have not explicitly used this scenario but comparing dates can be a problem depending on how the fields are compared.
eg: '28/07/2015' is not less than your startdate as 28 > 26.
You could try comparing dates reformatted into a YYYYMMDD format.
Cheers.

SQL. Select Unixtime for whole day

I am looking for a way to select a whole days worth of data from a where statement. Timestamp is in unix time such as (1406045122). I want to select the today's date of unix time range and find all the food that has been added in today. Thank in advance. This is the code I wrote. I'm not sure what I should put in the ( ????? ) part. I know it has to do with 60*60*24=86400 secs per day but I'm not too sure how I can implement this.
Select timestamp,food from table1 where timestamp = ( ????? );
Select timestamp,food
FROM table1
WHERE timestamp > :ts
AND timestamp <= (:ts + 86400);
replace :ts with the starting timstamp and you'll filter a whole day's worth of data
edit
This select query would give you the current timestamp (there may be more efficient ones, i don't work with sqlite often)
select strftime("%s", current_timestamp);
You can find more info about them here: http://www.tutorialspoint.com/sqlite/sqlite_date_time.htm
Using the strftime() function, combined with the date() function we can write this following query which will not need any manual editing. It will return the records filtered on timestamp > start of today & timestamp <= end of today.
Select timestamp,food
FROM table1
WHERE timestamp > strftime("%s", date(current_timestamp))
AND timestamp <= (strftime("%s", date(current_timestamp)) + 86400);
Your mileage will likely depend on your version of SQL but for example on MySQL you can specify a search as being BETWEEN two dates, which is taken conventionally to mean midnight on each. So
SELECT * FROM FOO WHERE T BETWEEN '2014-07-01' AND '2014-07-02';
selects anything with a timestamp anywhere on 1st July 2014. If you want to make it readable you could even use the ADDDATE function. So you could do something like
SET #mydate = DATE(T);
SELECT * FROM FOO WHERE T BETWEEN #mydate AND ADDDATE(#mydate, 1);
The first line should truncate your timestamp to be 00:00:00. The second line should SELECT only records from that date.

To get date from datetime in sql

I have datecreated field in a table. It contains value as "2009-12-30 11:47:20:297"
I have a query like this:
select *
from table
where DateCreated = getdate()
Although one row exists with today's date, I am not getting that row while executing above query. Can anybody help?
The reason why your query doesn't return the row you expect, is because GETDATE() returns the date and time portion at the moment the query was executed. The value in your DateCreated column will not match the time portion, so no rows are returned.
There are various ways to construct a query so that it evaluates the date based on only the date component. Here's one example:
WHERE YEAR(datecreated) = YEAR(GETDATE())
AND MONTH(datecreated) = MONTH(GETDATE())
AND DAY(datecreated) = DAY(GETDATE())
The unfortunate reality is that any query using a function on the column means that if an index exists on the column, it can't be used.
You can use something like this with Sql Server
CREATE FUNCTION [dbo].[udf_DateOnly](#DateTime DATETIME)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(dd,0, DATEDIFF(dd,0,#DateTime))
END
This line
DATEADD(dd,0, DATEDIFF(dd,0,#DateTime))
will strip out the Date portion.
The datetime field includes both the date and the time, accurate to the millisecond. Your query will only work if it is the exact millisecond stored in the database.
To check if it is today, but ignore the time of day, you can check for a range like this:
select * from table where
DateCreated >= '2009-12-30' and
DateCreated < '2009-12-31'
You can use that in conjunction with a function that converts the current date, as astander or Khilon has posted. Here is a full example using astander's answer. Also, as Craig Young points out, this will work with indexes.
select * from table where
DateCreated >= DATEDIFF(dd,0,GETDATE()) and
DateCreated < DATEDIFF(dd,0,GETDATE())
The simplest solution might be :
SELECT CAST(GETDATE() as DATE)
You can convert datetime to a string with only the date by using
CONVERT(varchar(8), GETDATE(), 112)
If needed, you can then change it back to datetime and as a result you'll get a datetime with the hours, minutes, seconds and milliseconds set to zero.

How to get records after a certain time using SQL datetime field

If I have a datetime field, how do I get just records created later than a certain time, ignoring the date altogether?
It's a logging table, it tells when people are connecting and doing something in our application. I want to find out how often people are on later than 5pm.
(Sorry - it is SQL Server. But this could be useful for other people for other databases)
For SQL Server:
select * from myTable where datepart(hh, myDateField) > 17
See http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx.
What database system are you using? Date/time functions vary widely.
For Oracle, you could say
SELECT * FROM TABLE
WHERE TO_CHAR(THE_DATE, 'HH24:MI:SS') BETWEEN '17:00:00' AND '23:59:59';
Also, you probably need to roll-over into the next day and also select times between midnight and, say, 6am.
In MySQL, this would be
where time(datetimefield) > '17:00:00'
The best thing I can think would be: don't use a DateTime field; well, you could use a lot of DATEADD/DATEPART etc, but it will be slow if you have a lot of data, as it can't really use an index here. Your DB may offer a suitable type natively - such as the TIME type in SQL Server 2008 - but you could just as easily store the time offset in minutes (for example).
For MSSQL use the CONVERT method:
DECLARE #TempDate datetime = '1/2/2016 6:28:03 AM'
SELECT
#TempDate as PassedInDate,
CASE
WHEN CONVERT(nvarchar(30), #TempDate, 108) < '06:30:00' then 'Before 6:30am'
ELSE 'On or after 6:30am'
END,
CASE
WHEN CONVERT(nvarchar(30), #TempDate, 108) >= '10:30:00' then 'On or after 10:30am'
ELSE 'Before 10:30am'
END
Another Oracle method for simple situations:
select ...
from ...
where EXTRACT(HOUR FROM my_date) >= 17
/
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions050.htm#SQLRF00639
Tricky for some questions though, like all records with the time between 15:03:21 and 15:25:45. I'd also use the TO_CHAR method there.
In Informix, assuming that you use a DATETIME YEAR TO SECOND field to hold the full date, you'd write:
WHERE EXTEND(dt_column, HOUR TO SECOND) > DATETIME(17:00:00) HOUR TO SECOND
'EXTEND' can indeed contract the set of fields (as well as extend it, as the name suggests).
As Thilo noted, this is an area of extreme variability between DBMS (and Informix is certainly one of the variant ones).
Ok, I've got it.
select myfield1,
myfield2,
mydatefield
from mytable
where datename(hour, mydatefield) > 17
This will get me records with a mydatefield with a time later than 5pm.