mmattax mmattax - 9 months ago 48
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?


Answer Source

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 
  SET new.api_key = uuid();