Specifying custom date range in SQL query - sql

I want to write a query where in I need to specify the custom range (instead of hardcoded date range) for date starting from the order day. In the table being used, I have the date for the order.
As of now I have hardcoded the date range like:
where owh.order_day between TO_DATE('2016/07/15','YYYY/MM/DD') and TO_DATE('2017/01/17','YYYY/MM/DD')
where order_day is a date.
But rather I want something like:
where owh.order_day between TO_DATE(owh.order_day - 1,'YYYY/MM/DD') and TO_DATE(owh.order_day +3,'YYYY/MM/DD')
I am doing "-1" as it's "between", so it will take from order_day - order_day+2
For example, If the order_day is: "17/01/2016" then I want the condition to be where the date range is dynamically calculated as: "16/01/2016 - 20/01/2016" .
Is something like this possible? If yes, how can we achieve in in SQL??
The DB in question is Oracle
Any leads appreciated

Since you have not told us which RDBMS you are using, and since you are saying "any leads appreciated", I suppose we are free to give an answer for any RDBMS. The following will work for MySQL:
BETWEEN DATE_SUB( somedate, INTERVAL 1 DAY ) AND DATE_ADD( somedate, INTERVAL 1 DAY )
(source: https://www.tutorialspoint.com/sql/sql-date-functions.htm#function_date-add)

Related

Timestamp to date in SQL

Here is what I did:
Select count(check_id)
From Checks
Where timestamp::date > '2012-07-31'
Group by 1
Is it right to do it like I did or is there a better way? Should/could I have used the DateDIFF function in my WHERE clause? Something like: DATEDIFF(day, timestamp, '2012/07/31') > 0
Also, I need to figure out how I'd calculate the total rate of acceptance for this
time period? Can anyone provide their expertise with this?
Is it right to do it like I did or is there a better way?
Using a cast like that is a perfectly valid way to convert a timestamp to a date (I don't understand the reference to the non-existing datediff though - why would adding anything to a timestamp change it)
However, the cast has one drawback: if there is an index on the column "timestamp" it won't be used.
But as you just want a range after a certain date, there is no reason to cast the column to begin with.
The following will achieve the same thing as your query, but can make use of an index on the column "timestamp" in case there is one and using it is considered beneficial by the optimizer.
Select count(distinct check_id)
From Checks
Where "timestamp" > date '2012-07-31' + 1
Note the + 1 which selects the day after, otherwise the query would include rows that are on that date but after midnight.
I removed the unnecessary group by from your query.
If you want to get a count per day, then you will need to include the day in the SELECT list. In that case casting is a good way to do it:
Select "timestamp"::date, count(distinct check_id)
From Checks
Where "timestamp" > date '2012-07-31' + 1
group by "timestamp"::date

MS Access - DateSerial?

I apologize in advance because I don't know how to properly ask this question.
I am using access to pull in data from several tables and want to filter/query the data by the first 10 days in any month, in any year. I understand that I could use operators to say something like:
=#1/1/2017# and <=#1/10/2017 Or >=#2/1/2017# and <=#2/10/2017# Or....on and on
But that would be a long expression. Is there something easy I could do using DateSerial, or something else?
The Day Function Returns a Variant (Integer) specifying a whole number between 1 and 31, inclusive, representing the day of the month.
So use that function in your query's WHERE clause ...
WHERE Day(YourDateField) BETWEEN 1 AND 10
Use this:
SELECT *
FROM [MyTable]
WHERE DatePart("d", [MyColumn]) > DatePart("d", #01/01/2018#)
AND DatePart("d", [MyColumn]) < DatePart("d", #01/11/2018#)

Postgresql query between date ranges

I am trying to query my postgresql db to return results where a date is in certain month and year. In other words I would like all the values for a month-year.
The only way i've been able to do it so far is like this:
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN '2014-02-01' AND '2014-02-28'
Problem with this is that I have to calculate the first date and last date before querying the table. Is there a simpler way to do this?
Thanks
With dates (and times) many things become simpler if you use >= start AND < end.
For example:
SELECT
user_id
FROM
user_logs
WHERE
login_date >= '2014-02-01'
AND login_date < '2014-03-01'
In this case you still need to calculate the start date of the month you need, but that should be straight forward in any number of ways.
The end date is also simplified; just add exactly one month. No messing about with 28th, 30th, 31st, etc.
This structure also has the advantage of being able to maintain use of indexes.
Many people may suggest a form such as the following, but they do not use indexes:
WHERE
DATEPART('year', login_date) = 2014
AND DATEPART('month', login_date) = 2
This involves calculating the conditions for every single row in the table (a scan) and not using index to find the range of rows that will match (a range-seek).
From PostreSQL 9.2 Range Types are supported. So you can write this like:
SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange #> login_date
this should be more efficient than the string comparison
Just in case somebody land here... since 8.1 you can simply use:
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'
From the docs:
BETWEEN SYMMETRIC is the same as BETWEEN except there is no
requirement that the argument to the left of AND be less than or equal
to the argument on the right. If it is not, those two arguments are
automatically swapped, so that a nonempty range is always implied.
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'
Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.
Read the documentation.
http://www.postgresql.org/docs/9.1/static/functions-datetime.html
I used a query like that:
WHERE
(
date_trunc('day',table1.date_eval) = '2015-02-09'
)
or
WHERE(date_trunc('day',table1.date_eval) >='2015-02-09'AND date_trunc('day',table1.date_eval) <'2015-02-09')

how to get data whose expired within 45 days..?

HI all,
i have one sql table and field for that table is
id
name
expireydate
Now i want only those record which one is expired within 45 days or 30 days.
how can i do with sql query .?
I have not much more exp with sql .
Thanks in advance,
If you are using mysql then try DATEDIFF.
for 45 days
select * from `table` where DATEDIFF(now(),expireydate)<=45;
for 30 days
select * from `table` where DATEDIFF(now(),expireydate)<=30;
In oracle - will do the trick instead of datediff and SYSDATE instead of now().[not sure]
In sql server DateDiff is quite different you have to provide unit in which difference to be taken out from 2 dates.
DATEDIFF(datepart,startdate,enddate)
to get current date try one of this: CURRENT_TIMESTAMP or GETDATE() or {fn NOW()}
You can use a simple SELECT * FROM yourtable WHERE expireydate < "some formula calculating today+30 or 45 days".
Simple comparison will work there, the tricky part is to write this last bit concerning the date you want to compare to. It'll depend of your environment and how you stored the "expireydate" in the database.
Try Below:-
SELECT * FROM MYTABLE WHERE (expireydate in days) < ((CURRENTDATE in days)+ 45)
Do not execute directly! Depending of your database, way of obtaining a date in days will be different. Go look at your database manual or please precise what is your database.

mysql return rows matching year month

How would I go about doing a query that returns results of all rows that contain dates for current year and month at the time of query.
Timestamps for each row are formated as such: yyyy-mm-dd
I know it probably has something to do with the date function and that I must somehow set a special parameter to make it spit out like such: yyyy-mm-%%.
Setting days to be wild card character would do the trick but I can't seem to figure it out how to do it.
Here is a link to for quick reference to date-time functions in mysql:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
Thanks
I think EXTRACT is the function you are looking for:
SELECT * FROM table
WHERE EXTRACT(YEAR_MONTH FROM timestamp_field) = EXTRACT(YEAR_MONTH FROM NOW())
you could extract the year and month using a function, but that will not be able to use an index.
if you want scalable performance, you need to do this:
SELECT *
FROM myTable
WHERE some_date_column BETWEEN '2009-01-01' AND '2009-01-31'
select * from someTable where year(myDt) = 2009 and month(myDt) = 9 and day(myDt) = 12