Is it possible to see date of update of row mysql? - mysql

I'd like to see the update date per-row in a table (InnoDB) in mysql.
Is it possible? The only thing I found is the statistics on a table, not row.
SHOW TABLE STATUS
Any suggestions appreciated!

It is not possible, if you want to track the updates or inserts of 'row' in a table, you have to manually create a logic to do so, for example you can use triggers , to maintain the track of all changes and updates of the 'rows' in any other table.

I don't think you can see specific informations like this for a row.
What I usually do is that I create a column creation_date and modification_date in all my tables and then I fill them for each INSERT or UPDATE query with the function NOW()
You can also create your table this way :
CREATE TABLE [name]
[other colmns]
creation_date DATETIME DEFAULT CURRENT_TIMESTAMP
For this, see this topic.

Related

Can I add rows to MySQL before removing all old rows (except same primary)?

If I have a table that has these rows:
animal (primary)
-------
man
dog
cow
and I want to delete all the rows and insert my new rows (that may contain some of the same data), such as:
animal (primary)
-------
dog
chicken
wolf
I could simply do something like:
delete from animal;
and then insert the new rows.
But when I do that, for a split second, 'dog' won't be accessible through the SELECT statement.
I could simply insert ignore the new data and then delete the rest, one by one, but that doesn't feel like the right solution when I have a lot of rows.
Is there a way to insert the new data and then have MySQL automatically delete the rest afterward?
I have a program that selects data from this table every 5 minutes (and the code I'm writing now will be updating this table once every 30 minutes), so I would like to be as accurate as possible at all times, and I would rather have too many rows for a split second than too few rows for the same time.
Note: I know that this may seem like it is unnecessary but I just feel like if I leave too many of those unlikely possibilities in different places, there will be times where things go wrong.
You may want to use TRUNCATE instead of DELETE here. TRUNCATE is faster than DELETE and resets the table back to its empty state (meaning IDENTITY columns are reset to original values as well).
Not sure why you're having problems with selecting a value that was deleted and re-added, maybe I'm missing some context. But if you're wiping the table clean, you might want to use truncate instead.
You could add another column timestamp and change the select statement to accommodate this scenario where it needs to check for the latest value.
If this is for school, I would argue that you need a timestamp and that is what your professor is looking for. You shouldn't need to truncate a table to get the latest values, you need to adjust the thinking behind the table and how you are querying data. Hope this helps!
Check out these:
How to make a mysql table with date and time columns?
Why not update values instead?
My other questions would be:
How are you loading this into the table?
What does that code look like?
Can you change the way you Select from the table?
What values are being "updated" and change in such a way that you need to truncate the entire table?
If you don't want to add new column, there is an other method.
1. At first step, update table in any way that mark all existing rows for deletion in future. For example:
UPDATE `table_name` SET `animal`=CONCAT('MUST_BE_DELETED_', `animal`)
At second step, insert new rows.
On final step, remove all marked rows:
DELETE FROM `table_name` WHERE `animal` LIKE 'MUST_BE_DELETED_%'
You could implement this by having the updated_on column as timestamp and you may even utilize some default values, but let's go with an example without them.
I presume the table would look something like this:
CREATE TABLE `new_table` (
`animal` varchar(255) NOT NULL,
`updated_on` timestamp,
PRIMARY KEY (`animal`)
) ENGINE=InnoDB
This is just a dummy table example. What's important are the two queries later on.
You would simply perform a query to insert the data, such as:
insert into my_table(animal)
select animal from my_view where animal = 'dogs'
on duplicate key update
updated_on = current_timestamp;
Please notice that my_view is your table/view/query by which you supply the values to insert into your table. Also notice that you need to have primary/unique key constraint on your animal column in this example, in order to work.
Then, you proceed with the following query, to "purge" (delete) the old values:
delete from my_table
where updated_on < (
select *
from (
select max(updated_on) from my_table
) as max_date
);
Please notice that you could make a separate view in order to obtain this max_date value for updated_on entry. This entry should indicate the timestamp for your last updated/inserted values in a previous query, so you could proceed with utilizing it in a where clause in order to issue deletion of old records that you don't want/need anymore.
IMPORTANT NOTE:
Since you are doing multiple queries and it's supposed to be a single operation, I'd advise you to utilize it within a single trancations and to utilize a proper rollback on various potential outcomes (i.e. in case of mysql exceptions). You might wish to utilize a proper stored procedure for that.

How to use UNIX_TIMESTAMP on a whole table?

I've been using CURRENT_TIMESTAMP in my DB for entries, but now wish to change to unix timestamp instead.
As seen here I have the data, but for each row I want to use UNIX_TIMESTAMP() and the value it returns to be placed in the unixtime column.
I've never messed around with big database changes and would appreciate a response.
I found it out myself by manipulating another post but doing it vice-versa.
UPDATE t_records SET unixtime = UNIX_TIMESTAMP(timeSet);
You might not able to replace the same column with unix_time, You will have to add another column first and set the values there. Later you can rename the columns.
alter table T add unix_time BIGINT(14);
update T set unix_time = unix_timestamp(<old_time_column>);
alter table T drop <old_time_column>;
alter table T change unix_time <old_time_column> BIGINT(14);

How can I record the username and timestamp of row insertions and updates in MySQL?

I'd like to record the last user and last time a particular row was either inserted or updated in a MySQL table. What is the best way to go about this? Is there some MySQL metadata I can investigate or do I need to create username and timestamp columns myself and then create triggers to populate them?
You need to create separate columns yourself for timestamp and user name. For timestamps there is no need to use triggers to update its value, just declare the timestamp field to use current timestamp as initial value and update value:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
The user is bit more interesting. If you are talking about mysql level user, then yes, use triggers or stored procedure using the USER() function. If you are talking about application level users, then I would supply that username as part of the update statement.
UPDATE table SET username='xxx', ... WHERE ...
You can use a column and set it default system date for insert
For update you must use trigger or etcs.
At least in MySQL 5.5.46, you can track tables. This includes structure and data. There, the DB username and timestamp is recorded.

Converting Epoch to day of the week in new column in MySQL

I have a table with a column containing unix time. I wish to create a new column that contains the day of the week for this time. For example, 1436160600 would be a Monday in this column.
I have created a new column, entitled "day_of_week"
alter table master add column test varchar(20);
I now wish to update this new column with the appropriate values.
I found the MySQL Unixtimestamp() function (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp)
I then attempted the following
update master set day_of_week = _sent_time_stamp(from_unixtime(unix_timestamp, %W));
where _sent_time_stamp is the column containing the Unix time values
But this results in an Error 1064.
Can anyone advise?
Solution. Convert epoch to date time
alter table master add column test_date datetime ;
update master set test_date = from_unixtime(_sent_time_stamp) ;
convert datetime to day of week using dayname function
alter table master add column test_day varchar(20) ;
update master set test_day = dayname(test_date) ;
I know this post is old, but the accepted answer is sadly wasteful, and I hope that future people seeking this answer may be more enlightened.
No need to add a new column to the table just for some temporary value. To achieve what you requested, you can simply do this:
UPDATE master
SET test_day = dayname(from_unixtime(_sent_time_stamp)) ;
However, even the goal is a wasteful in that we're simply storing two representations of the same data. What you can do instead, is to create a view:
CREATE VIEW master_vw AS
(SELECT mstr.*, DAYNAME(FROM_UNIXTIME(mstr._sent_time_stamp)) AS test_day
FROM master mstr) ;
Now, you can SELECT from this view anytime you like, and the value of test_day will always be in sync with the value of _sent_time_stamp. And no new column to maintain and whatnot.
There is a use case for actually storing the test_day column - execution of the view will take a miniscule amount of additional processing versus selecting from a table. And you cannot index over the virtual test_day column like you could in a table. So if you have millions of rows and you need to quickly get one that's (say) 'Saturday' then perhaps the table approach is more ideal.
But in cases where the column is just a convenience, or where it is simply a different representation of data that already exists, you'll do well to consider the View approach.

how can find which records are inserted / updated for particular date in sql if date related field not available in table?

I'm using sql server 2008 as a backend for my project.
My database table not contains any date related field then how can i find which records are inserted / updated for particular date ?
I want to perform above operation on existing data from my table
Is it possible? If yes then please let me know.
For existing records in the table, I dont think you can find it. But for the new records, you could create a TRIGGER which will update another table with the primary key and a date field
You can enable Change Tracking option on this table.
Check Here
You could add INSERT and UDPATE triggers to your tables that write the ID of the record being updated and the current date/time to an additional audit table. Then you can query the audit table
CREATE TRIGGER RecordInsertTrigger ON MyTable FOR INSERT
AS
INSERT INTO
AuditTrail
(
RecordID,
ActionDate
)
SELECT
RecordID,
getdate()
FROM
inserted
And then create a similar trigger for UPDATE.
You can extend the AuditTrail table to include other relevant information live UserID etc.