Friday , December 27 2024

How To Create Default Constraint On SQL Server

 

When we create our tables, we set some columns to be null, so that some columns are never null. If the columns that we create as nullable are sometimes null, then we may want to set the default value to this column if the value is not given to this column. Let’s continue with an example to make it more descriptive.

Let’s create a table as follows. In this table, the names of the city and the famous food of these cities will be stored.

The CityName column is defined as NOT NULL as you see below. So this column will never be null. The FamousFood column is defined as NULL. So this column could also be null. Because there might be cities without famous food.

Let’s do a few insert operations to our table as follows and then we’ll select values from the table.

As you can see, we set the FamousFood column for Ankara as null.

Let’s define a default constraint for FamousFood column with the help of the following script. This default constraint will set the value of the column to “There is not famous food” by default if the FamousFood column is null.

After defining the default Constaint, add a few records as follows and see the result.

As you can see, we did not insert a famous food record for Istanbul. For this reason, by default, “There is not Famous Food” was set to FamousFood column.

Loading

About dbtut

We are a team with over 10 years of database management and BI experience. Our Expertises: Oracle, SQL Server, PostgreSQL, MySQL, MongoDB, Elasticsearch, Kibana, Grafana.

Leave a Reply

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