How to select week data (more precisely, last 7 days data) from the current date in the fastest way as I have millions or rows in the table. I have a time stamp of created_date in sql table.
I have tried this
SELECT Created_Date
FROM Table_Name
WHERE Created_Date >= DATEADD(day,-7, GETDATE())
I have two question:
Is this query is correct?
Is this is the fastest way to get the last seven day data from a table having millions of rows ?
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
to select records for the last 7 days
SELECT * FROM [TableName]
WHERE Created_Date >= DATEADD(day, -7, GETDATE())
to select records for the current week
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM [TableName]
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 8 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
if you want to select records for last week instead of the last 7 days
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM [TableName]
WHERE CreatedDate >= DATEADD(day, -(DATEPART(WEEKDAY, GETDATE()) + 6), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
The query is correct
2A. As far as last seven days have much less rows than whole table an index can help
2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size
Related
I'm trying to query for users with birthdays falling between a given date range.
The users table stores birthdays in a pair of int columns: dob_month (1 to 12) and dob_day (1 to 31). The date range I'm querying with is a pair of date-time strings, including the year.
Here's what I've got so far:
SELECT *
FROM `users`
WHERE DATE(CONCAT_WS('-', 2023, dob_month, dob_day)) BETWEEN '2023-03-01 00:00:00' AND '2023-03-31 23:59:59'
However, this doesn't work when the date range spans multiple years.
For example, 2023-12-15 00:00:00 and 2024-01-10 23:59:59.
How can I work around this? Thanks!
You can solve this by joining to a set of rows with individual dates.
Suppose you had another table called dates which had one row per day, spanning the whole range you need.
mysql> create table dates (date date primary key);
mysql> insert into dates(date)
with recursive cte as (
select '2023-01-01' as date
union
select cte.date + interval 1 day from cte where cte.date < '2025-01-01'
)
select * from cte;
Query OK, 732 rows affected (0.01 sec)
Now it's easy to query a subset of dates:
mysql> SELECT date
FROM dates
WHERE dates.date BETWEEN '2023-12-15 00:00:00' AND '2024-01-10 23:59:59';
...
27 rows in set (0.00 sec)
We create a sample user with a dob of January 3.
mysql> create table users ( id serial primary key, dob_month tinyint, dob_day tinyint);
mysql> insert into users set dob_month = 1, dob_day = 3;
You can join your users table to that subset of dates where the month and day match.
mysql> SELECT date FROM users JOIN dates
ON dob_month = MONTH(date) AND dob_day = DAY(date)
WHERE dates.date BETWEEN '2023-12-15 00:00:00' AND '2024-01-10 23:59:59';
+------------+
| date |
+------------+
| 2024-01-03 |
+------------+
In the below code, the logic is to convert dob_month and dob_day into a date and then do the comparison using BETWEEN operator.
Now the year value used for date conversion is based on the below logic :
Use the year value the same as that of "from date". If the date is less than the "from date", then push it to the next year. Use BETWEEN operator to check if the date is within the given date range. This logic is applied because to use BETWEEN operator the date has to be greater than or equal to the "from date" keeping month and day values intact.
Note Date_add(Date_add(Makedate(some_year_value, 1), INTERVAL (dob_month)-1 month), INTERVAL (dob_day)-1 day) is repeated 3 times. It is for creating a date out of the year, month, and day values.
SET #fromdate = date('2023-09-01 00:00:00');
SET #fromyear = year(#fromdate);
SET #todate = date('2024-02-28 23:59:59');
CREATE TABLE users
(
id SERIAL PRIMARY KEY,
dob_month TINYINT,
dob_day TINYINT
);
INSERT INTO users
SET dob_month = 2,
dob_day = 1;
SELECT *
FROM users
WHERE CASE
WHEN Date_add(Date_add(Makedate(#fromyear, 1),
INTERVAL (dob_month)-1 month),
INTERVAL (dob_day)-1 day) < #fromdate THEN
Date_add(Date_add(Makedate(#fromyear + 1, 1),
INTERVAL (dob_month)-1 month),
INTERVAL (dob_day)-1 day) BETWEEN #fromdate AND #todate
ELSE Date_add(Date_add(Makedate(#fromyear, 1),
INTERVAL (dob_month)-1 month),
INTERVAL (dob_day)-1 day) BETWEEN #fromdate AND #todate
end;
Psuedo code for understanding the crux:
SELECT *
FROM users
WHERE CASE
WHEN Date(from_date_year,dob_month,dob_day) < #fromdate THEN
Date(from_date_year,dob_month,dob_day) BETWEEN #fromdate AND #todate
ELSE Date(from_date_year + 1,dob_month,dob_day) BETWEEN #fromdate AND #todate
end;
How do I select date range from this query?
E.g : From Month('2017-05-22') And Year(date1) = Year('2017-05-22')
to Month('2018-05-22') And Year(date1) = Year('2018-05-22')
My current query :
SELECT
date1
FROM
data
WHERE
Month(date1) = Month('2018-05-22') And Year(date1) = Year('2018-05-22')
I'd convert those literals to dates using str_to_date:
SELECT MONTH(date1)
FROM data
WHERE date1 BETWEEN STR_TO_DATE('2017-05-22', '%Y-%m-%d') AND STR_TO_DATE('2018-05-23', '%Y-%m-%d')
Note that between is inclusive on the first argument and exclusive on the second, so I bumped the day to the 23rd.
BETWEEN condition to retrieve values within a date range.
For example:
SELECT *
FROM order_details
WHERE order_date BETWEEN CAST('2014-02-01' AS DATE) AND CAST('2014-02-28' AS DATE);
This MySQL BETWEEN condition example would return all records from the order_details table where the order_date is between Feb 1, 2014 and Feb 28, 2014 (inclusive). It would be equivalent to the following SELECT statement:
SELECT *
FROM order_details
WHERE order_date >= CAST('2014-02-01' AS DATE)
AND order_date <= CAST('2014-02-28' AS DATE);
SELECT TO_CHAR(systemts, 'yyyy-mm') as yyyymm,
max(notenum) - min(notenum) + 1 as notenum_range
FROM your_table_name
WHERE systemts >= to_date('2018-01-01', 'yyyy-mm-dd') AND
systemts < to_date('2018-07-17', 'yyyy-mm-dd')
GROUP BY TO_CHAR(systemts, 'yyyy-mm');
DECLARE #monthfrom int=null,
#yearfrom int=null,
#monthto int=null,
#yearto int=null
/**Region For Create Date on Behalf of Month & Year**/
DECLARE #FromDate DATE=NULL
DECLARE #ToDate DATE=NULL
SET #FromDate=DateAdd(day,0, DateAdd(month, #monthfrom - 1,DateAdd(Year, #yearfrom-1900, 0)))
SET #ToDate=DateAdd(day,-1, DateAdd(month, #monthto - 0,DateAdd(Year, #yearto-1900, 0)))
/**Region For Create Date on Behalf of Month & Year**/
SELECT DISTINCT month ,Year FROM tbl_Att
WHERE (DATEADD(yy, year - 1900, DATEADD(m, Month - 1, 1 - 1)) BETWEEN CONVERT(DATETIME, #FromDate, 102) AND
CONVERT(DATETIME, #ToDate, 102))
i am try to request date only yesterday but without success...
My query request.
SELECT registeredDaySell FROM new_sell WHERE DATE_SUB(CURDATE(), INTERVAL 1 DAY)
My date is organized this way.
16 September, 2017
Thanks for helping me out.
subdate(now(),1) will return yesterdays timestamp
The below code will select all rows with yesterday's timestamp from employee_login page
Select * FROM `employee_login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)
The below code will display yesterday's timestamp
Select subdate(now(),1) ,subdate(now(),2))
This will give
SELECT producFinalPrice
FROM new_sell
WHERE WEEK (date) = WEEK( current_date ) - 1
As #Gordon mentioned, you should consider storing your dates either in some date type column, or possibly as a UNIX timestamp (seconds since the epoch). A possible workaround here would be to use STR_TO_DATE to convert your string dates to bona fide dates on the fly.
SELECT
producFinalPrice
FROM new_sell
WHERE
STR_TO_DATE(date_col, '%d %M, %Y') = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
This assumes that date_col is the name of the column in your table which contains string dates.
SELECT producFinalPrice FROM new_sell
WHERE where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
-1 equates to "today" minus 1 day. You can change that number to get the number of days that you want to go back if further than 1.
If the current date is 3/12/2015, then I need to get the files from dates 2/12/2015, 3/12/2015, 4/12/2015. Can anyone tell me an idea for how to do it?
<%
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433/CubeHomeTrans","sa","softex");
Statement statement = con.createStatement() ;
ResultSet resultset = statement.executeQuery("
select file from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date <= DATEADD(day, +1, convert(date, GETDATE()))") ;
while(resultset.next())
{
String datee =resultset.getString("Date");
out.println(datee);
}
}
catch(SQLException ex){
System.out.println("exception--"+ex);
}
%>
This is the query I have done, but it's erroneous. I need to get the previous date, current date and next date.
Use DATE_ADD() And DATE_SUB() functions:
Try this:
SELECT FILE, DATE
FROM ForgeRock
WHERE STR_TO_DATE(DATE, '%d/%m/%Y') >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
AND STR_TO_DATE(DATE, '%d/%m/%Y') <= DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY);
Check the SQL FIDDLE DEMO
::OUTPUT::
| file | DATE |
|------|------------|
| dda | 31/12/2015 |
| ass | 01/01/2016 |
| sde | 02/01/2016 |
Simplest way to get all these dates are as below:-
CURRENT DATE
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
NEXT DAY DATE (Adding 1 to the dateadd parameter for one day ahead)
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)
YESTERDAY DATE (Removing 1 from the datediff parameter for one day back)
SELECT DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0)
If you go through the link here, you will get an amazing way of explanation for getting date. It will clear your logic and will be useful for future reference too.
Hope that helps you
You can use dateAdd function
syntax
DATEADD(datepart,number,date)
i.e for current date
select GETDATE()
for yesterday
select DATEADD(D,-1,GETDATE())
for tomorrow
select DATEADD(D,1,GETDATE())
so, your query should be like
select file from tablename
where date >= DATEADD(D,-1,GETDATE())
and date <= DATEADD(D,1,GETDATE())
current date
date = (SELECT CONVERT(char(10), GetDate(),126))
yesterday
date = (SELECT dateadd(day,datediff(day,1,GETDATE()),0))
next day
date= SELECT DATEADD(day, 1,(convert(date, GETDATE())))
I am trying to add hours to current time like
-- NOT A VALID STATEMENT
-- SELECT GetDate(DATEADD (Day, 5, GETDATE()))
How can I get hours ahead time in SQL Server?
DATEADD (datepart , number , date )
declare #num_hours int;
set #num_hours = 5;
select dateadd(HOUR, #num_hours, getdate()) as time_added,
getdate() as curr_date
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
The DATEADD() function adds or subtracts a specified time interval from a date.
DATEADD(datepart,number,date)
datepart(interval) can be hour, second, day, year, quarter, week etc;
number (increment int);
date(expression smalldatetime)
For example if you want to add 30 days to current date you can use something like this
select dateadd(dd, 30, getdate())
To Substract 30 days from current date
select dateadd(dd, -30, getdate())
declare #hours int = 5;
select dateadd(hour,#hours,getdate())
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
If you are using mySql or similar SQL engines then you can use the DATEADD method to add hour, date, month, year to a date.
select dateadd(hour, 5, now());
If you are using postgreSQL you can use the interval option to add values to the date.
select now() + interval '1 hour';