SQL Server – Difference Between Primary Key and Unique Key In MS Sql Server

Both PRIMARY KEY and UNIQUE KEY enforces the Uniqueness of the values (i.e. avoids duplicate values) on the column[s] on which it is defined. Also these key’s can Uniquely identify each row in database table.

Primary Key:

  • Can be only one in a table
  • It never allows null values
  • Primary Key is a unique key identifier and can not be null
  • By default it adds a clustered index
  • A table can have only one PRIMARY KEY Column[s]
  • We can generated ID automatically with the help of Auto Increment field. Primary key supports Auto Increment value.
  • Primary key can be related with another table’s as a Foreign Key.

Unique Key:

  • Can be more than one unique key in one table
  • Unique key can have null values(only single null is allowed)
  • It can be a candidate key
  • Unique key can be null But only one Null value.
  • By default it adds a UNIQUE non-clustered index
  • A table can have more than one UNIQUE Key Column[s]
  • Unique Constraint doesn’t supports Auto Increment value.
  • Unique Constraint can not be related with another table’s as a Foreign Key.

Share this:
Share

SQL Server – STUFF function in MS SQL Server

The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

Syntax:
STUFF ( character_expression , start , length , replaceWith_expression )

Arguments:

character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

start
Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.


PolicyBazaar IN CPL - Personal Loan

length
Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

replaceWith_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data. This expression will replace length characters of character_expression beginning at start.

Example:
SELECT STUFF(‘abcdef’, 2, 3, ‘ijklmn’)

Output:
aijklmnef

Share this:
Share