Connecting To SQL Server Using SSMS
Connecting To SQL Server Using SSMS
SQL Server Management Studio (SSMS), is the client tool that can be used to write and
execute SQL queries. To connect to the SQL Server Management Studio
1. Click Start
2. Select All Programs
3. Select Microsoft SQL Server 2005, 2008, or 2008 R2 (Depending on the version installed)
4. Select SQL Server Management Studio
SSMS is a client tool and not the Server by itself. Usually database server (SQL Server), will be
on a dedicated machine, and developers connect to the server using SSMS from their respective
local (development) computers.
Developer Machines 1,2,3 and 4 connects to the database server using SSMS.
Creating, altering and dropping a database - Part 2
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.
Alter Database DatabaseName Set SINGLE_USER With Rollback Immediate
With Rollback Immediate option, will rollback all incomplete transactions and closes the
connection to the database.
Note: System databases cannot be dropped.
Creating and Working with tables - Part 3
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.
The following statement creates tblGender table, with ID and Gender columns. The following
statement creates tblGender table, with ID and Gender columns. ID column, is the primary
key column. The primary key is used to uniquely identify each row in a table. Primary key does
not allow nulls.
Create Table tblGender
(ID int Not Null Primary Key,
Gender nvarchar(50))
In tblPerson table, GenderID is the foreign key referencing ID column in tblGender table.
Foreign key references can be added graphically using SSMS or using a query.
Foreign keys are used to enforce database integrity. In layman's terms, A foreign key in one
table points to a primary key in another table. The foreign key constraint prevents invalid data
form being inserted into the foreign key column. The values that you enter into the foreign key
column, has to be one of the values contained in the table it points to.
Default constraint in sql server - Part 4
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','s@s.com')
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','d@d.com',NULL)
To drop a constraint
ALTER TABLE { TABLE_NAME }
DROP CONSTRAINT { CONSTRAINT_NAME }
Cascading referential integrity constraint - Part 5
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.
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.
Unique key constraint - Part 9
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
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
If you want to select all the columns, you can also use *. For better performance use the
column list, instead of using *.
SELECT *
FROM Table_Name
Note: Text values, should be present in single quotes, but not required for numeric values.
Group by clause is used to group a selected set of rows into a set of summary rows by the
values of one or more columns or expressions. It is always used in conjunction with one or more
aggregate functions.
I want an sql query, which gives total salaries paid by City. The output should be as shown
below.
Note: If you omit, the group by clause and try to execute the query, you get an error - Column
'tblEmployee.City' is invalid in the select list because it is not contained in either an aggregate
function or the GROUP BY clause.
Now, I want an sql query, which gives total salaries by City, by gender. The output should be as
shown below.
Query for retrieving total salaries by city and by gender: It's possible to group by multiple
columns. In this query, we are grouping first by city and then by gender.
Select City, Gender, SUM(Salary) as TotalSalary
from tblEmployee
group by City, Gender
Now, I want an sql query, which gives total salaries and total number of employees by City, and
by gender. The output should be as shown below.
Query for retrieving total salaries and total number of employees by City, and by gender:
The only difference here is that, we are using Count() aggregate function.
Select City, Gender, SUM(Salary) as TotalSalary,
COUNT(ID) as TotalEmployees
from tblEmployee
group by City, Gender
Filtering Groups:
WHERE clause is used to filter rows before aggregation, where as HAVING clause is used to
filter groups after aggregations. The following 2 queries produce the same result.
Filtering groups using HAVING clause, after all aggrgations take place:
Select City, SUM(Salary) as TotalSalary
from tblEmployee
group by City
Having City = 'London'
From a performance standpoint, you cannot say that one method is less efficient than the other.
Sql server optimizer analyzes each statement and selects an efficient way of executing it. As a
best practice, use the syntax that clearly describes the desired result. Try to eliminate rows that
you wouldn't need, as early as possible.