using the difference between two dates in a WHERE clause - mysql

I'm trying to filter a SELECT query between NOW() and NOW - interval 10 minute(?), but i can't seem to get this to work, and it's given me a few questions on the topic.
I've looked through some documentation online, and alot of questions on stackoverflow but non of the solutions give me what i need. Looking at the TIMEDIFF and TIMESTAMPDIFF documentation, i only see it used like this;
SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00');
However i don't want to just select the time difference, i want to use it in a query as a WHERE clause, something like;
SELECT * FROM tableName WHERE (the time difference betweeen NOW() and the stored timestamp is less than x minutes);
Is there a particular data type i need to set my column to?
How can i use the TIMEDIFF / TIMESTAMPDIFF correctly, and if these are not the correct methods i should be using, what is?

SELECT * FROM tableName WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) < 10

SELECT * FROM tableName
WHERE now() - interval 10 minute < stored_timestamp

Related

Query data between the same date

Is it possible to do something like this?
select * from table where Date BETWEEN '2019-05-29' AND '2019-05-29'
Yes it is possible. If you have time part you could use DATE function to skip it:
SELECT * FROM table WHERE DATE(Date) BETWEEN '2019-05-29' AND '2019-05-29'
-- it may degrade performance, condition is not SARGable
Yes, but the better approach is:
select t.*
from table t
where t.Date >= date('2019-05-29') AND
t.Date < date('2019-05-29') + interval 1 day
Why is this better? It doesn't have a function on the column name, so it can make use of an index on the date column.
Yes you can, if you want to run it in a test window without manually changing the date within the code you can set it as a variable. Use trunc to get rid of time i.e there will be no 29-05-2019 23:59:00. If you want the same date within a time period remove the trunc and then you can set hours-minutes-seconds which makes your query more precise
SELECT t.*
FROM table t
WHERE t.date BETWEEN trunc(to_date(:datefrom, 'dd.mm.yyyy hh24:mi:ss')) AND
trunc(to_date(:dateto, 'dd.mm.yyyy hh24:mi:ss'))

MySQL: How to get a count of events occurred within a span of 24 hrs using ONLY COUNT() and WITHOUT using WHERE clause

This is my scenario:
I am collecting IP addresses of clients pinging my server and also the time of ping in MySQL.
Columns:
IP_address, Time_of_Ping(date - hr - min - sec)
At any given point of time, I want to know how many clients have been communicated with my server in the last 24 hrs.
Please note: I know this can be done with a simple select statement with where clause.
But why I am posting this in the forum just to know: can this be done with just count() I mean just writing some condition within count() and without using where clause?
Thanks in advance
You could take advantage of MySQL treating boolean expressions as either 1 or 0 in a numeric context and use SUM:
SELECT SUM(Time_of_Ping > NOW() - INTERVAL 24 HOUR)
FROM your_table
I think you want:
select count(*) as num_pings, count(distinct ip_address) as num_ips
from t
where time_of_ping > now() - interval 24 hour;
Note that count(*) is the number of pings. count(distinct) is the number of different ip address, which is what I think you really want.
I got the expected query and it is working fine:
select count(ping_time > datetime('now', '-24 hours')) from testTable

Mysql Select with Dates and maybe Case when

im having a problem where i cant think of a solution, maybe im having a bad table-structure or i just dont know enough about mysql select commands to think of a good solution. Maybe you can help me out:
So i got a table that has a Column with the Date-format (yyyy-mm-dd) i wanted to select all upcoming dates so i did:
SELECT * WHERE date >= now.
This worked kinda well but i also got "dates" where only the year is entered (2014-00-00) i also wanted to select these but "now" is already bigger so i made another column with the year only and if the month, date or both arent known i will use 0000-00-00 and the Column "year" now i could select like this:
SELECT * WHERE date >= now AND year >=now(year)
Now all entrys with 0000-00-00 wont be selected. If i use OR the entrys from last year will be shown.
So thats my problem, is there any way i can change my table so i can have entries with only the year or only year and month and of course all together? I already considered get rid of the date-format and use simple INT with seperated columns for year, month and date. But i think i will have the same problem.
Sometimes i just want to do a capsuled select like
SELECT *
WHERE (date >= now AND year >= now(year))
OR date == "0000-00-00" (i know that this doesnt work)
If I understood your problem correctly, you could use this request:
WHERE (date >= now OR year > now(year))
There is probably a simpler way though, that would preserve your design, like initializing at January 1st (01-01) instead of 00-00
I think you can use this code:
$_SESSION['month'] = //set here your selected month
$_SESSION['year'] = //set here your selected year
SELECT * FROM table WHERE DATEPART(m,date) >= '".$_SESSION['month']."' AND DATEPART(yyyy,year) >= '".$_SESSION['year']."' AND date <> '0000-00-00'
Change your table structure format. Actually just allow for that field to have null value when not entered. By default it will be null then. You shouldn't be storing 0000-00-00 as a value for Date type field. I would rather leave it as null , or as suggested in some of previous answers, initialize it with some other date. It would be much easier to manipulate with database then.
the problem is that half of you write is not MySQL and your database schema is terrible...
You have the following problems:
column data date does not have the date data type.
To fix it, you need to add a cast to the select statement eg. cast(datecolumn as date)
select * from table where cast(datecolumn as date) >= '2014-01-10';
the way to use now date is using the now function.
select now(), date(now());
result> 2014-01-10 11:11:36, 2014-01-10
select * from table where cast(datecolumn as date) >= date(now());
Because your datecolumn is not a date (2014-00-00 is not a valid date), you need to use string manipulation to extract the year.
select substring('2014-01-01', 1,4)
result> 2014
select * from table where substring(datecolumn, 1,4) = year(now());
The comparassion operator is = and not ==
the select statement syntax looks like this (pay attention because you are missing the table in your statement)
select * from [Table] where [column] = condition ...
You probably need or instead of ands, therefore your query should look like this:
select * from FooTable where
cast(datecolumn as date) >= date(now())
or substring(datecolumn, 1,4) >= year(now())
or datecolumn = '0000-00-00'
You should use something like phpmyAdmin or mySQL workbench to test your sql queries before try to use them on php, java or whatever is your programing language.

Why doesn't BETWEEN work in this MySQL query?

Query 1 works but query 2 doesn't:
Query #1:
SELECT * FROM `users` WHERE users.dob <= '1994-1-14' AND users.dob >= '1993-1-14' LIMIT 10
Query #2:
SELECT * FROM `users` WHERE users.dob BETWEEN '1994-1-14' AND '1993-1-14' LIMIT 10
The 2nd one should be able to do the same thing as the first but I don't understand why it's not working.
The dob (date of birth) field in the users table is a type date field with records that look like this:
1988-11-08
1967-11-14
1991-03-09
1958-03-08
1967-06-30
1988-10-19
1986-01-23
1965-09-20
YEAR - MONTH - DAY
With either query #1 or #2 I'm trying to get back all users who are between 18 and 19 years of age, because 1994-1-14 is exactly 18 years from today and 1993-1-14 is 19 years from today. So is there a way to get the between query to work?
By not working I mean it doesn't return any records from the db while the working query does.
Also is the between query more efficient or is the performance difference negligible?
To answer the first part: "expr BETWEEN min AND max". Try switching those 2 dates in the second query.
The usage is wrong. See the BETWEEN documentation:
expr BETWEEN min AND max is equivalent to (min <= expr AND expr <= max).
Therefore, users.dob BETWEEN '1994-1-14' AND '1993-1-14' is the same as ('1994-1-14' <= users.dob AND users.dob <= '1993-1-14'), of which there will never be more than 0 results.
Simply reverse the order :)
There will be no performance difference when using either form, possibly subject to the note below. This transformation happens at the query planner level. However, if you have concerns, remember to profile, profile, profile. Then you can see for yourself and appease the premature-optimization demons.
Also note the ... note:
For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type.

Working with Dates in SQL

I have an events table and need to pull the 4 closest dates to today's date and they can be in the past, present or future.
What would the SQL (using MySQL) be for this if it is possible?
Thanks
Brett
I don't know which DB you are using, but this works with mysql:
select *
from event
order by abs(datediff(event_date, now()))
limit 4
Try using the TIMEDIFF function like this:
select *
from events
order by abs(timediff(now(), yourdatecolumn))
limit 4;