TimeStamp column always gets zero value - mysql

I have the following query to set a default value to a column:
ALTER TABLE tableName ADD COLUMN testDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
But I see 0000-00-00 00:00:00 for testDate column in newly inserted rows.
I would like to see current date and time in it.
Can anybody explain why this might be happening?

Data, you specified in your INSERT query, override default values of column, i.e. default values works if no data set for column.
See my fiddle.

Default values only work if the value is not defined in the query.
This will use the default value for test:
INSERT INTO mytable(userid, email) VALUES(42, 'info#example.org');
While this will override the default value of test:
INSERT INTO mytable(userid,email,test/*here is when it goes wrong, you shouldn't mention the column in your insert statement at all*/) VALUES(42,'bush#example.did','2001-09-11 00:00:00');

Related

mysql insert and update dates

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.

INSERT INTO using subquery is telling me an uninvolved field is the error?

I'm not entirely sure how to explain what's happening but basically I'm trying to insert values into my table using a subquery and it's telling me that I'm getting an error because a field that is not involved in the query at all does not have a default value.
INSERT INTO customerPayment (customerOrderId)
SELECT ID FROM customerOrder
WHERE customerOrder.orderStateId = (
SELECT ID
FROM orderState
WHERE orderState.state = "Payment Recieved"
);
ERROR 1364 (HY000): Field 'total' doesn't have a default value
And then when I go into the table itself to try and set a default value for total, it then tells me I have an invalid default value for another unrelated field.
ALTER TABLE customerPayment ALTER total SET DEFAULT 0.0;
ERROR 1067 (42000): Invalid default value for 'paymentDate'
It may be relevant to note that 'paymentDate' currently has a default value of curdate().
From what I can see, the total column was created with NOT NULL condition but wasn't assigned with any default value. Something like this example:
total DECIMAL(4,4) NOT NULL,
And it seems CURDATE() or CURRENT_DATE() can't be assigned as default value from my testing. Instead, the column datatype should be TIMESTAMP or DATETIME then can only assign with default value of CURRENT_TIMESTAMP() or NOW(). So, maybe the first step is to change the paymentDate datatype and default value like:
ALTER TABLE customerPayment MODIFY COLUMN `paymentDate` TIMESTAMP NOT NULL DEFAULT NOW();
Then you can proceed with modifying the total column like:
ALTER TABLE customerPayment MODIFY COLUMN total DECIMAL(4,4) NOT NULL DEFAULT 0.0;
Then probably you can do your INSERT after that.
Here's a fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4af3d11f90916469d8fbe61011b3fcab

Mysql Date Default insert in 1970-01-01

I am inserting an empty date-field, but a default value 1970-01-01 gets inserted automatically. Why?
I even changed the Date structure to allow null, set Default as Null, still it's inserting 1970-01-01.
It's the default behavior of MySQL, check in the Database that the field can be NULL.
Check this: old post
You are most likely inserting an empty string. Inserting an entry string will result in 1970-01-01 being written instead. You have to really insert NULL if you don't want this to happen.
What you want to do is:
INSERT INTO table
SET datefield = NULL
Not "NULL" but NULL Otherwise it will read it as a string and not as NULL
You can also just don't set the column at all in your insert and than it will use NULL as well

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.

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()):