SQLite query to compare dates - date

I have two text columns (valid_from and valid_to) in a table (history) in SQLite database in which I am storing date in dd/MM/yyyy format.
Now I am running following query to fetch all the records between June 1, 2018 to June 30, 2018, but I am not getting any results:
Try 1:
SELECT * FROM history WHERE valid_from >= datetime('01/06/2018') AND valid_to <= datetime('30/06/2018');
Try 2:
SELECT * FROM history WHERE cast(strftime('%Y%m%d', valid_from) as integer) >= cast(strftime('%Y%m%d', '01/06/2018') as integer) AND cast(strftime('%Y%m%d', valid_to) as integer) <= cast(strftime('%Y%m%d', '30/06/2018') as integer);
Nothing fetched the records. Am I missing something?

You should always store your date information in SQLite in an ISO format, where the year comes before the month, which comes before the day. The reason for this is that in SQLite dates are just stored as plain text, and your current format won't sort properly. As a workaround, you may try the following query:
SELECT *
FROM history
WHERE
SUBSTR(valid_from, 7, 4) || '/' || SUBSTR(valid_from, 4, 2) ||
'/' || SUBSTR(valid_from, 1, 2)
BETWEEN '2018/06/01' AND '2018/06/30';
Here we are just building the correct date format for each date. But again, the best long term solution is to fix your date data.

Related

how can i get the all data from postgresql thats from the current day, between the hours of 00:00:00 and 11:59:59?

very new to the backend as well as all things postgresql, at the moment all ive been able to do is
SELECT * FROM nutrition WHERE timestamp >= (extract(epoch from now())::bigint * 1000) - 86400000 AND timestamp <= (extract(epoch from now())::bigint * 1000) + 86400000
in the frontend using js, im using Date.now() to store the timestamp in the DB.
timestamp is a column in my db thats logging the unix time in bigint format in which the food was logged. I want to get all the data from the current day from the hours beteen 12 AM midnight, and 11:59 PM. thanks.
for example, the last item i logged was last night at 10pm (1663995295337 UNIX time) so the data shouldnt include it.
show timezone returns;
America/Los_Angeles
Solution below --------------------------------------------------------------------
const today = new Date();
const beginningOfDay = today.setUTCHours(7, 0, 0, 0);
const endOfDay = today.setUTCHours(30, 59, 59, 99);
switch (method) {
case "GET":
try {
const text = `
select
*
from
nutrition
where
timestamp
between ${beginningOfDay} and ${endOfDay}`
this was the solution i was looking for, thanks for the help. sorry if i wasnt descriptive enough.
Assuming that by Unix time you mean epoch.
select extract(epoch from now());
extract
-------------------
1664038032.392004
select to_timestamp(1664038032.392004);
to_timestamp
--------------------------------
09/24/2022 09:47:12.392004 PDT
select
*
from
some_table
where
to_timestamp(1664038032.392004)
between
current_date + '00:00:00'::time AND current_date + '23:59:59'::time
UPDATE
Using timestamptz field in Postgres and an ISO datetime string from Javascript in order to properly deal with time zone.
create table tsz_test(id integer, tsz_fld timestamptz);
--In Web frontend today = new Date().toISOString(); "2022-09-24T20:57:05.830Z"
insert into
tsz_test
values (1, '2022-09-24T20:57:05.830Z'), (2, '2022-09-25T08:57:05.830Z');
select * from tsz_test ;
id | tsz_fld
----+----------------------------
1 | 09/24/2022 13:57:05.83 PDT
2 | 09/25/2022 01:57:05.83 PDT
--Borrowing from #a_horse_with_no_name answer
select * from tsz_test where tsz_fld::date = '09/24/2022'::date;
id | tsz_fld
----+----------------------------
1 | 09/24/2022 13:57:05.83 PDT
You can convert your "unix timestamp" to a date, then compare it with "today":
where to_timestamp("timestamp")::date = current_date
This assumes that your column named "timestamp" is not really a timestamp
If the column doesn't actually store seconds (which would be a unix epoch), but milliseconds you need to_timestamp("timestamp"/1000)::date instead (another source of problems that wouldn't exist if you had used a proper timestamptz or at least timestamp data type).

SAS Proc SQL function in where clause for only current week

I have some data in week-date-time format ie 14dec2020 00:00:00:0000. I am using SAS and a proc sql query
This data contains many weeks worth of data but i was curious if theres in way to only pull data relevant to only current week? IE today is 17dec2020 so i would want to only pull data for the week of 14dec2020. if today was 22dec2020 then i would want it to pull data for the week of 21dec2020.
Here is one of the many queries i have tried.
data have;
today = today();
wkday = weekday(today);
start = today - (wkday - 1);
end = today + (7 - wkday);
length cstart cend $30;
cstart = put(start, date9.) || ' 00:00:00.0000' ;
cend = put(end, date9.) || ' 00:00:00.0000' ;
call symput('start', cstart);
call symput('end', cend);
run;
Proc Sql;
connect to odbc (environment=x user=y p=z);
create table basic.curweek as select * from connection to odbc
(select year, month, week, store, sales, SKU
from datatable
where (&start. <= week <= &end.)
order by sku);
disconnect from odbc;
quit;
Thanks to the help of the great people below i have gotten to this state. But am still facing some syntax errors.
Any help here would be greatly appreciated!!
Use intnx() to align both the datetime of interest and today's datetime to the start of the week.
proc sql;
create table want as
select *
from table
where intnx('dtweek', date, 0, 'B') = intnx('dtweek', datetime(), 0, 'B')
;
quit;
As others have pointed out - if you are using SQL pass-thru, you need to use date functions that exist in your "flavor" of SQL. SAS specific functions will not work, and in particular SAS function "today()" has no meaning in the SQL you are working with.
The approach I would take is:
in a SAS datastep - get today's date
use today's date to calculate beginning and end of the week
convert beginning/end dates to character strings
(string will depend on how dates are formatted in your sql database - date or datetime)
use character strings to create macro variables
feed macro variables into sql pass-thru query to subset dates wanted
Below is some example code. It might not get you all the way there, but could give you some more ideas to try.
data have;
today = today(); *** TODAYs DATE ***;
wkday = weekday(today); *** WEEK DAY NUMBER FOR TODAY, POSSIBLE VALUES ARE 1-7 ***;
start = today - (wkday - 1); *** CALCULATE SUNDAY ***;
end = today + (7 - wkday); *** CALCULATE SATURDAY ***;
*** UNCOMMENT AND USE BELOW IF WEEK START/END IS MON-FRI ***;
*start = today - (wkday - 2); *** CALCULATE MONDAY ***;
*end = today + (6 - wkday); *** CALCULATE FRIDAY ***;
*** REPRESENT DATES AS DATE-TIME CHARACTER STRING - SURROUNDED BY SINGLE QUOTES ***;
cstart = "'" || put(start, date9.) || ' 00:00:00.0000' || "'";
cend = "'" || put(end, date9.) || ' 00:00:00.0000' || "'";
*** USE CHARACTER VARIABLES TO CREATE MACRO VARIABLES ***;
call symput('start', cstart);
call symput('end', cend);
run;
*** IN SQL PASS-THRU, USE MACRO VARIABLES IN WHERE STATEMENT TO SUBSET ONE WEEK ***;
Proc Sql
connect to odbc (environment=x user=y p=z);
create table basic.curweek as select * from connection to odbc
(select year, month, week, store, sales, SKU
from datatable
where (&start. <= week and week <= &end.)
order by sku);
disconnect from odbc;
quit;

Compare YEAR value in WHERE clause

Using SQL Server 2008 R2 I am trying to compare year values in a where clause like so:
AND year(convert(date, (LEFT(formAuditLog, 10)), 104 )) = year(GETDATE())
But I get this error:
Conversion failed when converting date and/or time from character string
I have also tried this but get that same result:
AND cast(year(convert(date, (LEFT(formAuditLog, 10)), 104 )) as int) = cast(year(GETDATE()) AS INT)
Note - formAuditLog is a string. I am getting the first 10 chars which is always mm/dd/yyyy (I have triple checked this) so I convert as a date and then get the year of this. Based on this info, should I not be able to do this comparison?
Thanks in advance
Added :
Note - When I put this in a select it works. I get the year part of the date I am expecting:
select top 10 year(convert(date, (LEFT(formAuditLog, 10)), 104 )) , * from myTableName
So why would this be allowed in a select but fail in a where clause?
Added : For completeness, there is actually nothing wrong with either of the two SQL bits at the top of this post. As mentioned in the accepted post comment below, it was a leading quote in one formAuditLog records that cause it to fall over
If your formAuditLog column is a string like you suggest and the left 10 characters is equivalent to a date format MM/DD/YYYY. This should have worked for you:
create table mytableName (id int, formAuditLog varchar(50));
insert into mytableName values
(1,'01/02/20141203'),
(2,'01/03/20151203'),
(3,'05/01/20151203');
select
id,
formAuditLog,
cast(left(formAuditLog,10) as date) as DateField,
year(cast(left(formAuditLog,10) as date)) as yearfield
from mytableName
where year(cast(left(formAuditLog,10) as date)) = year(cast(getdate() as date));
Code Demo
for sql server 2008, this should be your where condition
and year(GETDATE()) = case when isdate(LEFT(formAuditLog, 10))=1 then year(convert(date, (LEFT(formAuditLog, 10)))) else 99999 end
For sql server 2012..
AND year( try_parse(LEFT(formAuditLog, 10) as date) ) = year(GETDATE())

Problem when extracting year and week number from string in PSQL

Let's say that I have a range of SQL tables that are named name_YYYY_WW where YYYY = year and WW = week number. If I call upon a function that guides a user defined date to the right table.
If the date entered is "20110101":
SELECT EXTRACT (WEEK FROM DATE '20110101') returns 52 and
SELECT EXTRACT (YEAR FROM DATE '20110101') returns 2011.
While is nothing wrong with these results I want "20110101" to either point to table name_2010_52 or name_2011_01, not name_2011_52 as it does now when I concanate the results to form the query for the table.
Any elegant solutions to this problem?
The function to_char() will allow you to format a date or timestamp to output correct the iso week and iso year.
SELECT to_char('2011-01-01'::date, 'IYYY_IW') as iso_year_week;
will produce:
iso_year_week
---------------
2010_52
(1 row)
You could use a CASE:
WITH sub(field) AS (
SELECT CAST('20110101' AS date) -- just to test
)
SELECT
CASE
WHEN EXTRACT (WEEK FROM field ) > 1 AND EXTRACT (MONTH FROM field) = 1 AND EXTRACT (DAY FROM field) < 3 THEN 1
ELSE
EXTRACT (WEEK FROM field)
END
FROM
sub;

How do I format a date in a SQL Where clause?

I have a .NET 2010 app that bangs against a SQL db. On the app side, a user can search on Begin date and End Date. Bot of these are just Month + Year. I then format them so they are complete dates. So when they go to the stored proc they'll look like this...
Begin Date: 1/1/2011
End Date: 5/31/2011
But the date in the db is broken up into 3 int fields, Month,Day & Year, ...of which Day may or may not be filled in (0 if not). It would be ok for this to always default to one when running this query. So if the values in the db were Month=3, Day=0 Year=2011 I would like the sql statement to render as
Where FORMATTEDDATEHERE between '1/1/2011' and '5/31/2011'
I just can't figure out how to format sql fields in a where clause.
Did you try something like
WHERE CONVERT(DATETIME,
CONVERT(VARCHAR(4), [c_year]) + '/'
+ CONVERT(VARCHAR(2), [c_month]) + '/'
+ CONVERT(VARCHAR(2), [c_day]))
BETWEEN '2011/1/1' AND '2011/5/31'
Hope it helps
you could build the date using datadd functions within the WHERE clause EG.
SELECT ...
WHERE DATEADD(Day, field_days-1, DATEADD(Month, field_months-1, DATEADD(Year, field_years-1900, 0))) BETWEEN '1/1/2011' AND '5/31/2011'
Just replace field_days, field_months, field_years with the int fields on the table for days, months and year. This will return all records within the date range.
Is this what you require?
WHERE CAST(Year AS varchar) + RIGHT(100 + Month, 2) +
RIGHT(100 + COALESCE(NULLIF(Day, 0), 1), 2) BETWEEN ...