In SQL, the DEFAULT constraint is used to specify a default value for a column when a new row is inserted into a table. It ensures that if no explicit value is provided for the column during an INSERT operation, the default value will be used instead. The DEFAULT constraint can be applied during table creation or modified later using the ALTER TABLE statement. Here's an example of how to use the DEFAULT constraint:
sql
CREATE TABLE table_name (
column_name data_type DEFAULT default_value,
...
);
To add the DEFAULT constraint to an existing column using ALTER TABLE:
sql
ALTER TABLE table_name
ALTER COLUMN column_name SET DEFAULT default_value;
To drop the DEFAULT constraint from a column using ALTER TABLE:
sql
ALTER TABLE table_name
ALTER COLUMN column_name DROP DEFAULT;
Replace `table_name` with the name of the table, `column_name` with the name of the column you want to apply or modify the DEFAULT constraint on, and `default_value` with the desired default value for the column.
Here's an example that demonstrates the usage of the DEFAULT constraint:
sql
CREATE TABLE employees (
id INT,
name VARCHAR(50) DEFAULT 'Unknown',
hire_date DATE DEFAULT GETDATE()
);
In this example, the "employees" table has a "name" column with a default value of 'Unknown' and a "hire_date" column with a default value of the current date obtained using the GETDATE() function.
The DEFAULT constraint provides a convenient way to assign default values to columns, ensuring that data is populated even when no explicit value is provided. It can be used to handle scenarios where the absence of a value should be substituted with a predetermined default value.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc