SQL, LEFT operator on datetime - sql

Is it possible to use the LEFT() operator in MSSQL on a datetime.
I'm asking because this is my db:
In a SQL query i want now to SELECT only this objects WHERE Rueckmeldetatum = a date in form like (2023-01-27) so my string comperable has no time just a date. But with this SQL Query I'm getting no results:
SELECT TOP (1000) [KNR]
,[Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE LEFT(Rueckmeldedatum,10) ='2023-01-27'
But normally or what i want to get is the 20th entry from the picture.

You should cast the datetime to date, then compare to a date literal:
SELECT TOP (1000) [KNR], [Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE CAST(Rueckmeldedatum AS date) = '20230127';
Or, better yet, use this sargable version:
SELECT TOP (1000) [KNR], [Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE Rueckmeldedatum >= '20230127 00:00:00' AND
Rueckmeldedatum < '20230128';

You should use this instead of LEFT or casting, then, if the index is available, your query can use this:
SELECT TOP (1000) [KNR]
,[Rueckmeldedatum]
FROM [Fertigung].[dbo].[Box1Auswertung]
WHERE Rueckmeldedatum >= '2023-01-27' AND Rueckmeldedatum < DATEADD(DAY, 1, '2023-01-27')
Also, make your query from the application parameterized.

Related

How can I generate a random timestamp appended to getdate() in SQL Server?

The following sql select generates the current date and time:
select
Getdate() AS DueDate
which looks like:
2021-02-06 10:16:35.340
I'd like to use getdate() (or an equivalent alternative) to continue getting the current date but I'd like to randomize the time component. I am having trouble finding a workable solution within a select statement.
Any suggestions?
here is another way if you need to have random time for each row:
SELECT
DATEADD(SECOND ,RAND(CHECKSUM(NEWID())) * 86400,CONVERT(datetime,CONVERT(varchar(8),GETDATE(),112)))
FROM tablename
You can simply add another DATEADD around your expression. For example, using INFORMATION_SCHEMA:
SELECT DATEADD(MILLISECOND, RAND(ROW_NUMBER()OVER(ORDER BY C.ORDINAL_POSITION)) * 10000000, GETDATE())
FROM INFORMATION_SCHEMA.COLUMNS AS C
You can play around with the RAND() and ROW_NUMBER() functions to get the result you want. If you have a primary key with lots of gaps, that helps to randomize.

PostgreSQL - where datetime <= YEAR-MONTH-DAY, ignore time

date column - datetime type.
My query is:
select * from car_db.car_parts where date::text LIKE '2018-07-06%'
How i select where date <= 'YEAR-MONTH-DAY', and ignore time?
I will be grateful...
First, Postgres doesn't offer a datetime type. The type is called timestamp. Also, Postgres has the very convenient function date_trunc(), so you can use that:
select *
from car_db.car_parts
where date_trunc('day', date) = '2018-07-06'::date;
However, this method -- or any method with a functional call or type conversion -- can affect index usage. I strongly recommend:
where date >= '2018-07-06'::date and
date < '2018-07-07'::date
Try the following. Also, you should not name your column as date.
select * from car_db.car_parts where cast("date" as date) < '2018-07-06'

SQL: How to use 'LIKE' with a date 'between'?

So, i´m trying to select rows between two dates.
In db, the dates also have time.
Therefor i need to use LIKE.
SQL
$query = "SELECT * FROM table WHERE date >= LIKE :selectedDateFrom AND <= LIKE :selectedDateTo";
$query_params = array(':selectedDateFrom' => $selectedDateFrom.="%", ':selectedDateTo' => $selectedDateTo.="%");
This one returns error!
How should it look like?
In db, the dates also have time.
Therefor i need to use LIKE.
No, you don't.
To select all date/times where the date component is between (from) and (to), inclusive, you can write it as
SELECT *
FROM table
WHERE date >= :selectedDateFrom
AND date < :selectedDateToPlusOne
(Note the < instead of <=, and set the second parameter to one day after the last day you want to include in your results.) This works even when the column includes times.
you can't use like with dates in SQL
SO use this:
$query = "SELECT * FROM table WHERE date >= :selectedDateFrom AND date <= :selectedDateTo";
You'd strip the time part from a datetime with DATE().
SELECT *
FROM mytable
WHERE date(mydate) >= :selectedDateFrom
AND date(mydate) <= :selectedDateTo;
Or with BETWEEN for better readability:
SELECT *
FROM mytable
WHERE date(mydate) BETWEEN :selectedDateFrom AND :selectedDateTo;

SQL Server: how to select records with specific date from datetime column

I have a table with one column dateX formatted as datetime and containing standard dates.
How can I select all records from this table where this dateX equals a certain date, e.g. May 9, 2014 ?
I tried the following, but this returns nothing even if I have several records with this date.
SELECT *
FROM dbo.LogRequests
WHERE (CONVERT(VARCHAR(10), dateX, 101) = '09/05/14')
Edit: In the database the above example looks as follows, using SQL 2012: 2014-05-09 00:00:00.000
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
For Perfect DateTime Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';
This will select all the data between the 2 dates

Using case statements with IsDate in a SQL where clause

I am trying to clean up the where clause statement in the following code:
SELECT
CONVERT(datetime, [UTC_Time_Stamp], 127) AS TimeStamp
FROM
Table
WHERE
CASE
WHEN ISDATE([UTC_Time_Stamp]) = 1
THEN CONVERT(datetime, [UTC_Time_Stamp], 127)
ELSE CAST('1/1/1900' AS datetime)
END > CAST('11/09/2012' AS datetime)
AND
CASE
WHEN ISDATE([UTC_Time_Stamp]) = 1
THEN CONVERT(datetime, [UTC_Time_Stamp], 127)
ELSE CAST('1/1/3000' AS datetime)
END < CAST('11/10/2012' as datetime)
ORDER BY
TimeStamp;
UTC_Time_Stamp is stored as a string and is sometimes null. I was previously running into a conversion error inside my where clause. I fixed the error following advice from this question here, but I feel like there has to be a simpler way to achieve the same result.
You need to do the conversion within a case statement. SQL is a descriptive language and does not guarantee the order of processing. So, a where clause does not necessarily happen before other processing, even when it is in a subquery or a CTE. However, SQL does guarantee the order of processing in a case statement (that contains no expressions with aggregation functions).
You can simplify your statement by using a subquery:
select TimeStamp
FROM (select t.*,
Case When ISDATE([UTC_Time_Stamp]) = 1 Then CONVERT(datetime, UTC_Time_Stamp, 127) end) as TimeStamp
from Table t
) t
WHERE coalesce(TimeStamp, cast('1/1/1900' as datetime)) > cast('11/09/2012' as datetime) and
coalesce(TimeStamp, cast('1/1/3000' as datetime)) < cast('11/10/2012' as datetime)
ORDER BY TimeStamp;
This does the conversion to TimeStamp, for valid values. You can then use the variable in the outer query.
I would also encourage you to get used to the ANSI standard format for dates (YYYYMMDD or YYYY-MM-DD) instead of ambiguous formats like '11/10/2012'. It may be clear to you that this means 2012-11-10 . . . or is that 2012-10-11 . . . but the format is ambiguous.
I like CTEs for this, or you could also do temp tables, table variables or an inline derived table like #Derek.
Basically, we're going to grab the proper datatype first, and then have a much easier time creating our query:
;with CTE as (
-- Bring back the column as datetime
select case when isdate(UTC_Time_Stamp) = 1 then cast(UTC_Time_Stamp as datetime) end as UTC_Time_Stamp
from [Table]
)
-- Simple select with the proper datatype
select convert(varchar(50), UTC_Time_Stamp, 127) as [TimeStamp]
from CTE
-- May still need gt and lt functionality
where UTC_Time_Stamp between cast('11/09/2012' as datetime) and cast('11/10/2012' as datetime)
It seems like you're using some arbitrarily small and large values for TimeStamp when you have non-dates, which is probably unnecessary given your comparison, so I've removed them.
Note that I am using the datetime datatype in the CTE and for the comparison, only converting it to a string for presentation.
Also note that between is inclusive, so you might need to go back to your separate > and < where clause.
It's easier to do something like this (using whatever convert/between clause in the predicate that you see fit):
SELECT CONVERT(datetime, [UTC_Time_Stamp], 127) as TimeStamp
FROM (
select [UTC_Time_Stamp]
from Table
WHERE ISDATE([UTC_Time_Stamp]) = 1
) a
WHERE
convert(datetime, [UTC_Time_Stamp], 127) between '11/9/2012' and '11/10/2012'
ORDER BY TimeStamp;
In this time for me this solves the problem of working with temporary table alias
or sub queries that can slow down the selection of millions of records.
select your_column
from your_table
where case when ISDATE(your_column) = 1
then Cast(your_column as date)
end Between '01/01/2016' and '01/01/2017'
order by your_column
Regards