SQL DEFAULT Constraint

SQL DEFAULT Constraint

SQL DEFAULT Constraint

In SQL, the DEFAULT constraint is used to specify a default value for a column in a table. When a new row is inserted into the table, if a value for the column is not specified, the default value will be used instead.

Here is an example of how to define a DEFAULT constraint in SQL:

				
					CREATE TABLE employees (
   id INT PRIMARY KEY,
   name VARCHAR(50),
   department VARCHAR(50),
   salary DECIMAL(10,2) DEFAULT 50000.00
); 

				
			

In this example, we have defined a table called “employees” with four columns: “id”, “name”, “department”, and “salary”. The salary column has a DEFAULT constraint that specifies a default value of 50000.00.

Here is an example of how to insert data into the “employees” table without specifying a value for the salary column:

				
					INSERT INTO employees (id, name, department)
VALUES (1, 'John Doe', 'Sales'); 

				
			

In this example, we are inserting a new row into the “employees” table with values for the “id”, “name”, and “department” columns. Since a value for the salary column is not specified, the default value of 50000.00 will be used.

Here is an example of how to insert data into the “employees” table with a specified value for the salary column:

				
					INSERT INTO employees (id, name, department, salary)
VALUES (2, 'Jane Smith', 'Marketing', 75000.00); 

				
			

In this example, we are inserting a new row into the “employees” table with values for the “id”, “name”, “department”, and “salary” columns. Since a value for the salary column is specified, the default value will not be used.

In summary, the DEFAULT constraint is used to specify a default value for a column in SQL. It is useful for setting a default value that will be used when a value is not specified during an INSERT operation.

Join To Get Our Newsletter
Spread the love