Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 897
mmattax Avatar asked Nov 06 '08 21:11

mmattax


People also ask

How do I find the default value in MySQL?

MySQL | DEFAULT() Function The DEFAULT() function returns the default value for table column. DEFAULT value of a column is a value used in the case, there is no value specified by user. In order, to use this function there should be a DEFAULT value assign to the column. Otherwise, it will generate an error.

How do I change the default value in MySQL?

To change a default value, use ALTER col_name SET DEFAULT : ALTER TABLE mytbl ALTER j SET DEFAULT 1000; Default values must be constants. For example, you cannot set the default for a date-valued column to NOW( ) , although that would be very useful.

What is default SQL function?

The DEFAULT constraint is used to set a default value for a column. The default value will be added to all new records, if no other value is specified.

Can we add default value using alter?

You can use the ALTER TABLE statement to add, change, or remove the default value for a column.


1 Answers

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(); 
like image 157
Harrison Fisk Avatar answered Oct 11 '22 02:10

Harrison Fisk