To verify if SQL Server Express is working on our machine: Control Panel -> Adminitrative Tools -> Services -> SQL Server (SQLEXPRESS) -> Start if not already started.
Types of Authentication in SQL Server are:
- Windows Authentication: The identity of the client on the Domain of the OS / Network is used by SQL Server to allow or deny access to the resources in the database
- SQL Server Authentication: The permissions to the client are granted based on the identity which was created and stored in SQL Server database.
Note: The default installation of Express Edition only Supports Windows Authentication.
Steps for Configuring SQL Server to support both the types of Authentication:
Start -> Programs -> Microsoft SQL Server 2005 -> SQL Server Management Studio -> Connect ->
- Right-click on Root of the Tree -> Properties -> Select Security -> Check SQL Server and Windows Authentication Mode.
- Expand Security -> Logins -> Select User "sa" -> Right Click - Properties -> Set Password ->
- Also Select Status (on left side) -> Check Login Enabled.
- Disconnect and Connect again with SQL Server Authentication so that we are sure the above steps were performed correctly.
Note: SQL Server Management must be already installed on the machine.
System databases in SQL Server
Master
The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care. For this reason, it is vital to make regular backups of this database.
This database includes information such as system logins, configuration settings, linked servers, and general information regarding the other system and user databases for the instance. The master database also holds extended stored procedures, which access external processes, allowing you to interact with features such as the disk subsystem and system API calls.
Model: Model is essentially a template database used in the creation of any new user database created in the instance. You can place any stored procedures, views, users, etc. in the model database so that when a new database is created, the database will contain the objects you have placed in the model database.
Tempdb
As its name implies, tempdb holds temporary objects such as global and local temporary tables and stored procedures.
This database is recreated every time SQL Server starts, and the objects contained in it will be based upon the objects defined in the model database. In addition to these objects, tempdb also houses other objects such as table variables, results sets from table-valued functions, and temporary table indexes. Because tempdb will hold these types of objects for all of the databases on the SQL Server instance, it is important that the database is configured for optimal performance.
Msdb
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
Types of SQL Statements
- Data Definition Language (DDL) : Create, Alter, Drop, Truncate
- Data Manipulation Language (DML) : Insert , Update , Delete
- Data Query Language(DQL) : Select
- Transaction Control Language (TCL) : Commit , RollBack , SavePoint
- Data Control Language (DCL) : Grant , Revoke
CREATE DATABASE
Create Database DemoDb
Use DemoDb (To use the newly created database)
sp_helpdb DemoDb (Describes the structure of a database)
Data types in SQL Server
- Numeric: TinyInt, SmallInt, Int, BigInt, Decimal, Numeric, Float, Real, Bit
- String : Char, Varchar, NChar, NVarChar, Text, NText, Varchar(Max)
- Currency: Money , SmallMoney
- Date and Time : DateTime, SmallDateTime
- Binary: Binary, VarBinary, VarBinary(Max)
- Miscellaneous : Table , Cursor, Sql_Variant, TimeStamp, Image , Xml
CREATE TABLE
CREATE TABLE [dbo].[Department](
[DeptId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[DeptName] [varchar](50) NOT NULL,
[DateOfFormation] [datetime] NULL
)
CREATE TABLE [dbo].[Employee](
[EmpId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[EmpName] [varchar](50) NOT NULL,
[BasicSalary] [money] NOT NULL,
[Allowances] [money] NOT NULL,
[Deductions] [money] NOT NULL,
[DeptId] [int] NOT NULL,
[DateOfBirth] [datetime] NOT NULL,
)
ALTER TABLE
Alter Table <table name > Add <column name> <data type>
Alter Table <table name> Alter Column <column name> <data type>
Alter Table <table name> Drop Column <column name>
Ex:
Alter table Employee add Designation varchar(20)
Alter table Employee alter column Designation varchar(50) NOT NULL
Alter table Employee drop column Designation
DROP TABLE
Drop Table <TableName>
*DDL (Create, Alter, Drop) Statements cannot be rolledback.
INSERT
Syntax:
Insert into <table name> (column list) values (value1,value2...)Ex: INSERT INTO [Employee](EmpName,BasicSalary,Allowances,Deductions,DeptId,DateOfBirth,Location,Designation)VALUES ('E1',10000,1000,200,1,'1/1/1980','Hyderabad','Manager')
Note- For inserting NULL value into a column either column name can be skipped or NULL can be used for value
Set IDENTITY_INSERT <tablename> ON : Allows to insert value for Identity column - This can be done on only one table at a time
UPDATE
Syntax:
update <table name> set col1 = val1 , col2 = val2 Ex: update Employee Set EmpSalary = EmpSalary + 100 where EmpId=1
DELETE
Syntax:
delete from <table name> [where expression]
Delete from Employee where EmpId=4 -Deletes only one record
Delete from Employee -Deletes all the records from the Employee table
TRUNCATE
It is functionally identical to the Delete statement but is much faster when compared to delete as Delete removes rows one at a time and records an entry in the transaction log for each deleted row so the delete execution is slower when compared to truncate.
Records deleted using truncate cannot be rolled back. Also the identity column value is reset.
Syntax: truncate table <table name>
SELECT
SELECT select_list [ INTO new_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ]
Examples:
Select * From Employee
Select EmpId,EmpName,BasicSalary From Employee]
It is recommended to always replace "*" with column names in the select statement. By doing this we can provide only the required columns and this optimizes the performance of the query.
- Select EmpId AS ID, EName = EmpName From Employee – Aliasing a Column
- Select DISTINCT BasicSalary From Employee
- Select IDENTITYCOL from Employee
- Select TOP 3 * From Employee
- Select TOP 50 PERCENT * From Employee
- Select cast(EmpName as varchar(5)) as ShortName From Employee
- Select * From Employee Order By EmpName, BasicSalary DESC.
Note ntext, text, or image columns cannot be used in an ORDER BY clause.
Null values are treated as the lowest possible values.
Operators:
Arithmetic operators |
+ , - , * , / , % |
|
Basic Relational operators |
= , > , < , >= , <= , ! , != , <> , !> , !< |
|
Logical operators |
And , or , Not |
|
Advanced Relational operators |
In , Not In , Is Null , Is Not Null , Between , Not Between , Like , Not Like, Any, ALL |
update <table name> set col1 = val1 , col2 = val2
Ex:
update Employee Set EmpSalary = EmpSalary + 100 where EmpId=1
Select EmpName, BasicSalary + Allowances - Deductions As Salary from Employee
Select * from Employee where BasicSalary > 2000 and Designation = 'clerk'
Select * from Employee where Designation In ('clerk', 'manager') - case insensitive comparison is done
Select * from Employee where DateOfBirth between '12-10-1975' and '12-10
1995'
Select * from Employee where BasicSalary not between 10000 and 20000
Select * from Employee where BasicSalary is null
Select * from Employee where BasicSalary is not null
Select * From Employee where BasicSalary > SOME (Select BasicSalary from
Employee where DeptId=2)
Select * From Employee where BasicSalary > ALL (Select BasicSalary from Employee where DeptId=2)
|
Wild card |
Matches |
|
% |
Represents a set of characters |
|
_ |
Represents any one character |
|
[ ] |
Any single character within the specified range |
|
[^] |
Any single character not within the specified range |
Select * from Employee where EmpName like 'B%'
Select * from Employee where EmpName like '___'
Select * from Employee where EmpName like 'B__'
Select * from Employee where EmpName like '[a-c]%'
Select * from Employee where EmpName like '[^a-c]%'
Select * from Employee where EmpName like 'A[a-c]%'
Select * from Employee where EmpName like '%\_%' escape '\'
Aggregate Functions
These functions ignore NULL values
-
Select AVG(BasicSalary), Count(*), MAX(BasicSalary), MIN(BasicSalary), SUM(BasicSalary) From Employee
Compute and Compute by
Select * From Employee Compute Sum(BasicSalary), SUM(Allowances)
Select EmpId, EmpName, Location, DeptId, BasicSalary From Employee order by Location, DeptId
Compute Sum(BasicSalary) by Location, DeptId
Compute Sum(BasicSalary) by Location
To Create another table with data from existing table
EXEC sp_dboption 'ForDemos', 'select into/bulkcopy', 'true'
Select * INTO Managers From Employee where Designation='Manager'
EXEC sp_dboption 'ForDemos', 'select into/bulkcopy', 'false'
SET IDENTITY_INSERT ON
Insert into Managers Select * From Employee
--The above statement works only if the Mangers table is already existing.
Correlated Sub Queries
Select * From Employee Where EmpSalary <(Select Max(EmpSalary) from Employee)
Group By
Every Column in the select list must be either in group by or must be an aggregate function.
Select DeptID, Sum(BasicSalary) From Employee Group By Deptid
Select DeptID, Max(BasicSalary) From Employee Group By DeptID
Select DeptID, Max(BasicSalary) From Employee where allowances > 500 Group By ALL DeptID
Note: ALL is meaningful only when the SELECT statement also includes a WHERE clause.
Select DeptID, Count(*) as EmpCount From Employee Group By ALL DeptID Having Count(*) > 2
Note: With HAVING clause condition can have aggregate function
Select SubString(EmpName,1,1) as FirstCharName, Count(*) From Employee Group by SubString(EmpName,1,1)
Select DeptID, AVG(BasicSalary) as AverageSalary, SUM(BasicSalary) as TotalSalary From Employee Where BasicSalary > 10000 Group By DeptID Having AVG(BasicSalary) >= 30000
Note: Having is applied to aggregated value for that group and where is applied to each row .
Select Location, DeptId, SUM(BasicSalary) as TotalDeptSalary From Employee Group By Location, DeptId Compute Count(DeptId)
Select Location, DeptId, SUM(BasicSalary) as TotalDeptSalary From Employee Group By Location, DeptId order by Location Compute Count(DeptId) By Location
CUBE
-
Select Location, DeptId, Sum(BasicSalary) From Employee Group by Location, DeptId with CUBE
Select DeptId, Location, Sum(BasicSalary) From Employee Group by DeptId, Location with CUBE
Select CASE WHEN (GROUPING(Location) = 1) THEN 'ALL'
ELSE ISNULL(Location, 'UNKNOWN')END AS Location,
CASE WHEN (GROUPING(DeptId) = 1) THEN 0
ELSE ISNULL(DeptId, -1)END AS DeptId, Sum(BasicSalary) From Employee Group by Location,DeptId with
CUBE
Note: If the row is added because of CUBE then Grouping(<ColName>) returns 1 else return 0
ROLLUP
Try the same examples as above and replace CUBE with ROLLUP and observe the difference
UNION / INTERSECT / EXCEPT
- Select EmpName,BasicSalary from Employee where BasicSalary > 20000
UNION ALL
Select EmpName,BasicSalary from Employee where BasicSalary between 5000 and 42000
- Select EmpName,BasicSalary from Employee where BasicSalary > 20000
INTERSECT
Select EmpName,BasicSalary from Employee where BasicSalary between 5000 and 42000
- Select EmpName,BasicSalary from Employee where BasicSalary between 5000 and 42000
EXCEPT
Select EmpName,BasicSalary from Employee where BasicSalary > 20000
Note: All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
Working with CONSTRAINTS
A Constraint is a check or a rule that is applied on the data in the table.
Types of Constraint
- Not Null
- Unique
- Primary Key
- Default
- Check
- Foreign key
1. NOT NULL CONSTRAINT
When a table's column is applied with the Not Null constraint then that column will not accept any null value.
Syntax: Create table <table name>(column1 datatype not null,column2 datatype not null)
2. UNIQUE CONSTRAINT
A unique key ensures that no two rows have the same value in a column or set of columns.
Note: It allows one row in the specified column to contain a Null.
Column level:
Syntax
- Create table <table name> (column1 datatype1 Unique, column2 datatype2 Unique)
- Create table <table name> (column1 datatype1 Constraint <constraint name> Unique)
Ex:
- Create table Department (DeptId int UNIQUE, DeptName varchar(20))
- Create table Department (DeptId int constraint UQ_DeptId UNIQUE, DeptName varchar(20))
Table level:
- Create table <table name> (column1 datatype1, column2 datatype2, UNIQUE(colname))
- Create table <table name> (column1 datatype1, Constraint <constraint name> UNIQUE (colname))
Ex:
- Create table Department (DeptId int, DeptName varchar (20), UNIQUE (DeptId))
- Create table Department (DeptId int, DeptName varchar (20), constraint UQ_DeptId UNIQUE(DeptId))
Composite Unique Key
Syntax:
- Create table <table name> (column1 datatype1, column2 datatype2, Unique (column1, column2))
- Create table <table name> (column1 datatype1, column2 datatype2, Constraint <constraint name> Unique (column1, column2))
Ex:
- Create table Department (DeptId int, DeptName varchar (20), unique (DeptId, DeptName))
- Create table Department (DeptId int, DeptName varchar (20), constraint UQ_DeptId_DeptName unique (DeptId, DeptName))
3. PRIMARY KEY CONSTRAINT
Primary key constraints are similar to unique constraints except that they do not permit the associated column to contain a null.
Column level:
- Create table <table name> (column1 datatype1 Primary key, column2 datatype2)
- Create table <table name> (column1 datatype1 Constraint <constraint name> Primary key, column2 datatype2)
Ex:
- Create table Department (DeptId int primary key, DeptName varchar (20))
- Create table Department (DeptId int constraint PK_DeptId primary key, DeptName varchar (20))
Table level:
- Create table <table name> (column1 datatype1, column2 datatype2, Primary key (column))
- Create table <table name> (column1 datatype1, column2 datatype2, Constraint <constraint name> Primary key (column name))
Ex:
- Create table Department (DeptId int, DeptName varchar (20), Primary key (DeptId))
- Create table Department (DeptId int, DeptName varchar (20), constraint PK_DeptId primary key (DeptId))
Composite Primary Key
Syntax:
- Create table <table name> (column1 datatype1, column2 datatype2, Primary key (column1, column2))
- Create table <table name> (column1 datatype1, column2 datatype2, Constraint <constraint name> Primary key (column1, column2))
Ex:
- Create table Department (DeptId int, DeptName varchar (20), primary key (DeptId, DeptName))
- Create table Department (DeptId int, DeptName varchar (20), constraint PK_DeptId_DeptName primary key (DeptId, DeptName))
4. FOREIGN KEY CONSTRAINT
It is used to establish a parent / child or master / dependent relationship between the tables. Foreign key columns of the child table is always linked to either primary key or unique column of the parent table. It can be used only when:
- The referenced table has a unique or primary key constraint defined on the appropriate column
- Data types of the referencing table columns exactly match the data types of the referenced table columns.
Purpose of Creating ForeignKeyConstraint
- To make the column of the child table dependent upon a column of the parent table. Ex: The DeptId of Employee table cannot have a value which is not present in DeptId of Department table.
- If the row in the parent table is deleted, it should either delete all the dependent rows of the child table or set the foreignkey field of the child rows to NULL. By default the row in the parent table cannot be deleted if it has dependent rows in the child table.
To Add Foreign Key
Step 1: Create tables
Department(DeptId,DeptName) - DeptId is Primary Key / Identity Column
Emp(EmpId,EmpName,EmpSalary,DeptId) - EmpId is Primary Key / Identity Column
Step 2: Table Designer -> RelationShips -> Add -> Expand Tables and Columns Specification -> Click->
Primary Key Table = Department, Foreign Key Table = Employee -> Select "DeptId" under both the tables -> OK
Step 3: Table Designer -> RelationShips -> Add -> Expand Insert and Update Specification -> Set Delete Rule / Update Rule
Syntax:
Create table <table name> (column1 data type, column2 data type, constraint <constraint name> references <table name> (column name) on delete [no action | cascade | set null] on update [no action | cascade | set null)
Ex:
CREATE TABLE Employee (EmpId int primary key, EmpName varchar (20),
DeptId int constraint FK_DeptId references Department (DeptId) on delete no action on update cascade)
ALTER TABLE Employee ADD CONSTRAINT FK_Department_Employee FOREIGN KEY(DeptId) REFERENCES Department(DeptId) ON UPDATE NO ACTION ON DELETE SET NULL
5. DEFAULT CONSTRAINT
A default value can be specified for a column using the default constraint. When a user does not enter a value for the column SQL Server inserts the default value automatically.
Syntax: Create table <table name> (column data type default ['value' | null])
6. CHECK CONSTRAINT
The check constraint is used to validate simple conditions on columns while data is being updated or inserted into the table.
Syntax: Create table <table name> (column data type Check (condition))
- ALTER TABLE Employee ADD CONSTRAINT CK_Employee CHECK (([BasicSalary]>(1000)))
- ALTER TABLE Employee ADD CONSTRAINT CK_Employee_1 CHECK (BasicSalary > Allowances)
Assignment:
Category(PKCategoryID, CategoryName, Description, IsActive, FKCategoryID)
Product(PKProductID, ProductName,QuantityInStock,Price)
MMCategoryProduct(FKCategoryID,FKProductID)
Customer(PKCustomerID, CustomerName, Address, OtherInfo)
Order (PKOrderID, FKCustomerID, OrderDate)
OrderDetail(PKOrderDetailsID,FKOrderID,FKProductId,Quantity)
JOINS
Join conditions can be specified in either the FROM or WHERE clauses; specifying them in the FROM clause is recommended. WHERE and HAVING clauses can also contain search conditions to further filter the rows selected by the join conditions.
Joins can be categorized as:
Cross joins
Cross joins return all rows from the left table; each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian Products.
This is generally useful when the tables joining don't have any relationship between them (no common column).
Example: Assuming that we have two independent tables: Student and Subject, we can use cross join to get all subjects for every student - Select * From Student, Subject
Inner joins
Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.
Outer joins
Outer joins can be a left, a right, or full outer join.
- LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. - RIGHT JOIN or RIGHT OUTER JOIN.
A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. - FULL JOIN or FULL OUTER JOIN.
A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
Examples:
- To retrieve only the information about those employees who are assigned to a department.
Select EmpID,EmpName,DeptName From Employee e INNER JOIN Department d on e.DeptID = d.DeptID
- Retrieve only the information about departments to which atleast one employee is assigned
Select distinct d.DeptId, DeptName from Department d INNER JOIN Employee e on e.DeptID = d.DeptID
- Retrieve information about all Employees irrespective of department assigned to them or not
Select EmpID,EmpName,DeptName From Employee e LEFT OUTER JOIN Department d on e.DeptID = d.DeptID
Select EmpID,EmpName,DeptName From Department d RIGHT OUTER JOIN Employee e on e.DeptID = d.DeptID
- Retrieve information about all Department irrespective of employees assigned to them or not
Select EmpID,EmpName,DeptName From Employee e RIGHT OUTER JOIN Department d on e.DeptID = d.DeptID
- Get the DeptName and Number of Employees in that department
Select Count(EmpName) as EmpCount, DeptName From Employee e RIGHT OUTER JOIN Department d on e.DeptID = d.DeptID GROUP BY d.DeptName
- Retrive all employees and all departments
Select * From Employee e FULL OUTER JOIN Department d on e.DeptID = d.DeptID
VIEWS
A SQL View is a virtual table, which is based on a SQL SELECT query. Essentially a view is very close to a real database table (it has columns and rows just like a regular table), except for the fact that the real tables store data, while the views don't. The view's data is generated dynamically when the view is referenced. A view references one or more existing database tables or other views.
Advantages of Views
- Views provide a security mechanism by subsetting the data by rows (All Active Customers, all customers in a certain state) and by columns (Payroll fields not shown in the Employee Phone List View).
- Views can simplify complex queries into a single reference. Complex Join operations that can make a normalized database design of several tables into a single row in the result set of the view. This is great for reporting tools like Crystal and Cognos.
- Views give us aggregation capabilities (Min, Max, Count, Sum) where the data is not stored but calculated.
- Views can create other calculated fields based on values in the real underlying tables.
- Views can hide the complexity of partitioned data (Sales from 1998 are in the 1998 table, Sales from 1999 are in the 1999 table, Sales from 2000 are in the Current Table) .
- Views can be updateable in certain situations
- Views do not incur overhead of additional permanent storage.
Creating a View
Create View EmpView
WITH ENCRYPTION | SCHEMABINDING
SELECT EmpName, Salary = BasicSalary+Allowances-Deductions FROM Employee
WITH CHECK OPTION
Note: Views cannot include ORDER BY clause and Cannot include the INTO keyword
If "with Encryption" is used - View cannot be modified or viewed only result can be seen
If WITH SCHEMABINDING clause is used then the base table cannot be dropped or modified in a way that would affect the view
If WITH CHECK OPTION clause is then row cannot be updated through a view if it would no longer be included in the view.
Modifying Data Through Views (Updatable Views)
- Cannot modify views with more than one base tables.
- The select list cant include a DISTINCT or TOP clause or an aggregate function or a calculated value.
- The select statement cant include a GROUP BY or HAVING clause or UNION operator.
- Can cause errors if they affect columns that are not referenced in the View
- If the WITH CHECK OPTION has been specified, makes sure that inserted or updated row meets the select condition.


sridhar thotaPosted May 23, 2013, 7:28 AM
great work.