Fetch values between two dates - MariaDB version: 10.1.37 - mysql

I'm trying to fetch values between two dates, specifically 24hrs
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN 20190311 AND 20190312
This query works fine but, i don't want it for a constant date, i have checked and seen many format but none seems to work. please help

If you "want records from today alone" - a simple way would be:
WHERE accnum = '1534610376'
AND DATE(tdate) = CURRENT_DATE()
However - To utilize an index, a column should not be wrapped into a function. So an efficient way would be
WHERE accnum = '1534610376'
AND tdate >= CURRENT_DATE()
AND tdate < CURRENT_DATE() + INTERVAL 1 DAY
A good index for this query would be INDEX(accnum, tdate).

I suggest you to put your date between quots like this:
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN '20190311' AND '20190312'
After, you can define a user defined function like this :
CREATE FUNCTION BetweenDate(#toCompare VARCHAR(30), #rightDate DATE, #leftDate DATE)
RETURNS TABLE
AS
BEGIN
RETURN (
SELECT *
FROM transactions
WHERE accum = #toCompare AND tdate BETWEEN #rightDATE AND #leftDate
)
END;

Related

MySQL user defined function with nested query inside

I want to create a mysql function to get due date (90 work days from start_date) based on my local holiday calendar. The query in my PHP function is like this..
select max(col_date) as due_date from (select col_date from ref_calendar where holiday=0 and col_date>'".$start_date."' limit 90) as a
I want to make it as a mysql function so I can just query "duedate(start_date)" to get the due date.
I have tried but still failed.
CREATE FUNCTION duedate(st_date DATE)
DECLARE datedue DATE
BEGIN
SELECT MAX(col_date) INTO datedue from (select col_date from ref_calendar where holiday=0 and col_date>st_date limit 90);
RETURN datedue;
END
Problem resolved. This is my final code after read MariaDB knowledge base.
CREATE OR REPLACE FUNCTION duedate (st_date DATE)
RETURNS DATE
RETURN (select max(a.col_date) FROM (select col_date from ref_calendar where holiday=0 and col_date>st_date limit 90) as a);
Thank you! :)

Put in where sql only the date from datetime

I have a table in my database like this :
id date origine
1 2015-12-04 16:54:38 1
Now I want to get only data witch have the date = 2015-12-04. So I tried like this :
select * from table where id = 1 and date = "2014-12-04"
But I have no data. Can you help me please ?
You can use the date function:
where id = 1 and date(date) = '2015-12-04'
However, for performance reasons, it is often better to use inequalities. This allows MySQL to use an index on id, date for the query:
where id = 1 and
(date >= '2015-12-04' and date < date_add('2014-12-04', interval 1 day))
you can use Date Function of mysql which returns date from DateTime or truncate the Time part
select * from table where id = 1 and Date(date) = "2014-12-04"
There are several date related function out there you can use, take the following:
select *
from table
where id = 1
and date_format(date, '%Y-%m-%d') = '2015-12-04';
date_format will format your date column to a particular format.
In MSSQL you can simply say
SELECT *
FROM Table
WHERE ID = 1
AND Date > '2015-12-04'
I'm not familiar with mysql, but I assume something similar would work here. This date gets formatted as 2015-12-04 00:00:00 so in effect it matches everything with a date of 2015-12-04 and a time greater than 00:00:00.
If you happen to have rows with time of 00:00:00, just use >= instead.

How to select from a DATETIME column using only a date?

I have a DATETIME column on my table which stores when a record was created. I want to select only the records created on a particular date. If I try:
SELECT *
FROM myTable
WHERE postedOn = '2012-06-06'
It returns no rows even though there are many rows in the table with the postedOn set as
2012-06-06 21:42:02, 2012-06-06 07:55:17 , and so forth.
Any ideas?
Use the DATE scalar:
SELECT *
FROM myTable
WHERE date(postedOn) = '2012-06-06'
SELECT *
FROM myTable
WHERE DATE(postedOn) = '2012-06-06'
DATE() returns the date part of a datetime field.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date
Create a time range by adding a day to the date:
SELECT *
FROM myTable
WHERE postedOn >= '2012-06-06' and postedOn < '2012-06-07'
This is the most efficient way, as the query can use an index on the field.

TSQL - Calculating datediff in a query and setting a value?

Using SQL Server 2008, I want to calculate the timespan, in seconds, that has occurred between two times.
The start date, is the timestamp of the last occurance of where a specific ID exists (if the filter is true), get the time from that timestamp record, and do a DATEDIFF() against the current processing time and return a value, #LastEventTimespan, in seconds.
DECLARE #CurrentProcessTime DATETIME
DECLARE #LastEventTimespan DATETIME
SET #CurrentProcessTime = GetDate()
-- find the timespan since the last session event
-- DATEDIFF ( datepart , startdate , enddate )
SELECT MAX(PageVisitEventID) AS LastPageVisitEventID, #LastEventTimespan = DATEDIFF(second , DateAdded , #CurrentProcessTime )
FROM PageVisitEvents
WHERE UserID = #UserID
GROUP BY LastPageVisitEventID
I figured I could get the MAX ID of the filter and process accordingly but am unable to set the #LastEventTimespan, however trying to assign a value when doing data-retrieval is a no-no.
How can I get around this?
Thanks.
I guess you want something like this.
DECLARE #LastEventTimespan INT
SELECT TOP 1 #LastEventTimespan = DATEDIFF(SECOND, DateAdded, GETDATE())
FROM PageVisitEvents
WHERE UserID = #UserID
ORDER BY PageVisitEventID DESC
This will calculate the difference in seconds between DateAdded for the highest value of PageVisitEventID for a given user and the current DateTime. I changed the data type of #LastEventTimespan to INT because it probably makes more sense when dealing with seconds.
You can replace the SELECT statement with this one:
SELECT TOP 1
#LastEventTimespan = DATEDIFF(second , DateAdded , #CurrentProcessTime )
FROM PageVisitEvents
WHERE UserID = #UserID
ORDER BY PageVisitEventID desc
I've done such queries many times and never had problems.

Mysql: Select all data between two dates

I have a mysql table with data connected to dates. Each row has data and a date, like this:
2009-06-25 75
2009-07-01 100
2009-07-02 120
I have a mysql query that select all data between two dates. This is the query:
SELECT data FROM tbl WHERE date BETWEEN date1 AND date2
My problem is that I also need to get the rows between date1 and date2 even if there is no data for a day.
So my query would miss the dates that are empty between 2009-06-25 and 2009-07-01.
Can I in some way add these dates with just 0 as data?
You can use a concept that is frequently referred to as 'calendar tables'. Here is a good guide on how to create calendar tables in MySql:
-- create some infrastructure
CREATE TABLE ints (i INTEGER);
INSERT INTO ints VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
-- only works for 100 days, add more ints joins for more
SELECT cal.date, tbl.data
FROM (
SELECT '2009-06-25' + INTERVAL a.i * 10 + b.i DAY as date
FROM ints a JOIN ints b
ORDER BY a.i * 10 + b.i
) cal LEFT JOIN tbl ON cal.date = tbl.date
WHERE cal.date BETWEEN '2009-06-25' AND '2009-07-01';
You might want to create table cal instead of the subselect.
Select * from emp where joindate between date1 and date2;
But this query not show proper data.
Eg
1-jan-2013 to 12-jan-2013.
But it's show data
1-jan-2013 to 11-jan-2013.
its very easy to handle this situation
You can use BETWEEN CLAUSE in combination with date_sub( now( ) , INTERVAL 30 DAY )
AND NOW( )
SELECT
sc_cust_design.design_id as id,
sc_cust_design.main_image,
FROM
sc_cust_design
WHERE
sc_cust_design.publish = 1
AND **`datein`BETWEEN date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )**
Happy Coding :)
Do you have a table that has all dates? If not, you might want to consider implementing a calendar table and left joining your data onto the calendar table.
IF YOU CAN AVOID IT.. DON'T DO IT
Databases aren't really designed for this, you are effectively trying to create data (albeit a list of dates) within a query.
For anyone who has an application layer above the DB query the simplest solution is to fill in the blank data there.
You'll more than likely be looping through the query results anyway and can implement something like this:
loop_date = start_date
while (loop_date <= end_date){
if(loop_date in db_data) {
output db_data for loop_date
}
else {
output default_data for loop_date
}
loop_date = loop_date + 1 day
}
The benefits of this are reduced data transmission; simpler, easier to debug queries; and no worry of over-flowing the calendar table.
you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)
You can use as an alternate solution:
SELECT * FROM TABLE_NAME WHERE `date` >= '1-jan-2013'
OR `date` <= '12-jan-2013'