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

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

Related

SQL number Wildcard issue

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

Strange behaviour of Sql query with between operator

There is this strange error in sql query.
The query is something like this.
select * from student where dob between '20150820' and '20150828'
But in the database the column of dob is varchar(14) and is in yyyyMMddhhmmss format,Say my data in the row is (20150827142545).If i fire the above query it should not retrive any rows as i have mentioned yyyyMMdd format in the query.But it retrives the row with yesterday date (i.e 20150827112535) and it cannot get the records with today's date (i.e 20150828144532)
Why is this happening??
Thanks for the help in advance
You can try like this:
select * from student
where convert(date,LEFT(dob,8)) between
convert(date'20150820') and convert(date,'20150828'))
Also as others have commented you need to store your date as Date instead of varchar to avoid such problems in future.
As already mentioned you would need to use the correct date type to have between behave properly.
select *
from student
where convert(date,LEFT(dob,8)) between '20150820' and '20150828'
Sidenote: You don't have to explicitly convert your two dates from text as this will be done implicitly as long as you use an unambiguous date representation, i.e. the ISO standard 'YYYYMMDD' or 'YYYY-MM-DD'. Of course if you're holding the values in variables then use date | datetime datatype
declare #startdate date
declare #enddate date
select *
from student
where convert(date,LEFT(dob,8)) between #startdate and #enddate
Sidenote 2: Performing the functions on your table dob column would prevent any indexes on that column from being used to their full potential in your execution plan and may result in slower execution, if you can, define the correct data type for the table dob column or use a persistent computed column or materialised view if your performance is a real issue.
Sidenote 3: If you need to maintain the time portion in your data i.e. date and time of birth, use the following to ensure all records are captured;
select *
from student
where
convert(date,LEFT(dob,8)) >= '20150820'
and convert(date,LEFT(dob,8)) < dateadd(d,1,'20150828')
All you have to do is to convert first the string to date.
select *
from student
where dob between convert(date, '20150820') and convert(date, '20150828')
Why is this happening?
The comparison is executed from left to right and the order of characters is determined by the codepage in use.
Sort Order
Sort order specifies the way that data values are sorted, affecting
the results of data comparison. The sorting of data is accomplished
through collations, and it can be optimized using indexes.
https://msdn.microsoft.com/en-us/library/ms143726.aspx
There are problems with between in T-SQL.
But if you want a fast answer convert to date first and use >= <= or even datediff to compare - maybe write a between function yourself if you want the easy use like between and no care about begin and start times ...
What do BETWEEN and the devil have in common?

Find record between two dates

When I write below query it gives record .
SELECT [srno],[order_no],[order_date],[supplier_name],[item_code],[item_name],[quntity]
FROM [first].[dbo].[Purchase_Order]
WHERE order_date BETWEEN '22/04/2015' AND '4/05/2015'
In this query if I don't add 0 in '4/05/2015' it returns record.
But when I add 0 to the date i.e. '04/05/2015' it doesn't give any records.
SELECT [srno],[order_no],[order_date],[supplier_name],[item_code],[item_name],[quntity]
FROM [first].[dbo].[Purchase_Order]
WHERE order_date BETWEEN '22/04/2015' AND '04/05/2015'
The reason it's not working because SQL is trying to do a string comparison because both your types are string types, But what you really want to do a date comparison.
You should do something like this. Since you only need date part you can strip off the time and use style 103 for your format dd/mm/yyyy.
WHERE CONVERT(DATETIME,LEFT(order_date,10),103)
BETWEEN CONVERT(DATETIME,'20150422') AND CONVERT(DATETIME,'20150504')
Alternately you can use this as well if your order_date has dates like this 5/4/2015 03:20:24PM
WHERE CONVERT(DATETIME,LEFT(order_Date,CHARINDEX(' ', order_Date) - 1),103)
BETWEEN CONVERT(DATETIME,'20150422') AND CONVERT(DATETIME,'20150504')
A long term solution is to change your column order_date to DATE/DATETIME
It Better to Cast it to date rather than depend on IMPLICIT conversion
SELECT [srno],[order_no],[order_date],[supplier_name],[item_code],
[item_name],[quntity] FROM [first].[dbo].[Purchase_Order] where
convert(date,order_date,105) BETWEEN cast('22/04/2015' as Date) AND cast('04/05/2015' as date)

SQL query doesnt bring out results when queried using date

I see that a table has the data value as 18-May-2012. But when I query looking for the same date using the below query, no results are available.
Select Submit_Dt From Siebel.S_Order_Dtl
where submit_dt = '18-May-2012'
Could you help me sort this issue?
You need to convert string date into date with TO_DATE() function.
Also you need to take into account that your date might contain hours/minutes/seconds. In order to handle this you need to truncate submit_dt column.
In your case it would look like this:
Select Submit_Dt From Siebel.S_Order_Dtl
where TRUNC(submit_dt) = TO_DATE('18-May-2012','dd-MON-yyyy')
Try to convert the date to date format using to_date as below
Select Submit_Dt From Siebel.S_Order_Dtl
where submit_dt = to_date('18-May-2012','DD-MON-YYYY')

how to delete the records which is inserted 1 day ago

I dont have proper timestamp in table; is it possible to delete 1 day old logs even now?
I have a column name as SESSION_IN which is basically a VARCHAR datatype, and the value will be like
2013-10-15 02:10:27.883;1591537355
is there any way to trim the number after ; and is it possible to compare with "sysdate" identifier?
This SP should compare all the session IDs with current datetime and it should delete if it is older then 1 day.
You can igonre time part and convert date into required format somthing like this
SYSDATE - to_date('date_col','YYYY-DD-MM')
then you can perform operations.
Use the Substring function to extract the datetime portion from the record, then use convert to datetime to cast it to datetime, and then finally use datediff to check if it was inserted yesterday. Use all these caluses in a
DELETE FROM table
WHERE ___ query
For Oracle you could use something like this:
SELECT
TRUNC(to_timestamp(SUBSTR('2013-10-15 02:10:27.883;1591537355',1,
(
SELECT
instr('2013-10-15 02:10:27.883;1591537355', ';')-1
FROM
dual
)
), 'YYYY-MM-DD HH:MI:SS.FF'))
FROM
dual;
Which gives you just the date portion of your input string. Just subtract the amount of days you want to log at the end.
Hope following query helps you:
Select Convert(Datetime,Substring('2013-10-15 02:10:27.883;1591537355',1,23)), DateDiff(dd,Convert(Datetime,Substring('2013-10-15 02:10:27.883;1591537355',1,23)),Getdate())