mmattax mmattax - 1 month ago 8
MySQL Question

Can I use a function for a default value in MySql?

I want to do something like this:



create table app_users
(
app_user_id smallint(6) not null auto_increment primary key,
api_key char(36) not null default uuid()
);



However this results in a error, is there a way to call a function for a default value in mysql?

thanks.

Answer

No, you can't.

However, you could easily create a trigger to do this, such as:

CREATE TRIGGER before_insert_app_users
  BEFORE INSERT ON app_users 
  FOR EACH ROW
  SET new.api_key = uuid();