Retrieve data from a certain date in SQLite - sql

I'm having a problem retrieving data from my SQLite database based on a certain month. I've looked around and saw people using strftime in a WHERE clause and I've tried this, but I'm getting mixed results. I'm either getting all the data in the database regardless of the date, or I'm getting no results but no errors or exceptions are appearing. I'm wondering if anyone would have a solution to this?
In my table I have a column called "Date" which is TEXT (string in my Model class) and I'm saving data in the format of dd/MM/yyyy, but after reading around I thought it was maybe the format I'm saving it as that was causing the problem so I tried with yyyy-MM-dd and dd-MM-yyyy also, but it doesn't solve the problem.
I've also tried different select statements to see if that helped. This returns all data rather than only data from January;
var selectStmt = "SELECT * FROM SleepTrackerModel WHERE strftime('%m', '01')";
SleepHistory = _dbHelper.Read<SleepTrackerModel>(selectStmt);
The following returns no data;
var selectStmt = "SELECT * FROM SleepTrackerModel WHERE strftime('%m', 'Date') = '01'";
SleepHistory = _dbHelper.Read<SleepTrackerModel>(selectStmt);
I've also tried listing all column names rather than using the *. I can't really find any help other than the way I've been using. SleepHistory is an ObservableCollection. What I'm trying to do is when the user clicks a button representing each month of the year, they'll be shown the data for that month.
Any help would be great. Thanks.

In SQL, Date is a column name, while 'Date' is just a string.
strftime('%m', 'Date') tries to interpret that string as a date value, which fails.
An SQL expression like this checks for dates in January:
... WHERE strftime('%m', Date) = '01'

Related

Access query with date BETWEEN breaks when using parameters

I have an SQL query in access that will grab all records where a calculated date is in between two values. It works fine if I hardcode date literals such as:
SELECT *
FROM Table
WHERE DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate])) Between #3/21/2021# And #3/27/2021#;
However I need to parametrize the the between dates so that they can be entered by a user like:
SELECT *
FROM Table
WHERE DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate])) Between [StartDate] And [EndDate];
However when I run the latter query and enter the exact same dates as the former, hard-coded one, it starts pulling records outside the between range. I've attempted to enter the dates like 3/21/2021 as well as date literals like #3/21/2021# and neither work. The latter doesn't pull anything at all.
I also have a form with a handful of text boxes using the short date format that let the user pick the dates for the query. It has the same issue of pulling back incorrect records. None of the records have any time component to my knowledge.
How can I get the date between to correctly work with user entered parameters?
Access doesn't know what data type your parameters are, so specify that in the query:
PARAMETERS
StartDate DateTime,
EndDate DateTime;
SELECT
*
FROM
Table
WHERE
DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate])) Between [StartDate] And [EndDate];
Parameters worked to filter a native field - not the calculated date. However, using CDate() function worked.
SELECT *
FROM Table
WHERE DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate]))
Between CDate([StartDate]) And CDate([EndDate]);
But before I remembered that, I tested calculating with inputs back to a birthdate range which also worked.
SELECT *
FROM Table
WHERE [BirthDate] Between DateAdd("d",60,DateAdd("yyyy",-65,[StartDate]))
And DateAdd("d",60,DateAdd("yyyy",-65,[EndDate]));

SQL Select Query on Date/Time column strange behavior

I am having an odd issue with a select statement in SQL Server Express, hopefully someone can shed some light on why I'm experiencing this behavior as well as the right way to do it.
When I run this query it returns exactly what I would expect:
SELECT
Action, TimeOccurred, UserName, IPv4From, ShareName,
FullFilePath, NewPathName, FromServer
FROM
File_System_Profiles
WHERE
Action LIKE '%create%'
AND (TimeOccurred >= '04/27/2017')
All those entries from 4/27 and anything after that.
When I run this query it returns 0 results which is extremely odd since there are entries for 4/27 in the previous query's results:
SELECT
Action, TimeOccurred, UserName, IPv4From, ShareName,
FullFilePath, NewPathName, FromServer
FROM
File_System_Profiles
WHERE
Action LIKE '%create%'
AND (TimeOccurred = '04/27/2017')
All I removed was the > between the = and the date and I get no results. I can clearly see when I run the first query that there are results where 04/27/2017 is the date that something occurred. If the first query didn't work I would assume there was a problem with my date format of MM/DD/YYYY and what is actually in the column YYYY-MM-DD HH:MM:SS but since the first one works it seems logical that the second one should.
It is a problem of the date format. As you mentioned, you are using Date format as "YYYY-MM-DD HH:MM:SS" so you should know that the value "04/27/2017" will be taken as "04/27/2017 00:00:00" when used in the comparison.
I assume that you have no record where the value in date field is "04/27/2017 00:00:00" and that is why when you use = operator, it does not match any record. However, the operator >= picks the records where hour:minute:second part of the date exist. As an example "04/27/2017 01:10:00" is greater than "04/27/2017 00:00:00" and therefore the > operator fetches those records.
Hope it helps.
First, always use ISO standard formats for comparison. Your code should look more like this:
where Action LIKE '%create%' AND
TimeOccurred = '2017-04-27'
Nauman explained the problem, which is the time component on TimeOccurred. You can solve this in various ways. One method is to convert to date. Something like this:
where Action LIKE '%create%' AND
cast(TimeOccurred as date) = '2017-04-27'
Depending on the database, the cast() might be replaced by trunc() or date_trunc() or something else.
However, I prefer this version:
where Action LIKE '%create%' AND
TimeOccurred >= '2017-04-27' AND
TimeOccurred < '2017-04-28'
It gets to the heart of the problem. And -- better yet -- SQL optimizers can make use of an index.

Comparing dates in SQL returns wrong records

I am trying to locate a date in database between two specific dates entered by user. Something like:
SELECT date FROM table WHERE date>=dateFrom AND date<=dateTO
I have the following table:
I have made a mistake saving the date as VARCHAR and now i have to do all the str_to_date and date_format as i am using phpMyAdmin. I somehow did it but i am facing this strange problem using this query:
SELECT date_format(str_to_date(data,'%d/%m/%Y'),'%d/%m/%Y') AS data FROM montaggio WHERE data>=date_format(str_to_date('29/08/2014','%d/%m/%Y'),'%d/%m/%Y')
The query would return to me only the date 19/08/2014 where as i expected it to return 01/09/2014. On the other hand if it enter the query
SELECT date_format(str_to_date(data,'%d/%m/%Y'),'%d/%m/%Y') AS data FROM montaggio WHERE data>=date_format(str_to_date('29/08/2014','%d/%m/%Y'),'%d/%m/%Y') AND data<=date_format(str_to_date('05/09/2014','%d/%m/%Y'),'%d/%m/%Y')
The query returns nothing.
I am using phpMyAdmin.
What am i missing here? Any help would be appreciated!
You do seem a bit confused. All the operations on dates should be done on the date data type. There is no need to convert things back to strings:
SELECT data
FROM montaggio
WHERE str_to_date(data, '%d/%m/%Y') >= str_to_date('29/08/2014', '%d/%m/%Y')
You seem to understand the real solution, which is to store dates/times in the database using the correct type. If you have to use strings for dates, then always stored them as YYYY-MM-DD, so comparisons and sorting will work correctly.

MsSQL - Return results within a date range

I was wondering if someone could help me out.
I need to return database results based on a date range, im using Classic ASP and MsSQL
My script gives me dates formatted as follows:
6/18/2014
The dates are saved in the database in the following format
12/24/2014 7:03:00 AM
What im wanting to do is something as follows:
SELECT * FROM table WHERE paid >= 6/18/2014 AND =< 6/28/2014
When i run that, im getting weird results as the dates arent formatted the same.
Can someone help me out.
Cheers,
you should put those two dates between single quotes like..
SELECT * FROM table WHERE paid BETWEEN '6/18/2014' and '6/28/2014'
EDIT:
you can use DATE_FORMAT(date,format) function to display date/time data in different formats.
here's some reference
http://www.w3schools.com/sql/func_date_format.asp
if its not typo
SELECT * FROM table WHERE paid BETWEEN '6/18/2014' AND '6/28/2014'
EDIT:-my database is storing it in the format yyyy-mm-dd
SELECT *
FROM table
WHERE DATE >= '2014-05-18'
AND DATE <= '2014-06-28'
and its working correctly
here is a reference
change the format according to your own database it will work

Does constructor DateTime take string or ONLY TIMESTAMP type as parameter?

I am working with SQLite SQL statement or Query.
So far, I was able to figure out some of things by asking stackoverflow question that can cause problem when executing such SQL Statement.
However, I still am not able to get any result?
Here is my SQL Query:
SELECT *
FROM Alarms
WHERE ALARMSTATE IN (0,1,2)
AND ALARMPRIORITY IN (0,1,2,3,4)
AND ALARMGROUP IN (0,1,2,3,4,5,6,7)
AND DateTime(ALARMTIME) BETWEEN datetime("2012-08-02 00:00:00")
AND datetime("2012-08-03 00:00:00")
ORDER BY ALARMTIME DESC
Here is my table as viewed within datagridView control:
As you can see, I have records from yesterdays and the day before in the table.
I corrected all the columns in question of their format such as my ALARMTIME, which is TEXT in data type. Still not getting any result, I decided to run the SQL statement right from within SQLite Administrator application as below. Surprisingly, I got the same result which is nothing or nill or null for dataset. However, SQLite Administrator showed me that DateTime accepts only TIMESTAMP as a parameter not TEXT. If so, my above SQL Statement won't work even if I have everything else correct. Am I correct in saying that?
Here is my answer. From what I understand, DATETIME supposed to take string or timestamp as a parameter, but in my case it doesn't work for me.
Since my column ALARMTIME is TEXT, I am able to query my table with the following SQL statement and retrieve dataset I am looking for.
SELECT *
FROM Alarms
WHERE ALARMSTATE IN (0,1,2)
AND ALARMPRIORITY IN (0,1,2,3,4)
AND ALARMGROUP IN (0,1,2,3,4,5,6,7)
AND ALARMTIME LIKE "2012/08/01%"
ORDER BY ALARMTIME DESC
I simply can't convert my ALARMTIME text into datetime type.
try using between 8/1 and 8/3 and you will get the ones for 8/2.
the way you have it should pull up the alarms in between the two times though
EDIT
can you change your ALARMTIME to a DATETIME format? Then you would be able to use the Between and you wouldn't have to convert the text to DATETIME.
if you Convert to DATETIME type you will have better flexibility in your query. it will be easier to use in the future as well.
I believe that DATETIME is a overloaded text type, so it should output text