SQL number Wildcard issue - sql

I'm trying to add a wildcard to my date select query so i only pull the day not time. I.e. 2021-03-11 17:54:30.123. I thought a number could be substituted for a #.
select AID, LocalCoAltIn,LocalCoAltOut,EventTime
from EXCDS.dbo.WKS_LOG_VIEW
where EventTime like '2021-03-11 ##:##:##:###';
My query is returning no values even though they are in the table. Thanks.

No! Don't use strings! One method is to convert to a date:
select AID, LocalCoAltIn,LocalCoAltOut,EventTime
from EXCDS.dbo.WKS_LOG_VIEW
where convert(date, EventTime) = '2021-03-11';
Another method is to use a range:
where EventTime >= '2021-03-11' and
EventTime < '2021-03-12'

The LIKE operator in most flavors of SQL only support _ and * wildcards (matching any one single, or multiple characters). Gordon has given you a better approach, but if you wanted to fix your current query on SQL Server you could try:
SELECT AID, LocalCoAltIn, LocalCoAltOut, EventTime
FROM EXCDS.dbo.WKS_LOG_VIEW
WHERE EventTime LIKE '2021-03-11 [0-9][0-9]:[0-9][0-9]:[0-9][0-9]:[0-9][0-9][0-9]';
SQL Server extended the LIKE operator to accept a few extra things, such as character classes. Here [0-9] inside LIKE would match any single digit.

Not sure that like operator would work for date as you want, but you still have few options.
Use DATEPART function to retrieve year\month\etc and compare it with exact value that you need
select AID, LocalCoAltIn,LocalCoAltOut,EventTime from EXCDS.dbo.WKS_LOG_VIEW where DATEPART(year,EventTime) = 2021 AND DATEPART(month,EventTime) = 3 AND DATEPART(day,EventTime = 11);
Or use Gordon Linoff suggestion if you dont care about exact date part and only need to compare entire date without time

Related

Sql Server Table date query showing incorrect result

I have a Sql server table which contains below Date values(4th october)
Now Below query is not showing any result
select
*
from [dbo].[TB_AUDIT] TBA
where TBA.ActionDate >= '10/01/2018' and TBA.ActionDate <= '10/04/2018' which is not correct.
But If I write
select
*
from [dbo].[TB_AUDIT] TBA
where TBA.ActionDate >= '10/01/2018' and TBA.ActionDate <= '10/05/2018' it is returning me all results.
What I am doing wrong.
There are two problems with this query. The first, is that it's using a localized string. To me, it looks like it's asking for rows between January and April. The unambiguous date format is YYYYMMDD. YYYY-MM-DD by itself may not work in SQL server as it's still affected by the language. The ODBC date literal, {d'YYYY-MM-DD'} also works unambiguously.
Second, the date parameters have no time which defaults to 00:00. The stored dates though have a time element which means they are outside the search range, even if the date parameter was recognized.
The query should change to :
select
*
from [dbo].[TB_AUDIT] TBA
where
cast(TBA.ActionDate as date) between '20181001' and '20181004'
or
cast(TBA.ActionDate as date) between {d'2018-10-01'} and {d'2018-10-04'}
Normally, applying a function to a field prevents the server from using any indexes. SQL Server is smart enough though to convert this to a query that covers the entire date, essentially similar to
where
TBA.ActionDate >='2018:10:01T00:00' and TBA.ActionDate <'2018-10-05T00:00:00'
When you don't specify a time component for a DATETIME, SQL Server defaults it to midnight. So in your first query, you're asking for all results <='2018-10-04T00:00:00.000'. All of the data points in your table are greater than '2018-10-04T00:00:00.000', so nothing is returned.
You want
TBA.ActionDate >= '2018-10-01T00:00:00.000' and TBA.ActionDate < '2018-10-05T00:00:00.000'`
Use properly formatted dates!
select *
from [dbo].[TB_AUDIT] TBA
where TBA.ActionDate >= '2018-10-01' and TBA.ActionDate <= '2018-10-04'
YYYY-MM-DD isn't just a good idea. It is the ISO standard for date formats, recognized by most databases.
when you just filter by the date, it is with regard to the time as per the standard.

SQL:how to perform select only on some characters from a column

I wanted to know how to perform the SQL SELECT operation on only a particular range of characters.
For example,I've got an SQL query:
SELECT date,score from feedback GROUP BY date
Now this date is of format yyyy/mm/dd.
So I wanted to strip the days or cut out the days from it and make it yyyy/mm, thereby selecting only 0-7 characters from the date.
I've searched everywhere for the answer but could not find anything.Could I maybe do something like this?
SELECT date(7),score from feedback GROUP BY date(7)
In MSQL you use LEFT other use substring
SELECT LEFT('abcdefg',2);
--
ab
So in your case
SELECT LEFT(date,7), score
FROM feedback
GROUP BY LEFT(date,7)
But again things will be much easier if you use a date field instead a text field.
Assuming that your date field is an actual date field (or even a datetime field) the following solution would work:
select left(convert(date ,getdate()),7) as Year_Month
Changing getdate() to your date field, it would look like:
select left(convert(date , feedback.date),7) as Year_Month
Both queries return the following:
2016-01

Is this query correct? SELECT s FROM Salesmen s WHERE s.dateOfEmployment < '26-06-2012' ORDER BY s.salepersonId ASC

I am not sure how to query for a date and I have tried it without the ' ' but it does not work. I was wonder if this is correct. Dateofemployment is a Date in the database and the date I put there is the date.
SELECT s
FROM Salesmen s
WHERE s.dateOfEmployment < '26-06-2012'
ORDER BY s.salepersonId ASC
Never assume there's a specific date format (dmy,ymd,mdy,etc.), always use the functions of your DBMS for writing dates instead of writing a string literal, e.g. TO_DATE in Oracle (and some others).
In best case you can use Standard SQL's date literals:
WHERE s.dateOfEmployment < DATE '2012-06-26'
Most DBMSes support it and there's no ambiguity because there's only one format allowed: yyyy-mm-dd
Your query is correct and you must put the two quotes since dateOfEmployment is a date. However, be careful with the position of the day and the month and make sure that your query does what you want.
When you leave out the quotes, you have a simple arithmetic expression: 26 - 06 - 2012. This is equal to something like -1992. That is an integer and not a date, so presumably the comparison will either generate an error or at least never return true.
When putting dates in queries, you should use ISO standard format: YYYY-MM-DD. Most databases will accept the following:
WHERE s.dateOfEmployment < '2012-06-26'
In Oracle, you need to add date before the constant.

regular expression not working on the datetime column

The date in my table looks like 2010-06-16 00:00:00.000
When I use the below regular expression, no rows get selected.
select mydate from mytable where mydate like '2010%'
However, when I use this one, rows do get selected correctly.
select mydate from mytable where mydate like '%2010%'
So, I thought that probably leading white spaces are getting added. To take those into account, I used the below query. But this doesn't work either.
select mydate from mytable where LTRIM(RTRIM(mydate)) like '2010%'
Since the first one works, it means, that there is something before the 2010? What else apart from white spaces, could it be? I tried pasting it onto a text file, and don't see anything.
If the datatype is Datetime you should use Year() function to filter the rows instead of like. You should not use like operator to filter the data from Datetime type.
If the datatype is Datetime then you won't be having leading or trailing spaces.
You do have appropriate Date functions in Sql Server use those to filter the rows.
select mydate from mytable where year(mydate) = 2010
or even Datepart
select mydate from mytable where Datepart(YYYY,mydate) = 2010
You have to convert datetime that first in varchar to use like
select mydate from mytable
WHERE CONVERT(VARCHAR(10),mydate,120) like '2010%'
DEMO
You probably should use just date range fetches, for example
select mydate from mytable where mydate >= '20100101' and mydate < '20110101'
Using functions for the column (e.g. year(mydate)) is not a good idea because then indexes can't be used. Using 'between' can also cause problems with datetime columns because the time part can cause you to accidentally leave out rows.
The reason you found something with your search is probably due to typecasting the date into varchar before comparison, and format is such that the year is at the end, but please don't use that.

Select data in date format

I have a query in which I want to select data from a column where the data is a date. The problem is that the data is a mix of text and dates.
This bit of SQL only returns the longest text field:
SELECT MAX(field_value)
Where the date does occur, it is always in the format xx/xx/xxxx
I'm trying to select the most recent date.
I'm using MS SQL.
Can anyone help?
Try this using ISDATE and CONVERT:
SELECT MAX(CONVERT(DateTime, MaybeDate))
FROM (
SELECT MaybeDate
FROM MyTable
WHERE ISDATE(MaybeDate) = 1) T
You could also use MAX(CAST(MaybeDate AS DateTime)). I got in the (maybe bad?) habit of using CONVERT years ago and have stuck with it.
To do this without a conversion error:
select max(case when isdate(col) = 1 then cast(col as date) end) -- or use convert()
from . . .
The SQL statement does not specify the order of operations. So, even including a where clause in a subquery will not guarantee that only dates get converted. In fact, the SQL Server optimizer is "smart" enough to do the conversion when the data is brought in and then do the filtering afterwards.
The only operation that guarantees sequencing of operations is the case statement, and there are even exceptions to that.
Another solution would be using PATINDEX in WHERE clause.
SELECT PATINDEX('[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]', field_value)
Problem with this approach is you really are not sure if something is date (e.g. 99/99/9999 is not date).
And problem with IS_DATE is it depends on configuration (e.g. DATEFORMAT).
So, use an appropriate option.