In MySQL, The DEFAULT keyword is used to specify a default value for a column when a new record is inserted into a table, and the value for that column is not provided in the INSERT statement.
CREATE TABLE tableName ( columnName1 data_type DEFAULT default_value, columnName2 data_type DEFAULT default_value, );
In the above command, we have declared "columnName1", and "columnName2" as column names.
`data_type` is the data type of the column.
`default_value` is the default value assigned to the column.
Using the below command, we are creating the table named `products` with columns such as `product_id`, `product_name`, `product_category`, `product_price` and `product_added_date`
CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(50), product_category VARCHAR(50), product_price INT DEFAULT 300, product_added_date DATE DEFAULT CURRENT_DATE );
In `product_added_date` and `product_price` we have added a DEFAULT KEYWORD so while inserting a new record in the table and no value is provided during an INSERT statement, then `product_price` and `product_added_date` column will column default values.
So, Now if we try to insert data into the table, if we don't specify a value for a column with a default, the default value will be used.
INSERT INTO products (product_id, product_name, category) VALUES (pro1, 'iPad', 'GADGETS');
Now Output will be `product_added_date` will be set to the current date (as per the default), and the `price` will be set to 300 (as per the default).
We can also use the DEFAULT keyword when updating existing records in the table.
UPDATE products SET price = DEFAULT WHERE product_id = 'pro1';
This will set the `price` column back to its default value for the specified record.
using the below command, we can add DEFAULT KEYWORD to an Existing Table in SQL.
ALTER TABLE products ALTER COLUMN isOutOfStock SET DEFAULT 1;
In the above command, we have added a DEFAULT Value in Integer where `0` will be considered as `false` and `1` will be considered as `true` value