Welcome to this SQL DEFAULT Constraint tutorial! Today, we're going to learn about a powerful tool in SQL that helps ensure the integrity of your database. Let's dive in! 💡
In simple terms, a DEFAULT Constraint is a feature in SQL that allows you to provide a default value for a column when no value is provided during data insertion. This is especially useful when dealing with columns that require certain standard values or when you want to prevent null values.
The SQL syntax for creating a table with a DEFAULT Constraint looks like this:
CREATE TABLE Table_Name (
Column_Name Data_Type DEFAULT Default_Value,
...
);Let's create a table for a simple library system:
CREATE TABLE Books (
BookID INT PRIMARY KEY,
Title VARCHAR(100) NOT NULL,
Author VARCHAR(100),
Publisher VARCHAR(100) DEFAULT 'Unknown Publisher'
);In the example above, we've set the 'Publisher' column to have a default value of 'Unknown Publisher'. If no publisher is specified during data insertion, the default value will be used.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Department VARCHAR(100) DEFAULT 'Undefined',
Salary DECIMAL(10, 2) DEFAULT 0
);In this example, we've set the 'Department' and 'Salary' columns to have default values. If no department or salary is specified during data insertion, the default values will be used.
What is the purpose of a DEFAULT Constraint in SQL?
Stay tuned for more SQL tutorials, and remember to practice regularly to master this powerful tool! 💡