Get Started: SQL DEFAULT Constraint

In This Article, You Will Know About SQL DEFAULT Constraint.

Before moving ahead, let’s know a bit about the SQL CHECK Constraint.

Table of Contents

SQL DEFAULT Constraint

The SQL DEFAULT Constraint is used to assign a default value to the column.

If not any other value is specified, then the default value is applied to all new records.

SQL DEFAULT on CREATE TABLE

My SQL / SQL Server

Example: Use the DEFAULT Constraint to return the data based on a rule.

				
					CREATE TABLE Student_info  (
	Serial Number int NOT NULL,
	Name char(10),
	Class char(10),
	Subject char(10) DEFAULT 'Eco'
);
				
			

The DEAFULT Constarint value is also used for inserting value by using GETDATE():

Example: Use the DEFAULT Constraint to return the data based on a rule.

				
					CREATE TABLE Student_info (
	Serial Number int NOT NULL,
	Name char(10),
	Class char(10),
	Date date DEFAULT GETDATE()
);

				
			

SQL DEFAULT on ALTER TABLE

Apply DEFAULT after the table is created.

SQL Server

Syntax:

				
					ALTER TABLE Table_Name
ADD CONSTRAINT Constraint_Table_Name
DEFAULT value FOR Table_Name;
				
			

Example: Use the DEFAULT Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
ADD CONSTRAINT Table_constraint
DEFAULT 'Eco' FOR Subject;
				
			

MySQL

Syntax:

				
					ALTER TABLE Table_Name
ALTER Column_Name SET DEFAULT value;
				
			

Example: Use the DEFAULT Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
ALTER Subject SET DEFAULT ‘Eco’;
				
			

DROP a DEFAULT Constraint

SQL Server

Syntax:

				
					ALTER TABLE Table_Name
ALTER COLUMN Column_Name DROP DEFAULT;
				
			

Example: Use the DEFAULT Constraint to return the data based on a rule.

				
					ALTER TABLE Student_Info
ALTER COLUMN Subject DROP DEFAULT;
				
			

MySQL Server

Syntax:

				
					ALTER TABLE Table_Name
ALTER Column_Name DROP DEFAULT;
				
			

If you find anything incorrect in the above-discussed topic and have further questions, please comment below.

Connect on:

1 thought on “Get Started: SQL DEFAULT Constraint”

Leave a Comment

Stay in the loop

codingstreets