Type date default sysdate in Mysql - mysql

I have seen this question before but it is not answered, so here it goes:
When creating a table, I have a column with the type Date. I want that the default value is the system date, (Sysdate), but for some reason it does not work and it gives an error (in syntax, which is strange because I am following the Mysql syntax).
create table students(
id integer(10),
name varchar (21) NOT NULL,
surname varchar(30),
grade integer check(grade in(1,2,3),
enrollment date default sysdate,
primary key(id) );
And it gives an error in syntax just at the "sysdate". I have tried with sys_date, sys-date, and it is the same.

Instead of sysdate, try CURRENT_TIMESTAMP like:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)

Related

Using DATETIME SQL datatype, especially with DEFAULT and ON UPDATE

W3schools defines the DATETIME datatype thusly:
A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The
supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'. Adding DEFAULT and ON UPDATE in the column definition to
get automatic initialization and updating to the current date and time
So, I'm trying to create a table that will record the date of each record inserted. I'm trying to record down to the minute, but not the second. I've tried to create the table as such:
create table forum(
postID int(2) AUTO_INCREMENT,
primary key (postID),
title varchar(100),
content varchar(2000),
postTime DATETIME(YYYY-MM-DD hh:mm) DEFAULT ON UPDATE
)
But that produces a syntax error. I've tried modifying it in countless ways, but short of
create table forum(
postID int(2) AUTO_INCREMENT,
primary key (postID),
title varchar(100),
content varchar(2000),
postTime DATETIME
)
nothing seems to be palatable to MySQL workbench. How can I properly express what I'm trying to do?

MySql tables, creating new

it seems like my syntax for the following command is incorrect. The error message points to the default current timestamp. Can someone point out where am I going wrong? Your help is much appreciated as I'm working on my first app. My code is the following:
CREATE TABLE ingredients (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
ingredient VARCHAR(100),
created_at DEFAULT CURRENT_TIMESTAMP,
updated_at DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
You forgot the Data Type ;)
The correct Query is following:
CREATE TABLE ingredients (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
ingredient VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Check out the docs: MySQL Docs | Create Table
You can check your syntax with following tool: SQL Validator

MariaDB Bug with TIMESTAMP, CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP

In MariaDB 5.5 and before there could only be one TIMESTAMP column per
table that had CURRENT_TIMESTAMP defined as its default value. This
limit has no longer applied since MariaDB 10.0.
Source: https://mariadb.com/kb/en/mariadb/timestamp/
I have the following table :
CREATE TABLE oauth_client_details (
client_id VARCHAR(255) PRIMARY KEY,
resource_ids VARCHAR(255),
client_secret VARCHAR(255),
scope VARCHAR(255),
authorized_grant_types VARCHAR(255),
web_server_redirect_uri VARCHAR(255),
authorities VARCHAR(255),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR(4096),
autoapprove VARCHAR(255),
version bigint(20) UNSIGNED DEFAULT '1',
creation_datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
modification_datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
active tinyint(1) UNSIGNED DEFAULT '1'
);
I need:
the creation datetime to be filled with current timestamp on insertion
the modification datetime to be updated with current timestamp on update.
I did an insert and here are the values I got:
creation_datetime : '2016-12-11 20:03:24'
modification_datetime : '2016-12-11 13:03:24'
I was expecting these values to be the same, so why is it now different ?
I would like to store only UTC time and translated it to user locale
at the last moment.
My Spring server use UTC time.
MariaDB :
SELECT ##global.time_zone, ##global.system_time_zone;
|SYSTEM|UTC
It's now 20:03 in my country, so I suppose the wrong value is the modification_datetime field.
I use mariadb:10.1.17 official docker image without any modification to the image.
This is my insert statement :
==> Preparing: insert into oauth_client_details(client_id,authorized_grant_types,access_token_validity,additional_information,active,client_secret,creation_datetime,autoapprove,modification_datetime,resource_ids,web_server_redirect_uri,authorities,refresh_token_validity,scope,version) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
==> Parameters: bo(String), authorization_code,refresh_token(String), 1800(Integer), {"companyId":1,"companyName":"testing"}(String), true(Boolean), $2a$10$h/0tc3qnZj/ZfRrNXf.oiuypEyYXJAJZdHPgy2ZMc1XMAntAMPK(String), null, true(Boolean), null, testinggroup/api(String), http://localhost:8080,http://dev:31735(String), ROLE_CLIENT(String), 3600(Integer), read,write,trust(String), 1(Long)
Does anyone ever had this ?
Edit: I have updated my docker Mariadb from version 10.1.17 to 10.1.19 the latest in date and I still have the same bug.
It appears dates are different because I left in the code a creationDateTime = new DateTime(); in the Model.
It means the server was using DateTime() for creationDateTime and database UTC.

How to initialize date FIELD IN MYSQL

I Wanted to initialize default date field in my table with CURRENT_DATE(); well BENCH gives me errors that is not possible i heard about triggers but it seems to be a little over complicatet for that problem so is there any way to make this in such way
CREATE TABLE Sprzedaz (
Id int unsigned primary key auto_increment,
KlientId int not null,
ProduktNumer int not null,
Ilosc int not null,
Cena float not null,
Data date default CURRENT_DATE(),
check (Data >= now()),
....
);
You can initialize a TIMESTAMP column with this:
Data TIMESTAMP DEFAULT CURRENT_TIMESTAMP
or a DATETIME column (MySQL 5.6+):
Data DATETIME DEFAULT CURRENT_TIMESTAMP
but if you want to initialize a DATE column using MySQL 5.5 you need an INSERT TRIGGER:
CREATE TRIGGER setdate_before_insert BEFORE INSERT ON test
FOR EACH ROW
SET NEW.Data = CURDATE();
and maybe you need also an UPDATE trigger? Please see fiddle here.
Another way to go about this, if you do not mind changing the date type, would be to use a TIMESTAMP and initialize it with TIMESTAMP DEFAULT CURRENT_TIMESTAMP. Your definition would then become:
CREATE TABLE Sprzedaz (
Id int unsigned primary key auto_increment,
KlientId int not null,
ProduktNumer int not null,
Ilosc int not null,
Cena float not null,
Data TIMESTAMP DEFAULT CURRENT_TIMESTAMP, <<<==== change this
check (Data >= now()),
....
);
If you have MySQL version 5.6.5 and above, you can use CURRENT_TIMESTAMP instead of CURRENT_DATE
See http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
So you can't do it with dates but you may be able to change your field to be a TIMESTAMP or DATETIME and Bobs your mothers brother!

MySQL default datetime through phpmyadmin

In an existing database, I've age column (INT). Now I need to set it as dob (DATETIME).
I try doing so through PHPMyAdmin, giving CURRENT_TIMESTAMP as default value as defined by answer with 138 upvotes. However PHPMyAdmin is complaining #1067 - invalid default value for 'dob' as in attached screenshot:
Can someone please suggest why I'm getting that error and how to fix that?
You can't set CURRENT_TIMESTAMP as default value with DATETIME.
But you can do it with TIMESTAMP.
See the difference here.
Words from this blog
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.
Set the type of the field as TIMESTAMP too.
I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..
CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());
You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.
The only field you can use current_time on is a timestamp.
The best way for DateTime is use a Trigger:
/************ ROLE ************/
drop table if exists `role`;
create table `role` (
`id_role` bigint(20) unsigned not null auto_increment,
`date_created` datetime,
`date_deleted` datetime,
`name` varchar(35) not null,
`description` text,
primary key (`id_role`)
) comment='';
drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
on `role`
for each row
set new.`date_created` = now();