SQL Server Constraints Interview Questions

SQL Server Constraints Interview Questions and Answers

In this article, we will discuss most frequently asked SQL Server Constraints Interview Questions and Answers.

What is Data Integrity?
  1. Data integrity means the data contained in the database is accurate and reliable.
  2. To provide data integrity, RDBMS provides a set of integrity constraints which ensures that data entered into the database is accurate, valid and consistent.
What are the different levels of data integrity in SQL Server?
  1. Entity Integrity (uniquely identify- PK, UQ)
  2. Domain Integrity (Follow defined rule- Check
  3. Referential integrity (relationships- FK)
  4. User-defined integrity

What is Entity integrity?

  1. Entity integrity ensures each row in a table is a uniquely identifiable entity. We can achieve entity integrity in a table by using either PRIMARY KEY or UNIQUE KEY constraints.
  2. In simple word, we can say Entity Integrity ensures that there are no duplicate rows in a table.
What is Referential integrity?
  1. Referential integrity ensures that relationships between tables remain preserved as data is inserted, deleted and modified. We can apply referential integrity using a FOREIGN KEY constraint.
  2. In simple word, we can say that Referential integrity ensures that rows cannot be updated or deleted which are used by other records.

What is Domain Integrity?

  1. Domain integrity ensures that the values going to store in a column must follow some defined rules such as range, type, and format. A database can enforce these rules by using the CHECK KEY constraint.
  2. In simple word, we can say that Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of possible values.
What is user defined integrity?

User-Defined Integrity enforces some specific business rules that do not fall into an entity, domain, or referential integrity categories. Each of these categories of the data integrity can be enforced by the appropriate constraints.

What is a Constraint?

A constraint is a property that is assigned to a column or set of columns in a table which is used to enforce data integrity means it ensures that the data is going to store in a table is valid, consistent and accurate.

Why constraint in SQL?

1. A constraint is used to restrict the insertion of unwanted data in any columns.

2. We can create constraints on single or multiple columns of any table.

3. It maintains the data integrity i.e. accurate data or original data of the table.

What are the different types of Constraints available in SQL Server?

SQL Server supports five constraints for maintaining data integrity those are

  1. UNIQUE KEY constraint
  2. NOT NULL constraint
  3. CHECK KEY constraint
  4. PRIMARY KEY constraint
  5. FOREIGN KEY constraint.

NOTE: Constraints are imposed on columns of a table.

Define the default constraint.
  1. Default constraint is used to fill the column with a default value that is defined during creation of a table if the user does not supply any value while inserting the data.
  2. IDENTITY columns and timestamp columns can’t be associated with a default constraint. 
  3. In simple word, we can say that Default constraints enable the SQL Server to write default value to a column when the user doesn’t specify a value.
  4. A default allows us to specify a constant value, NULL or the run-time value of a system function if no known value exists or if the column is missing in an INSERT statement. 
  5. Let us see an example for understanding this concept
CREATE TABLE Employee
(
  EmpID INT NOT NULL PRIMARY KEY DEFAULT 1000 CHECK(EmpID BETWEEN 0 AND 1000), 
  Name VARCHAR(20) DEFAULT 'PRANAYA'
)
GO

Now insert one record into that table with a default value.

INSERT INTO Employee VALUES(DEFAULT,DEFAULT)

Explain about NOT NULL constraint.

  1. If a NOT NULL constraint is imposed on a column then that column will not allow null values into it.
  2. The NOT NULL Constraint is used to avoid NULL values but accepted duplicate values into a column. 
  3. It enforces that the column will not accept NULL values. The NOT NULL constraints are used to enforce domain integrity as the check constraints.
  4. A table can contain any number of NOT NULL constraints.
  5. We can apply the NOT NULL constraint on any data type column such as integer, character, money, etc.

NOTE: When we INSERT a null value into a column on which the NOT NULL constraint is imposed. The execution of the insert statement is terminated by displaying a user-friendly message telling the reason for termination and also specifies the database, the table and the column where the problem got occurred.

Explain about UNIQUE constraint.

  1. If this constraint is imposed on a column then that column will not allow duplicate values into it.
  2. A UNIQUE constraint is used to avoid duplicate values but accepted null values in a column.
  3. IT enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.
  4. A table can contain any number of UNIQUE constraints.
  5. We can apply the UNIQUE constraint on any data type column such as integer, character, money, etc.

NOTE1: UNIQUE constraint will accept 1 NULL value only.

NOTE2: 

The unique key constraint is used to make sure that there is no duplicate value in that column. Both unique key and primary key enforces the uniqueness of column but there is one difference between them unique key constraint allows null value but the primary key does not allow null value.

NOTE3:

If we insert a duplicate value into a column that contains UNIQUE constraint on it, the statements get terminated by displaying an error message but that error message will not contain the column name where the violation got occurred it only display the constraint name.

UNIQUE KEY, PRIMARY KEY, CHECK and FOREIGN KEY constraints are independent objects under the database which are created and linked with the column of the table. So they have their own identity or name i.e. the reason why if these four constraints are violated they will never tell the column where the violation occurred. They only will display the name.

Actually, a constraint name must be defined by us while creating the table. If not defined by us database server will give a name to that constraint and those names will not be user-friendly for identification so it is always suggested to provide our own name to the constraint for easy identification by adopting a naming convention as following

<columnname>_<constraint type>

Example:

CREATE TABLE CUSTOMER
(
  CID INT CONSTRAINT CID_UNIQUE UNIQUE,
  CNAME VARCHAR(30) UNIQUE,
  AMOUNT MONEY UNIQUE
)
IMPOSING CONSTRAINT ON TABLE:

We can impose constraints on a table in two different ways

  1. Column-level imposing a constraint
  2. Table level imposing a constraint

In the first case, we provide the constraint information inside the column only whereas in the second case we first define all the columns and then we define constraints on the columns.

NOTE: We cannot impose NOT NULL constraint in table level. It is possible only for rest of the four constraints.

Column Level Imposing a Constraint:

CREATE TABLE CUSTOMER
(
  CID INT CONSTRAINT CUSTID_UNIQUE UNIQUE, 
  CNAME VARCHAR(50),
  BALANCE MONEY, 
  CITY VARCHAR(50)
)

Table Level Imposing a Constraint:

CREATE TABLE CUSTOMER
(
  CUSTID INT, 
  CNAME VARCHAR(50), 
  BALANCE MONEY, 
  CITY VARCHAR(50),
  CONSTRAINT CUSTID_UNIQUE UNIQUE(CUSTID)
)

What is composite constraint in SQL Server?

There is no difference in behavior whether the constraint is imposed in table level or column level but if a constraint is imposed in table level we have an advantage of imposing composite constraints. That is one constraint on multiple columns.

For example:

CREATE TABLE BRANCHDETAILS
( 
  CITY VARCHAR(50), 
  BRANCHCODE VARCHAR(10), 
  BRANCHLOCATION VARCHAR (30),
  CONSTRAINT CITY_BC_UNIQUE UNIQUE(CITY, BRANCHCODE)
)

NOTE: The drawback with a NOT NULL constraint is it will allow duplicate values whereas in case of the UNIQUE constraint it will allow null values.

Explain about CHECK constraint.

  1. The CHECK constraint is used to enforce domain integrity.
  2. Domain integrity ensures that the values going to store in a column must follow some defined rules such as range, type, and format. 
  3. In simple word, we can say that Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of possible values.
  4. Check constraints allow us to define an expression for a TABLE that must not evaluate to FALSE for a data modification statement to succeed. 

Example:

CREATE TABLE EMPLOYEE
(
  EMP_ID INT NOT NULL PRIMARY KEY CHECK(EMP_ID BETWEEN 0 AND 1000),
  EMP_NAME VARCHAR(30) NOT NULL, 
  ENTERED_DATE DATETIME NOT NULL CHECK (ENTERED_DATE >= CURRENT_TIMESTAMP),
  DEPT_NO INT CHECK(DEPT_NO > 0 AND DEPT_NO < 100)
)

Check constraints will be useful to limit the range of possible values in a column.

We could create check constraints at two different levels

  1. Column-level check constraints are applied only to the column and cannot reference data in other columns
  2. Table-level check constraints can reference any column within a table but cannot reference columns in other tables

A table can contain any number of check constraints and will apply on any column data type like integer, character, and decimal, date etc.

Example:

CREATE TABLE EMPDETAILS
(
  EID INT UNIQUE NOT NULL, 
  ENAME VARCHAR(30)NOT NULL, 
  SALARY MONEY CHECK(SALARY > 8000), 
  AGE INT CHECK(AGE BETWEEN 18 AND 30), 
  EADDRESS VARCHAR(40) CHECK(EADDRESS IN('HYD','UP','MP'))
)
Go

Test Examples:

INSERT EMPDETAILS VALUES(1,'AA',8001,18,'UP') --ALLOWED
INSERT EMPDETAILS VALUES(2,'AA',8000,31,'HYDERABAD') -- NOT ALLOWED
INSERT EMPDETAILS VALUES(2,'BB',52000,28,'HYD') --ALLOWED

Explain about PRIMARY KEY constraint.

  1. PRIMARY KEY is the combination of UNIQUE and NOT NULL constraint which does not allow either NULL or Duplicate values into a column or columns.
  2. Using the primary key we can enforce entity integrity.
  3. PRIMARY KEY is also used to make a relationship with the FOREIGN KEY constraint on the table.
  4. A table should contain 1 PRIMARY KEY constraint only which can be either on a single or multiple columns i.e. composite primary key also allowed.
  5. Every TABLE should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table.
  6. PRIMARY KEY can apply on any data type like integer, character, decimal, money, etc.

Example:

CREATE TABLE BRANCHES
(
  BCODE INT PRIMARY KEY, 
  BNAME VARCHAR(40), 
  BLOC CHAR(40) PRIMARY KEY
)

When we execute the above query it will display a compilation error that is

Cannot add multiple PRIMARY KEY constraints to table ‘BRANCHES’.

To overcome the above drawback, rewrite the query like below

CREATE TABLE BRANCHES
(
  BCODE INT PRIMARY KEY, 
  BNAME VARCHAR(40), 
  BLOC CHAR(40)
)

Explain about the composite primary key.

  1. When the primary key constructed with more than 1 column is called as composite primary key.
  2. A maximum number of columns are including in composite primary key is 16 columns.
  3. The composite primary key we need to define after all columns definition i.e. at the end of the table definition.
  4. In a composite primary key, each column can accept duplicate values but duplicate combination should not be duplicated.

Let us see an example:

CREATE TABLE BRANCHDETAILS
(
  CITY VARCHAR(40), 
  BCODE INT, 
  BLOC VARCHAR(30), 
  PRIMARY KEY(CITY, BCODE)
)

Now insert some values into the following table and see the difference

NOTE: Primary key is also called as a candidate key.

Explain about FOREIGN KEY constraint.

  1. One of the most important concepts in a database is creating the relationship between database tables.
  2. These relationships provide a mechanism for linking data stores in multiple tables and retrieving it in an efficient manner. 
  3. In order to create a link between two tables, we must specify a FOREIGN KEY in one table that references a column in another table.
  4. FOREIGN KEY constraints are used for relating or binding two tables with each other and then verify the existence of one table data in other tables.
  5. A foreign key in one TABLE points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.
To impose a FOREIGN KEY Constraint we require the following things
  1. We require two tables for binding with each other and those two tables must have a common column for linking the tables.
  2. The common column that is present in both the tables need not have the same name but their data type must be the same.
  3. The common column that is present under the parent table or master table is known as a reference key column and reference key column should not contain duplicate values in it. So we need to impose either UNIQUE or PRIMARY key constraint on that column.
  4. If we impose a primary key constraint on the reference key column that column will also be the identity column of the table.
  5. The common column which is present in the child or detailed table is known as FOREIGN key column and we need to impose a FOREIGN key constraint on the column which refers to reference key column of the master table.
Example: Creating PRIMARY KEY and FOREIGN KEY relation on two tables.

STEP1: Create a table with the name as DEPT by using PRIMARY KEY constraint (Parent table)

CREATE TABLE DEPT
(
  DNO INT PRIMARY KEY, 
  DNAME VARCHAR(30), 
  DLOC CHAR(40)
)
STEEP2: Now insert some values into Parent table like below
INSERT DEPT VALUES (10,'.NET','HYD'),
             (20,'.JAVA','PUNE'),
             (30,'TESTING','DELHI')

STEP3: Creating another table with the name as EMP by using FOREIGN KEY constraint (Child table)

CREATE TABLE EMP
(
  EID INT PRIMARY KEY, 
  ENAME VARCHAR(30), 
  SALARY MONEY, 
  DNO INT FOREIGN KEY REFERENCES DEPT(DNO)
)

STEP4: Now insert reference values into the child table like below

INSERT EMP VALUES (101,'AA', 25000, 10), 
                  (102,'BB', 32000, 20), 
                  (103,'CC', 52000, 30),
                  (104,'DD', 62000, 10), 
                  (105,'EE', 42000, 10)

 

Imposing Foreign key constraint in column level:
CREATE TABLE EMPLOYEE
(
  EMPID INT, 
  ENAME VARCHAR(40), 
  JOB VARCHAR(30), 
  SALARY MONEY,
  DEPTNO INT CONSTRAINT DEPTN0_FK REFERENCES DEPARTMENT(DEPTNO)
)
Imposing foreign key constraint at table level:
CREATE TABLE EMPLOYEE
(
  EMPID INT, 
  ENAME VARCHAR(40), 
  JOB VARCHAR(30), 
  SALARY MONEY,
  DEPTNO INT, 
  CONSTRAINT DEPTN0_FK FOREIGN KEY (DEPTNO) REFERENCES DEPARTMENT(DEPTNO)
)

While imposing a FOREIGN key constraint in table level we need to use explicitly the FOREIGN key clause whereas it is not required while imposing in column level because the constraint is defined beside the foreign key column only.

When we impose FOREIGN KEY constraint and establish the relation between tables the following 3 rules come into the picture

RULE1: Cannot insert a value into the foreign key column provided that value is not existing in the reference key column of the parent (master) table.

Example:

INSERT EMP VALUES (106,’FF’, 75000, 40) –NOT ALLOWED

RULE2: Cannot update the reference key value of a parent table provided that the value has corresponding child record in the child table without addressing what to do with the child records.

Example:

UPDATE DEPT SET DNO = 100 WHERE DNO = 10 –NOT ALLOWED

RULE3: Cannot delete a record from the parent table provided that records reference key value has child record in the child table without addressing what to do with the child record.

Example:

DELETE FROM DEPT WHERE DNO = 20  –NOT ALLOWED

If we want to delete or update a record in the parent table when they have the corresponding child record in the child table we are provided with a set of rules to perform delete and update operations known as DELETE rules and UPDATE rules.

DELETE Rules:
    ON DELETE NO ACTION
    ON DELETE CASCADE
    ON DELETE SET NULL
    ON DELETE SET DEFAULT

UPDATE Rules:
    ON UPDATE NO ACTION
    ON UPDATE CASCADE
    ON UPDATE SET NULL
    ON UPDATE SET DEFAULT

How can we provide the default value for a column?

The default, default value for any column is NULL, provided the column is not imposed with a NOT NULL constraint.

At the time of creating the table, we have a chance of giving our own default value on the column. So that when we insert a record into the table without specifying a value to that column automatically the default value comes into the picture and inserted into the column whereas if we provide a value that provided only will be inserted.

Example:

CREATE TABLE EMPLOYEEE
(
  EMPNO INT, 
  ENAME VARCHAR(50), 
  JOB VARCHAR(30), 
  SALARY MONEY DEFAULT 50000
)
What is SELF REFERENTIAL INTEGRITY?

This is the same as the referential integrity we have learned earlier. In earlier cases, we are binding one column of a table with another column of another table whereas in self-referential integrity we bind a column of a table with another column of the same table i.e. both the foreign key and primary key will be present in one table only.

Explain the steps to view primary key and foreign key relationship ER diagram representation.

  1. Go to open SQL Server management studio
  2. Click on new query option
  3. Go to query option from the main menu bar
  4. Click on design query in editor option
  5. Select primary key and foreign key tables one by one and click on add button
  6. Click on close button

What is the difference between primary key and unique key?

Both primary key and unique key enforces the uniqueness of the column on which they are defined. But by default primary key creates a unique clustered index on the column where are unique key creates a unique non-clustered index by default. Another major difference is that the primary key doesn’t allow NULLs, but unique key allows one NULL only.

What is the difference between primary key and foreign key?

Primary key:

  1. A primary key uniquely identifies a record in the table.
  2. Primary Key can’t accept null values and duplicate values by default,
  3. The primary key is a clustered index and data in the database table is physically organized in the sequence of the clustered index.
  4. We can have only one Primary key in a table.

Foreign key:

  1. A foreign key is a field in the table that is the primary key (or unique key) in another table.
  2. The foreign key can accept null values and duplicate values.
  3. A foreign key does not automatically create an index, clustered or non-clustered. We can manually create an index on the foreign key.
  4. We can have more than one foreign key in a table.

NOTE1: We can’t insert foreign key column value into the table if primary key value not available but the reverse is possible.

NOTE2: We can’t delete primary key value if the foreign key reference is set into the table but the reverse is possible.

CAN A TABLE HAVE MULTIPLE UNIQUE, FOREIGN, AND/OR PRIMARY KEYS?

A table can have multiple unique and foreign keys. However, a table can have only one primary key.

CAN A UNIQUE KEY HAVE NULL VALUES? CAN A PRIMARY KEY HAVE NULL VALUES?

Unique key columns are allowed to hold a single NULL value. The values in a primary key column, however, can never be NULL.

CAN A FOREIGN KEY REFERENCE A NON-PRIMARY KEY?

Yes, a foreign key can actually reference a key that is not the primary key of a table. But a foreign key must reference a unique key.

CAN A FOREIGN KEY CONTAIN NULL VALUES?

Yes, a foreign key can hold NULL values. Because foreign keys can reference unique, non-primary keys – which can hold NULL values – this means that foreign keys can themselves hold NULL values as well.

SUMMARY

In this article, I try to explain most frequently asked SQL Server Constraints Interview Questions and Answers. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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