SQL Tut
SQL Tut
In Part 1 of SQL Server, we have seen, using SSMS to connect to SQL Server. In this part
we will learn creating, altering and dropping a database.
Whether, you create a database graphically using the designer or, using a query, the
following 2 files gets generated.
.MDF file - Data File (Contains actual data)
.LDF file - Transaction Log file (Used to recover the database)
You cannot drop a database, if it is currently in use. You get an error stating - Cannot drop
database "NewDatabaseName" because it is currently in use. So, if other users are
connected, you need to put the database in single user mode and then drop the database.
Part 3 - Creating and Working with tables
The aim of this article is to create tblPerson and tblGender tables and establish primary key
and foreign key constraints. In SQL Server, tables can be created graphically using SQL
Server Management Studio (SSMS) or using a query.
Create Table tblGender
(ID int Not Null Primary Key,
Gender nvarchar(50))
In Part 3 of this video series, we have seen how to create tables (tblPerson and tblGender)
and enforce primary and foreign key constraints. Please watch Part 3, before continuing with
this session.
In this video, we will learn adding a Default Constraint. A column default can be specified
using Default constraint. The default constraint is used to insert a default value into a
column. The default value will be added to all new records, if no other value is specified,
including NULL.
The insert statement below does not provide a value for GenderId column, so the default of
1 will be inserted for this record.
Insert into tblPerson(ID,Name,Email) values(5,'Sam','[email protected]')
On the other hand, the following insert statement will insert NULL, instead of using the
default.
Insert into tblPerson(ID,Name,Email,GenderId) values (6,'Dan','[email protected]',NULL)
To drop a constraint
ALTER TABLE { TABLE_NAME }
DROP CONSTRAINT { CONSTRAINT_NAME }
In Part 3 of this video series, we have seen how to create tables (tblPerson and tblGender)
and enforce primary and foreign key constraints. In Part 4, we have learnt adding a default
constraint. Please watch Parts 3 and 4, before continuing with this session.
Cascading referential integrity constraint allows to define the actions Microsoft SQL Server
should take when a user attempts to delete or update a key to which an existing foreign keys
points.
For example, consider the 2 tables shown below. If you delete row with ID =
1 from tblGender table, then row with ID = 3 from tblPerson table becomes an orphan
record. You will not be able to tell the Gender for this row. So, Cascading referential integrity
constraint can be used to define actions Microsoft SQL Server should take when this
happens. By default, we get an error and the DELETE or UPDATE statement is rolled back.
However, you have the following options when setting up Cascading referential
integrity constraint
1. No Action: This is the default behaviour. No Action specifies that if an attempt is made to
delete or update a row with a key referenced by foreign keys in existing rows in other tables,
an error is raised and the DELETE or UPDATE is rolled back.
2. Cascade: Specifies that if an attempt is made to delete or update a row with a key
referenced by foreign keys in existing rows in other tables, all rows containing those foreign
keys are also deleted or updated.
3. Set NULL: Specifies that if an attempt is made to delete or update a row with a key
referenced by foreign keys in existing rows in other tables, all rows containing those foreign
keys are set to NULL.
4. Set Default: Specifies that if an attempt is made to delete or update a row with a key
referenced by foreign keys in existing rows in other tables, all rows containing those foreign
keys are set to default values.
Check constraint in SQL Server - Part 6
CHECK constraint is used to limit the range of the values, that can be entered for a
column.
Let's say, we have an integer AGE column, in a table. The AGE in general cannot be less
than ZERO and at the same time cannot be greater than 150. But, since AGE is an integer
column it can accept negative values and values much greater than 150.
So, to limit the values, that can be added, we can use CHECK constraint. In SQL Server,
CHECK constraint can be created graphically, or using a query.
The following check constraint, limits the age between ZERO and 150.
ALTER TABLE tblPerson
ADD CONSTRAINT CK_tblPerson_Age CHECK (Age > 0 AND Age < 150)
If the BOOLEAN_EXPRESSION returns true, then the CHECK constraint allows the value,
otherwise it doesn't. Since, AGE is a nullable column, it's possible to pass null for this
column, when inserting a row. When you pass NULL for the AGE column, the boolean
expression evaluates to UNKNOWN, and allows the value.
If a column is marked as an identity column, then the values for this column are
automatically generated, when you insert a new row into the table. The following, create
table statement marks PersonId as an identity column with seed = 1 and Identity Increment =
1. Seed and Increment values are optional. If you don't specify the identity and seed they
both default to 1.
Create Table tblPerson
(
PersonId int Identity(1,1) Primary Key,
Name nvarchar(20)
)
In the following 2 insert statements, we only supply values for Name column and not
for PersonId column.
Insert into tblPerson values ('Sam')
Insert into tblPerson values ('Sara')
If you select all the rows from tblPerson table, you will see that, 'Sam' and 'Sara' rows have
got 1 and 2 as PersonId.
Now, if I try to execute the following query, I get an error stating - An explicit value for the
identity column in table 'tblPerson' can only be specified when a column list is used and
IDENTITY_INSERT is ON.
Insert into tblPerson values (1,'Todd')
So if you mark a column as an Identity column, you dont have to explicitly supply a value for
that column when you insert a new row. The value is automatically calculated and provided
by SQL server. So, to insert a row into tblPerson table, just provide value for Name column.
Insert into tblPerson values ('Todd')
Delete the row, that you have just inserted and insert another row. You see that the value for
PersonId is 2. Now if you insert another row, PersonId is 3. A record with PersonId = 1, does
not exist, and I want to fill this gap. To do this, we should be able to explicitly supply the
value for identity column. To explicitly supply a value for identity column
1. First turn on identity insert - SET Identity_Insert tblPerson ON
2. In the insert query specify the column list
Insert into tblPerson(PersonId, Name) values(2, 'John')
As long as the Identity_Insert is turned on for a table, you need to explicitly provide the value
for that column. If you don't provide the value, you get an error - Explicit value must be
specified for identity column in table 'tblPerson1' either when IDENTITY_INSERT is set to
ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
After, you have the gaps in the identity column filled, and if you wish SQL server to calculate
the value, turn off Identity_Insert.
SET Identity_Insert tblPerson OFF
If you have deleted all the rows in a table, and you want to reset the identity column value,
use DBCC CHECKIDENT command. This command will reset PersonId identity column.
DBCC CHECKIDENT(tblPerson, RESEED, 0)
How to get the last generated identity column value in SQL Server -
Part 8
From the previous session, we understood that identity column values are auto generated.
There are several ways in sql server, to retrieve the last identity value that is generated. The
most common way is to use SCOPE_IDENTITY() built in function.
SCOPE_IDENTITY() returns the last identity value that is created in the same session
(Connection) and in the same scope (in the same Stored procedure, function, trigger). Let's
say, I have 2 tables tblPerson1 and tblPerson2, and I have a trigger on tblPerson1 table,
which will insert a record into tblPerson2 table. Now, when you insert a record into
tblPerson1 table, SCOPE_IDENTITY() returns the idetentity value that is generated in
tblPerson1 table, where as @@IDENTITY returns, the value that is generated in tblPerson2
table. So, @@IDENTITY returns the last identity value that is created in the same session
without any consideration to the scope. IDENT_CURRENT('tblPerson') returns the last
identity value created for a specific table across any session and any scope.
In brief:
SCOPE_IDENTITY() - returns the last identity value that is created in the same session and
in the same scope.
@@IDENTITY - returns the last identity value that is created in the same session and across
any scope.
IDENT_CURRENT('TableName') - returns the last identity value that is created for a specific
table across any session and any scope.
We use UNIQUE constraint to enforce uniqueness of a column i.e the column shouldn't
allow any duplicate values. We can add a Unique constraint thru the designer or using a
query.
To add a unique constraint using SQL server management studio designer:
1. Right-click on the table and select Design
2. Right-click on the column, and select Indexes/Keys...
3. Click Add
4. For Columns, select the column name you want to be unique.
5. For Type, choose Unique Key.
6. Click Close, Save the table.
To create the unique key using a query:
Alter Table Table_Name
Add Constraint Constraint_Name Unique(Column_Name)
Both primary key and unique key are used to enforce, the uniqueness of a column.
So, when do you choose one over the other?
A table can have, only one primary key. If you want to enforce uniqueness on 2 or more
columns, then we use unique key constraint.
What is the difference between Primary key constraint and Unique key constraint?
This question is asked very frequently in interviews.
1. A table can have only one primary key, but more than one unique key
2. Primary key does not allow nulls, where as unique key allows one null