MySQL Tutorial
The DEFAULT
constraint in MySQL is used to assign a default value to a column when no value is provided during an INSERT
operation. This ensures that fields have a valid value even if the user doesn't explicitly enter one.
CHAR
, VARCHAR
, INT
, DATE
, FLOAT
, and other data types.NULL
values.TEXT
, BLOB
, or JSON
data types.CREATE TABLE table_name ( column1 data_type DEFAULT default_value, column2 data_type );
The following SQL sets a DEFAULT
value for the "City" column when the "Persons" table is created:
age
→ Default value is 18
if no age is provided.city
→ Default is 'Unknown'
if no city is specified.admission_date
→ Uses CURRENT_DATE
to store the current date if not specified.To create a DEFAULT
constraint on the "City" column when the table is already created, use the following SQL:
age
column will now be 20 instead of 18.To drop a DEFAULT
constraint, use the following SQL:
city
column will no longer have a default value.NULL
value.