Delete Row at Set Time - mysql

I'm creating a database table where rows need to be removed after a set time. That time is defined in minutes by the valid_time cell in that row. I found this answer though I am not sure how I can implement what I need to into it.
Is someone able to tell me how I can implement this time (as minutes) into the event in the previous answer or if it's not possible, another way to do so. Thanks.
Clarification, I have two columns in the table. One is created which is a TIMESTAMP of when the row is created, and the second is valid_time, an integer in minutes of how long the row is valid for.

DELETE FROM table WHERE created < DATE_SUB(NOW(), INTERVAL `valid_time` MINUTE)

You can try to use the MySQL event scheduler and attach a DELETE query to it. That DELETE will be a simple query that will delete all records where current_time is greater that the valid_time/valid_until fields.
You can configure the scheduler to run in a minute/hourly/daily/... basis as you wish to erase the registers.
Check here and here for more information. M0rtiis offered the query example.

Related

Deleting/Copying the data from Database with specific condition in mySQL

I am looking for an Idea to handle data in DB directly.
Here is my use case
I have table “EVENT_REGISTERED” with column (ID, Event_name,Event_DateTime)
I want to display the EVENT_REGISTERED in the fronted end whose date and time is not passed. i.e. I want to display only Upcoming event not Historical events.
Of course this can be handle with JS code before displaying.
But What I want is there should be some sort of a trigger which will delete the Instance form the “EVENT_ REGISTERED” table and copy it to another Table “HISTORICAL_EVENT”
I cannot Create an MY SQL EVENT to do this as it like batch job and I cannot run this every 5 mins as there can be more than 10000 rows in there.
I see Trigger option as well, I am not sure how to use this as it says that it will be activated after the specific action is executed. Here the specific action is CURRENT_DATETIME == EVENT_DATETIME.
Can anybody give me a direction or any sort of alternative way to achieve this?
**I am not an Expert of MySQL*
Thank you
Regards
Prat
Don't start moving rows between tables. Simply run a query:
select er.*
from event_registered
where er.event_datetime > now();
With an index on (event_datetime), performance should be fine.

MySQL DATE_ADD INTERVAL 1 SECOND not working

I'm facing currently very, very strange behaviour.
I have an enterprise application, running on JBoss, the ORM is as you might expect hibernate and I'm doing some bulk operations.
I have a table and in that table there are all kind of fields and among the others there is a field of type DATETIME. In this field I'm saving user info, I have another field of the same type, configured with an trigger, so every time when the row is being updated the second DATETIME field is also updated.
I have a case where the first field should be increased with one second, so I'm doing bulk copy something like this:
UPDATE <TABLE_NAME> SET customerDATE = DATE_ADD(customerDATE, INTERVAL 1 SECOND)
My problem is that the query does not always work as expected.
What I see is that the second DATETIME field(the onne with the trigger) is being updated, together with some other fields, but the auto-increment with one second does not alway works(sometimes is also increased, sometimes not).
I tried searching for some known issues, but without success.
If anybody knows some problem in this direction I would really appreciate any help!
I'm testing now if there will be problems with more than an extra second.
Thanks in advance!

How to combine a trigger and an event and have the event use a specific row id?

I have the following problem to solve. I need rows inserted into a "reservations" table to, upon insertion, set a timer for themselves and then check a flag within this newly created row some minutes later to see if it has changed from "pending" to "completed" (which would be caused by user action in the intervening period) and if still "pending" to remove themselves from the table.
The idea here is that people are making reservations and the act of beginning the reservations process adds this row, however, if they fail to complete the purchase over a period of time I want to remove the rows to make the reservations (of which there is a finite amount) available to other consumers.
So, I've been looking at events and triggers and I get the concept for both, but what I'm failing to find is a way for the trigger to pass *this row's id to the event so that when the event fires it only looks at the relevant row because I don't want it to notice *all the rows that might be "pending" since there may have been newly created "pending" rows by other consumers for other reservations in the intervening period, and I obviously don't want to mess with those until their respective timers have elapsed.
So... what I am hoping for (in pseudo) is...
/*EVENT*/
CREATE EVENT IF NOT EXISTS delete_abandoned_pending_purchase
ON SCHEDULE AT CURRENT_TIMESTAMP + 5 minutes
DO
delete from tickets where state = 'PENDING' and id = [MY ROW ID]
and then...
/*trigger*/
CREATE TRIGGER remove_if_unused
AFTER INSERT ON `tickets` FOR EACH ROW
begin
[call delete_abandoned_pending_purchase with row_id MY_NEW_ROW_ID]
end
I'm guessing maybe I need to make a stored procedure that takes a parameter and then pass that row ID as the param? Or perhaps there's a more straight forward way... I'm just failing to find the syntax for this and would love some guidance. Obviously I can handle this in the business logic that wraps this data interaction, but felt that this was a more elegant approach.
[EDIT]
reading more about this
"There is no way to pass parameters directly to or from events; however, it is possible to invoke a stored routine with parameters within an event".
But the suggestion there is to call a stored procedure and pass it a param. However, my problem is that I don't see how to get *at the row.id in the event to pass to the stored proc. I feel like I must be missing something obvious... how can events not have access to specific row ids?
[EDIT EDIT]
so, based this I'm sensing that this is actually not doable in mySQL... that's a bummer and also quite surprising. Seems like a really obvious thing to want to do.
I'll leave the question open and see if anyone chimes in with a clever alternative.
I would recommend you do this via a script, less complexity and more control. Something like below:
MaxSleep=300 # In seconds SleepTime=MaxSleep
while (1) {
sleep SleepTime; delete from TheTable where reserved = 'pending' and the_timestamp >= Current_Timestamp; SleepTime='mysql
'select the_timestamp from TheTable where reserved = 'pending' order
by the_timestamp limit 1"
if SleepTime is null then SleepTime= MaxSleep
}
You could just do an event that checks against the whole table, should be fast if it is indexed correctly and then the business logic is in the DB. Perhaps use a minute as the check then max pending transaction is 6 Minutes if you have a 5 minute timeout.
CREATE EVENT delete_abandoned_pending_purchase
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 Minutes
DO
BEGIN
delete from TheTable where reserved = 'pending' and the_timestamp >= Current_Timestamp;
END

Extract results updated in last 2 hours

I am trying to write a query to extract records updated in the last 2 hours in SQL Server 2008.
Could anyone help me write this?
select * from table where table.date1>=dateadd(hh,-2,getdate())
dateadd() function lets you subtract hours from getdate() letting you choose records updated past 2 hours
First, you have to design the table so you have a field where the time of the last change will be stored
Then, whenever you update a row, update the value in the 'last update' field. After that, you can use a script such as suggested by Vijaykumar
The downside of this method is that when a single record was changed more than once in the specified time period, you will be notified only about the time of the last update.
Another solution for tracking the updates is to read the database online transaction log file, but you'll need a third party tool for that

mySQL update timestamp from 0

I have this mySQL syntax which updates the table users and column skills_mod_time every time the page is reloaded. $sql = "UPDATE users SET skills_mod_time = CURRENT_TIMESTAMP";
How can i change from instead of using the CURRENT_TIMESTAMP to using a counting timestamp.
For example the column skills_mod_time is defaulted as 0. If the page was reloaded 10 sec later, i want the seconds part to be 10. Instead of the current way where it changes 0 to this present time.
It sounds like you want to log "seconds since login", or something similar, rather than "last activity." To do this, you should create a column called login_time, or similar, and only update it when a user logs in. You probably still want to track the last-activity time, as you do now, for the purpose of session expiry.
Then if you have these two columns, login_time, and last_activity, you can get the seconds between login_time and last_activity by subtracting the one from the other. Or you can get the time since login by subtracting login_time from NOW().
I hope this answers your question--if not, please clarify your question.
you can use timestampdiff function to take the difference of two timestamp values
something like
UPDATE users SET skills_mod_time = TIMESTAMPDIFF(MINUTE,skills_mod_time,CURRENT_TIMESTAMP);