How to run a query asynchronously from MySQL Workbench - mysql

Say you have a query you want to run on your database, but you know that query is going to take a long time to complete, and you don't have direct access to the machine where MySQL is running, or to some other endpoint which has a stable connection with that machine. What do you do?

Well, you create a one time event that performs the necessary query.
Something like this:
CREATE EVENT <event_name>
ON SCHEDULE
AT CURRENT_TIMESTAMP + INTERVAL 10 SECOND
ENABLE DO
BEGIN
-- log the event started
INSERT INTO EventLogs (`Name`, `Start`, `Query`)
VALUES (<event_name>, CURRENT_TIMESTAMP, <query_string>);
-- run the query
....
... <query>
....
-- log the event done
UPDATE EventLogs
SET `Done` = CURRENT_TIMESTAMP
WHERE `Name` = <event_name>;
END
The above template can handle any arbitrary query.

Related

Executing an SQL query every hour

How can i make the following query execute each hour automatically?
SELECT count(*)
FROM user_tab_columns
WHERE table_name='MYTABLE'
Usually in a DBMS exist some schedule of instrument. In Oracle the instrument is DBMS_SCHEDULER.
MySQL same have scheduler. You should check global variable event_scheduler=1. Then you can create schedule:
CREATE EVENT 'new_event'
ON SCHEDULE EVERY 1 HOUR STARTS CURRENT_TIMESTAMP
ON COMPLETION NOT PRESERVE
ENABLE
COMMENT '' DO
call new_proc();
where new_proc() is procedure with your query.

How to make delayed DELETE SQL query?

I need to delete rows from table 14 days after the DELETE query has been made. Is it possible to do this using MySQL?
You can use the built-in MySQL Event Scheduler to schedule a query or a stored routine to run at an arbitrary point in time:
This is an example of a minimal CREATE EVENT statement:
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
UPDATE myschema.mytable SET mycol = mycol + 1;
Please mind, the Event Scheduler is disabled by default.

MySQL Trigger to automatic insert based on date

i tried following example .but it doesn't insert. is any problem in where clause??
CREATE DEFINER = `root`#`localhost` TRIGGER `new` AFTER INSERT ON `employee`
FOR EACH
ROW INSERT INTO employee_log( first_name, last_name )
SELECT first_name, last_name
FROM employee
WHERE start_date = now( )
I'm not sure if that can be done with triggers. But you can make a shell script, and execute mysql commands
test.sh:
#!/bin/bash
#delete everything from today_plan
mysql -e "DELETE FROM today_plan" --user=user_name --password=your_password db_name
#insert only todays plans to today_plan
mysql -e "INSERT INTO today_plan (pjtno, pattern, itemno, belt, kiln, qty, lnusr, distant, remark, decww, plandate, nowdate, shipment) SELECT pjtno, pattern, itemno, belt, kiln, qty, lnusr, distant, remark, decww, plandate, nowdate, shipment FROM daily_plan WHERE plandate=NOW()" --user=user_name --password=your_password db_name
exit
then add execution of shell script as cron job in /etc/crontab like:
0 6 * * * root php /path/to/script/./test.sh
Which will execute it every morning at 6:00
ps. This is just one idea of how to get it done :D
edit:
Or you can make mysql event
"A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table"
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Create a stored procedure
CREATE PROCEDURE yourdatabase.sp_plandate_process ()
BEGIN
// here you write the code to process the data
END
Create the event
CREATE EVENT mysql.name_of_event
ON SCHEDULE
EVERY 24 HOUR STARTS '2013-07-10 06:00:00'
COMMENT 'Write comment'
DO
CALL sp_plandate_process();
Make sure that your variable event_scheduler=1 , if its set to 0 you can just do
SET event_scheduler=1;
And this will start the connection for the event scheduler.
Since you changed the question i edit again
New answer:
Probably because Now( ) should be now() is not the same value as it
was when it was inserted. The trigger runs once after a employee hsa
been inserted. the value now(0 changes probably by miliseconds but it
wont be the same. unless you use sort desc in your where clause, you
can use the value new.id() instead. Did you actually read about
triggers as adviced? – Kay Nelson 41 secs ago

Is it possible to "decay" SQL information?

Let's say I have rows of information in an SQL database.
I want to have rows of information that are older than 30 days to be automatically removed.
Is this possible?
Additional information:
I am using the SQL date function provided to collect the dates.
This problem has two aspects:
How to schedule
Actual SQL Statement
How to Schedule
You have multiple options, but all of this revolves around whether you will schedule, or whether you will have a stored procedure triggered.
Three options
Use MySql event scheduling: http://dev.mysql.com/doc/refman/5.1/en/events-overview.html
Schedule through an operating system (CRON, SCHEDULED TASK) the execution of an app using SQL (either PHP script, java etc)
Have a trigger that is executes a stored procedure every time a change is made to a table.
I would propose options 1 and 2 are the best.
SQL Statement
The actual SQL statement is quite easy provided you have a field (e.g. dateField) that represents insertDate...
delete from myTable where insertDate < DATE_SUB(NOW(), INTERVAL 1 MONTH);
You can easily generate this value using the NOW() function within an insert statement, for example:
insert into myTable values (NOW(), 'value1', 'value2', ... , 'valueN');
Scheduling Using Event Scheduler at End of Day
If you have the CREATE EVENT privilege this will work through PHP MyAdmin.
See also: http://www.sitepoint.com/how-to-create-mysql-events/
CREATE EVENT `clean_up2`
ON SCHEDULE EVERY 1 DAY STARTS CURRENT_DATE
DO
delete from `data` where updated_on < DATE_SUB(NOW(), INTERVAL 1 MONTH);
END;
Yes. In SQL Server you could create a stored procedure to perform the delete, and create a SQL Agent job that runs every day (or a schedule of your choosing)

Timestamp for row creation and last modification

I need to keep track of the time a row was inserted into the database, and the time it was last modified.
I tried to create two separate columns, and use CURRENT_TIMESTAMP:
create table def (
id int,
creation timestamp
default CURRENT_TIMESTAMP,
modification timestamp
on update CURRENT_TIMESTAMP
);
However, this produced an error:
ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
What is the best way to do this?
I'm thinking stored procedure, but looking for a standard solution. I'm also concerned with access privileges -- as few programs/things should be able to touch the timestamps as possible.
Although I would prefer MySQL answers, solutions for other RDBMS's are also appreciated!
Ya this is a lame limitation on MySQL. If you are going through an application you can add a time() call for the created_at column, and let the updated_at column use the CURRENT_TIMESTAMP.
$sql = "INSERT INTO my_table SET name = 'Mike', created_at = " . time();
I'd opt to do this on the created_at column as it probably won't be touched as often as the updated_at column.
-- Edit --
Better yet, use MySQL's built in now() function. This way you only need to be concerned with the timezone of the mysql server, and not the timezones of the app server AND the mysql server.
$sql = "INSERT INTO my_table SET name = 'Mike', created_at = NOW()";
You can use a trigger. The application can also set the value, but if do, it will be overwritten by the database.
delimiter //
CREATE TRIGGER def_bef_update BEFORE UPDATE ON def FOR EACH ROW BEGIN
SET NEW.modification = CURRENT_TIMESTAMP;
END//
delimiter ;
You can also use it to check the data and update your modification date only if has important changes.