mysql insert and update dates - mysql

so, I have a table named companies and I want to add 2 columns for insert and update times.
how do I do this? I dont want to add insert and update dates into my query.
this is my create statement
create table companies(
name varchar(20),
city char(10),
numberofemployees int(10),
averagesalary double
);
alter table companies add inserttime datetime, add updatedtime datetime, add id serial;
I need the insert query to look like this:
insert into companies values ("company","bglr",30,400.00)
and need output as
name,city,numberofemployees,averagesalary,inserttime,updatetime
company blr 30 400.00 23:00:11 23:00:11

First of all, you'll have to change your INSERT statement since the number of values doesn't match the number of columns. Luckily, you can specify the subset of columns that correspond to the given values:
INSERT INTO companies(name, city, numberofemployees, averagesalary)
VALUES ('company', 'blgr', 30, 400.00);
As you don't provide values for inserttime and updatetime, default values will be used for new records. Another way to insert records using default values is to put in the DEFAULT keyword instead of a concrete value (please refer to the documentation of INSERT for more details).
In your case the default values should be NULL because you didn't define anything else. To change the DEFAULT value for your columns, you can modify their definitions:
ALTER TABLE companies MODIFY COLUMN inserttime datetime DEFAULT CURRENT_TIMESTAMP;
Having this, inserttime is set to the current time for newly inserted records. Of course, you can also use the DEFAULT clause in CREATE TABLE statements, or while adding the columns.
Next, let's have a look at the updatetime. Usually, you want this to be updated automatically to the current time. This can be achieved in MySQL by specifying an ON UPDATE clause for the default value (details in Automatic Initialization and Updating for TIMESTAMP and DATETIME:
ALTER TABLE companies MODIFY COLUMN
updatetime datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
From now on, updatetime will be set to the current time automatically when a new record is inserted or an existing record is updated.
More information about default values in MySQL can be found in the documentation.

Related

What is automatically populating this column?

I am using MySQL 5.6.1 on a Win 7 64Bit.
I have a standard audit column I add to all my tables called CRT_TS (create timestamp), along with a UPD_TS (update timestamp) column. I had planned on populating these via a before insert trigger and a before update trigger using utc_timestamp().
The UPD_TS column behaves as I expect it to. However, the CRT_TS column seems to be getting automatically populated without my defining a default or trigger for that column.
I was able to reproduce this behavior by running the following script.
create schema `test` default character set utf8 collate utf8_general_ci;
drop table test.TEST_TABLE;
create table test.TEST_TABLE(
TEST_ID int not null auto_increment ,
CRT_TS timestamp not null ,
UPD_TS timestamp not null ,
TEST_ALIAS varchar(64) not null ,
primary key PK_PERM (TEST_ID) ,
unique index UI_PERM_01 (TEST_ALIAS) )
auto_increment = 1001;
insert into test.TEST_TABLE
(TEST_ID
,TEST_ALIAS)
values
(1
,'testing');
select *
from test.TEST_TABLE;
In the above example, the CRT_TS column isn't being supplied a value, and yet it is being populated with the same value what would have been provided by the now() function. The UPD_TS column is populated with all zeros, yet both columns have been defined identically.
My questions is, what is populating the CRT_TS column? I am attempting to set both the UPD_TS and CRT_TS columns to utc_timestamp() value. Even setting the value in a trigger for CRT_TS, the value is overridden.
Thanks for any clarity you can provide.

INSERT current date or time into MySQL

If I create a table with an entity that is suppose to be DATE and when I Insert and leave that column blank shouldn't it display the current date? Same with time?
For example...
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Date DATE,
Time TIME
);
Then I Insert:
INSERT INTO Register (Name)
VALUES ('Howard');
I want it to display on the table:
Howard | 5/6/2014 | 8:30 PM
But instead it displays:
Howard | NULL | NULL
Is this incorrect and if so what am I suppose to Insert to allow the current date and time of insert to display?
Firstly, you should have a PRIMARY KEY in your table.
Secondly, you have not set default values for columns Date and Time. Also, you can't set them separately for the DATE and TIME types – you should use TIMESTAMP type and DEFAULT CURRENT_TIMESTAMP like :
CREATE TABLE Register (
Name CHAR(20) PRIMARY KEY NOT NULL,
Date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Thirdly, if you want to use exactly two columns for date storing, you can set a trigger on INSERT event for this table, like it is shown below :
CREATE TRIGGER default_date_time
BEFORE INSERT ON my_table_name
FOR EACH ROW
BEGIN
SET NEW.Date = CURDATE();
SET NEW.Time = CURTIME();
END;
$$
You need to set a default. So you might think you could do this:
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Date DATE DEFAULT CURRENT_DATE,
Time TIME DEFAULT CURRENT_TIME
);
But that won’t work. You need to use CURRENT_TIMESTAMP and change your DB structure to use the combined TIMESTAMP format:
CREATE TABLE Register
(
Name CHAR(20) NOT NULL,
Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
The reason being is there is no MySQL DEFAULT value for DATE or TIME alone. Some clues to that behavior here:
The DEFAULT value clause in a data type specification indicates a
default value for a column. With one exception, the default value must
be a constant; it cannot be a function or an expression. This means,
for example, that you cannot set the default for a date column to be
the value of a function such as NOW() or CURRENT_DATE. The exception
is that you can specify CURRENT_TIMESTAMP as the default for a
TIMESTAMP column. See Section 11.3.5, “Automatic Initialization and
Updating for TIMESTAMP”.
Here are two options:
Get rid of Date and Time columns and add time stamp
INSERT INTO Register (Name,Ctime) VALUES ('Howard',CURRENT_TIMESTAMP);
If you want to continue with your table structure
INSERT INTO Register (Name,Date,Time) VALUES ('Howard',CURDATE(), CURTIME());
Also Note that date and time are reserved words of MySQL and hence should be quoted with backticks to avoid conflicting with reserved words. Or just rename it according to a table name format.

Values within primary key occasionally changes over time

I got some data defined in a table in a MySQL database like this
CREATE TABLE `T_dev` (
id VARCHAR(20) NOT NULL,
date DATETIME NOT NULL,
amount VARCHAR(9) DEFAULT NULL,
PRIMARY KEY (id,date)
);
I then insert a record, for example
INSERT INTO T_dev VALUES
('10000','2009-08-05 23:00:00','35')
However, one month later I get a report that tells me that this exact record should have amount equal to 30, thus
INSERT INTO T_dev VALUES
('10000','2009-08-05 23:00:00','30')
However, that can´t be done because of the primary key I´ve defined. I would like to overwrite the old record with the new one, but not really change my primary key. Any suggestions?
Thanks.
Alexander
Since the record already exists, you don't use the INSERT statement. Instead use an UPDATE statement to change the value to 30 for that specific id and date combination:
UPDATE T_dev SET amount = '30'
WHERE id = '10000' AND date = '2009-08-05 23:00:00'
Just an observation, your table is a little out of the norm. Typically primary keys are of type INT and your amount would probably be better off as a DECIMAL.
use an update statement
UPDATE T_dev
SET amount = 30
WHERE id=10000 AND date = '2009-08-05 23:00:00'

MYSQL Timestamp Issue

I have a table called "users" and in that table there is a row for each account. In each row there is a column called "created" and in this I need to add the timestamp for when the account was created? So like when the user registers, the timestamp is automatically added. Also, when the values are updated in the row, I want the timestamp to stay the SAME. How can I accomplish this?
Create the table, and apply the default value for your created column.
CREATE TABLE IF NOT EXISTS `Users` (
`User_ID` int(11) NOT NULL,
... all other columns ...
`Created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
There is no need to update the Created (timestamp) when user update the info.
Just update the columns that need a change (e.g. email, address, etc)
using a trigger for the Created column is a bit overkill, I would say. It is better to use the default value instead. A Trigger in my opinion would be better for example a LastUpdated column. i.e. each time a user/account is modified it will update this column.

How to insert the current system date into a db column using mysql

I have three *date fields in a table defined as VARCHAR(45) with a default value of '00-00-0000'. Each of the fields needs the default value of the current system time when a record is created.
I have changed one of the fields from VARCHAR(45) to TIMESTAMP with default of CURRENT_TIMESTAMP, which works great. I think I can only have a single field with Datatype TIMESTAMP per table.
How do I handle the other 2 fields in the tables? I would like to *CURRENT_TIMESTAMP them too.
Thanks
Use the NOW() function:
INSERT INTO yourtable (field1, field2) VALUES ('blahblah', now());
You can use "NOW()" in a MySQL query to fill in the current time for a timestamp column.
You can write Now() to the fields
INSERT INTO table (right_now)
VALUES (Now()):