insert Default value to database

RMAG news

Certainly! In the context of databases, default values are predefined values assigned to a column if no value is specified during the insertion of a record. Here’s a real-world example using a Customer table:

Suppose you have a Customer table with a column for the customer’s account status. You want new customers to have a default account status of ‘Active’ unless specified otherwise. Here’s how you might define the table with a default value:

CREATE TABLE Customer (
customer_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255) NOT NULL,
account_status VARCHAR(50) DEFAULT ‘Active’
);

Now, when you insert a new customer without specifying the account_status, it will automatically be set to ‘Active’:

INSERT INTO Customer (customer_name)
VALUES (‘Alice Smith’);

After this insertion, the account_status for ‘Alice Smith’ will be ‘Active’ by default. If you need to set a different status during insertion, you can specify it like this:

INSERT INTO Customer (customer_name, account_status)
VALUES (‘Bob Johnson’, ‘Inactive’);

In this case, ‘Bob Johnson’ will have an account_status of ‘Inactive’ because it was explicitly set during the insertion. Default values are particularly useful for setting initial states or fallback values for records in a database.

Leave a Reply

Your email address will not be published. Required fields are marked *