2. Index No Index No
Database 01 SQL - Data types 15
Database Management System (DBMS) 02 DDL – Create 16-18
Types of DBMS 03 DDL – Alter 19-22
RDBMS 03 DDL – Rename 23-24
Features of RDBMS 04 DDL – Truncate & Drop 25-26
Database Tables 05 CRUD Operations 27
Primary Key 06 Data Manipulation Language (DML) 27
Table Relationship 07-09 SQL 28
Transaction 10 DML - Insert 29
ACID test 10 DML – Update & Delete 30
Introduction to SQL 11 DRL- SELECT 31-41
Database Model & Install SQL Server 12 DRL - JOINS 42-55
Using SQL Server Management Studio 13 SQL - FUNCTION 56-69
SQL Query - Types 13 DRL - SUBQUERY 70-76
Query - Quick Start 14 SQL - VIEW 77-82
3. Index No Index No
SQL Constraints 83-90 Data Control Language (DCL) 101-105
SQL - Procedure 91-95 Index 106-109
Transactional Control Language (TCL) 96-98 Trigger 110-113
Cursor 99-100 Normalization 114-116
4. Database
01
Database is an organized collection of data
It is not always necessary to store data in a database
Data can always be stored in files which are organized within folders
Spreadsheets can also be used to store and organize certain type of data
However these methods have certain drawbacks
When to use a Database?
Use a database under the following cases:
Size of data is huge
When you need multiple users to have access to data simultaneously
Accuracy
Security to ensure data is safe from unauthorized users
To avoid redundancy
Risk of losing important data
5. Database Management System (DBMS)
02
DBMS is a set of computer software providing the interface between users and a database or databases
Database management systems are designed to handle certain
operations such as :
Creation
Querying
Update
Administration
Well-known DBMSs include:
MySQL
PostgreSQL
SQLite
Microsoft SQL Server
Oracle
IBM DB2
FileMaker Pro
Microsoft Access
There could be scenarios where multiple DBMS may be used
6. Types of DBMS
03
There are different types of DBMS such as:
Hierarchical DBMS
Relational DBMS (RDBMS) – currently the most widely used
Network DBMS
Object-Oriented DBMS
NoSQL DBMS
RDBMS
RDBMS is based on the relational model
Developed by E. F. Codd in the late 1980s
RDBMS presents data in tabular form
RDBMS defines relations between tables
Most widely used RDBMS products are:
DB2
Oracle
SQL Server
7. Features of RDBMS
04
Uses one or more tables to store data
Tables are the most fundamental unit in a RDBMS
Tables consist of rows and columns
A table within a database can be related to other table(s)
8. Database Tables
05
Table contains multiple columns and each column holds a certain type of data
Columns can be defined to store unique values
Columns can also be defined to be optional
9. Primary Key
06
Primary key is used to uniquely identify a row in a table
It is common practice to define primary key columns of integer type
Primary keys are default set to unique
10. Table Relationship
07
It is possible that the data in different tables are related
In the example, student table is related to courses table.
In this case students can enroll for courses
13. Transaction
10
Transaction define a combined unit of work
Transaction is used to ensure “All or None”
It ensures that the series of actions are all done successfully
In case any of the action fails for some reason then reset to the start of the transaction
ACID rule defines a transaction
ACID test
Atomicity - Transaction should consist of indivisible units that are all performed or none are
performed
Consistency – Transaction should always leave the a database in a balanced state
Isolated – Database should be locked during a transaction Durable – Database should be robust
and data should be retained no matter what
14. Introduction to SQL
11
Structured Query Language (SQL) is a declarative query language
SQL can be used to
Create – CREATE TABLE Student
Read – SELECT * FROM Student
Update – UPDATE STUDENT SET Name=‘sunil’ WHERE StudentId=1
Delete – DELETE FROM STUDENT WHERE StudentId=1
Different DBMS use slightly different variations of SQL
Oracle – PL-SQL
SQL Server – Transact-SQL (T-SQL)
However, the basic knowledge of SQL works with all DBMS
15. Database Model
12
Follow these steps to define the database model or schema:
Define tables
Define columns
Define column data types
Define primary key
Create relationships
Check for referential integrity
Install SQL Server
The latest of SQL Server is 2014 while the earlier versions were SQL Server 2012, SQL Server 2008,
SQL Server 2005..
You can down the software directly from the Microsoft website
Microsoft provides Express edition which is free to download and to use for non commercial
purposes
Ensure to download the right package that supports both database engine and DBMS software
To install SQL server follow the steps provided in the training material
16. Using SQL Server Management Studio
13
Connecting to database
Creating database
Creating table
Defining column data types
Defining primary keys, unique values and optional fields
Inserting data to tables
View data
Edit data
SQL Query - Types
DDL – Data Definition Language
DML – Data Manipulation Language
DRL – Data Retrieval Language
DCL – Data Control Language
TCL – Transaction Control Language
17. Query - Quick Start
14
Create a database
CREATE DATABASE StudentDB
Create a table
CREATE TABLE Student
(
Name varchar(50),
ContactNo varchar(10),
Address varchar(100)
)
Quick Start
Insert values
INSERT INTO Student (Name, ContactNo, Address) VALUES
(‘Aamir’, ‘9886098860’, ‘Bangalore, India’)
Retrieve data
SELECT * FROM Student
19. DDL – Create
16
Create query is used to create a table
CREATE TABLE Student
(
Name varchar(50),
ContactNo varchar(10),
Address varchar(100)
)
DEFAULT constraint
Default constraint is used to specify a default value to a column if a value is not provided
CREATE TABLE Student
(
StudentID int,
Name varchar(50),
ContactNo varchar(10),
Address varchar(100) DEFAULT ‘Bangalore’
)
20. DDL – Create
17
NOT NULL constraint
Not null constraint is used to specify that a column value can’t be empty
CREATE TABLE Student
(
Name varchar(50) NOT NULL,
ContactNo varchar(10),
Address varchar(100)
)
CHECK constraint
CREATE TABLE Student
(
Name varchar(50) NOT NULL,
ContactNo varchar(10),
Address varchar(100)
CHECK (ContactNo > 0)
)
21. DDL – Create
18
PRIMARY KEY constraint
Primary key is used to uniquely identify rows in a table
CREATE TABLE Student
(
StudentId int PRIMARY KEY,
Name varchar(50),
ContactNo varchar(10)
)
FOREIGN KEY constraint
Is used to add reference to an other table
CREATE TABLE Student
(
StudentId int PRIMARY KEY,
Name varchar(50),
ContactNo varchar(10),
CourseId int FOREIGN KEY REFERENCES Course(CourseId)
)
22. DDL – Alter
19
Is used to modify the table definition by adding, deleting and altering columns and constraints
Syntax ( Add a new column ) :
ALTER TABLE <table name> ADD <column name> <data type>
Example
ALTER TABLE Student ADD Email VARCHAR(50);
Syntax ( Delete an existing column ) :
ALTER TABLE <table name> DROP COLUMN <column name> ;
Example
ALTER TABLE Student DROP COLUMN Email;
23. DDL – Alter
20
Syntax ( Modify an existing column ) :
ALTER TABLE <table name> ALTER COLUMN <column name> <data type>;
Example
ALTER TABLE Student ALTER COLUMN Email VARCHAR(25);
Syntax ( Add a new column with constraint )
ALTER TABLE <table name> ADD <column name> <data type> <constraint type>;
Example
ALTER TABLE Student ADD Address VARCHAR(50) NOT NULL;
24. DDL – Alter
21
Syntax ( Add a new constraint )
ALTER TABLE <table name> ADD CONSTRAINT <constraint name> <constraint type> (<column name>);
Example
ALTER TABLE Student ADD CONSTRAINT Unq_StudEmail UNIQUE (Email );
Syntax ( Add a NOT NULL constraint to an existing table )
ALTER TABLE <table name>
ALTER COLUMN <column name> <data type> NOT NULL
Example
ALTER TABLE EMPLOYEE
ALTER COLUMN salary INT NOT NULL
25. DDL – Alter
22
Syntax (Delete an existing constraint)
ALTER TABLE <table name> DROP CONSTRAINT <constraint name>;
Example
ALTER TABLE Student DROP CONSTRAINT Unq_StudEmail;
Syntax (Adding foreign Key to a column)
AlTER TABLE <table name> ADD CONSTRAINT <constraint name> FOREIGN KEY (<column name>)
REFERENCES < parent table name> (<column name>)
Example
ALTER TABLE Student
ADD CONSTRAINT fk_ CourseId
FOREIGN KEY (CourseId)
REFERENCES Course(CourseId);
26. DDL – Rename
23
Syntax ( To Rename a Column )
SP_RENAME ‘<table name>.<old column name>', <new column name>' , 'COLUMN'
Example
SP_RENAME 'Student.contact', 'PhNo' , 'COLUMN'
Syntax ( To Rename a Table )
SP_RENAME ‘<old table name>', ‘<new table name>'
Example
SP_RENAME 'Student', 'NewStudent'
27. DDL – Rename
24
Syntax ( To Rename a Column )
SP_RENAME ‘<old constraint name>', ‘<new constraint name>'
Example
sp_rename '[CK__EMPLOYEE__1367E606]', 'Check_SAL'
Syntax ( To Rename a Database )
ALTER DATABASE <Old_DatabaseName> MODIFY NAME = <New_DatabaseName>
Example
ALTER DATABASE <StudentDB> MODIFY NAME = <NewStudentDB>
28. DDL – Truncate
25
Syntax ( Truncate a Table )
TRUNCATE TABLE <table name> ;
Example :-
TRUNCATE TABLE Student ;
DDL – Drop
Syntax ( To Drop/Delete a Table )
DROP TABLE <table name> ;
Example
DROP TABLE Student ;
29. DDL – Drop
26
CASE Expression:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
SELECT name,sal, CASE
WHEN Sal <=2000 THEN 'C'
WHEN Sal Between 2000 And 5000 THEN 'B'
ELSE 'A'
END FROM emp;
30. CRUD Operations
27
CRUD – Create Read Update Delete
After creating a database you can perform CRUD operations on the database.
The four basic CRUD operations of persistent databases are:
Create : uses create command
Read : uses SELECT command
Update : uses UPDATE command
Delete : uses DELETE command
Data Manipulation Language (DML)
DML Includes:
INSERT
UPDATE
DELETE
31. SQL
28
Data Manipulation Language (DML)
DML statements are used to work with the data in tables. It is used to retrieve, store, modify, delete, insert
and update data in database. Below are the syntax for common DML statements:
1. INSERT INTO <table name>
VALUES (<value 1>, ...<value n>);
2. UPDATE <table name>
SET <attribute> = <expression>
WHERE <condition>;
3. DELETE FROM <table name>
WHERE <condition>;
32. DML - Insert
29
Used to insert data into tables
It enables you to add one or more rows of data into the table or view
Syntax
INSERT INTO <table name> (<column name1>, <column name2>, <column name3>…….)
VALUES (<value1>, <value2, <value3>……);
Example
INSERT INTO Employee (Name, Age, Dept_Id, Salary)
VALUES ('John', 25, 1, 120000);
Inserting multiple rows
INSERT INTO Department (Dept_name)
VALUES ('Human Resources'), (‘Finance’);
33. DML - Update
30
Used to modify existing data in a table
Syntax
UPDATE <table name> SET <column1>=<value1>, <column2>=<value2>,...
WHERE <some column>=<some_value>;
Example
UPDATE Employee
SET Name=‘Johny’,Age=22,...
WHERE Name=‘John’;
DML - Delete
Used to delete rows in a table
Syntax
DELETE FROM <table name> [WHERE condition]
Example
DELETE FROM Employee WHERE name =‘Johny’;
34. DRL- SELECT
31
To select all the columns:
Syntax
SELECT * FROM <table name>
Example
SELECT * FROM Student
To select specific columns
Syntax
SELECT <column1>,<column2>… FROM <table name>
Example
SELECT Name, Address FROM Student ;
35. DRL- SELECT
32
Select Using where clause:
Syntax
SELECT * FROM <table name> WHERE <column name>= <value>
Example
SELECT * FROM Employee WHERE Name=‘Johny’
Select Distinct row(s)
Syntax
SELECT DISTINCT <column1>,<column2>.. FROM <table name>
Example
SELECT DISTINCT Name, Address FROM Student.
36. DRL- SELECT
33
The SQL AND & OR Operators
The AND operator displays a record if both the first condition AND the second condition are true.
The OR operator displays a record if either the first condition OR the second condition is true
Syntax (AND):
SELECT * FROM <table name>
WHERE <column1>=<value1>
AND <column2>=<value2>;
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
37. DRL- SELECT
34
Syntax (OR):
SELECT * FROM <table name>
WHERE <column1>=<value1>
OR <column2>=<value2>;
Example
SELECT * FROM Customers
WHERE Country='Germany'
OR City='Berlin';
38. DRL- SELECT
35
Syntax (OR):
SELECT <column name>(s)
FROM <table name>
WHERE <column name> IN (value1,value2,...)
Example
SELECT * FROM Customers
WHERE City IN ('Paris', 'London');
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
39. DRL- SELECT
36
Syntax (OR):
SELECT <column name>(s)
FROM <table name>
WHERE <column name> NOT IN (value1,value2,...)
Example
SELECT * FROM Customers
WHERE City NOT IN ('Paris', 'London');
The NOT IN Operator
The NOT IN operator allows you to specify multiple values Except in a WHERE clause.
41. DRL - SELECT
38
In the below example, the wildcard _ is used to select records of employees whose age ends with 5.
SELECT ID as 'Employee#', NAME as 'Employee Name', AGE as 'Age', DEPT_ID as 'Department
Number' FROM EMPLOYEE
WHERE AGE LIKE '_5';
In the below example, the wildcard range is used to select records of employees whose names does not
contain the letter 'a'.
SELECT ID as 'Employee#', NAME as 'Employee Name', AGE as 'Age', DEPT_ID as 'Department
Number' FROM EMPLOYEE
WHERE NAME NOT LIKE '%a%';
42. DRL - SELECT
39
HAVING
HAVING keyword can only be used in a SELECT statement. It defines the search condition for a group.
HAVING clause is usually used with the GROUP BY clause, however, it can be used without GROUP BY
clause, during which it yields the result similar to WHERE clause.
The below example illustrates the HAVING clause in the SELECT query.
Syntax
SELECT <column name (s)> FROM <table name> HAVING <= <aggregate_function(column_name)>
Example
SELECT * FROM Employee HAVING AVG(Salary) <= 5000;
43. DRL - SELECT
40
UNION
The UNION clause combines results of two or more queries into a single result which contains all
the rows that belong to all the queries in the UNION.
Rules for combining the result sets using UNION are:
The data types of the result sets should be compatible
The order and number of columns in each of the queries must be the same
SELECT e.Id as 'Id', e.Name as 'Employee Name' , e.Salary as 'Salary' FROM Employee e
WHERE Salary < 100000
UNION ALL
SELECT m.Id as 'Id', m.Name as 'Employee Name', m.Salary as 'Salary' FROM Employee m WHERE
Salary > 250000
44. DRL - SELECT
41
EXCEPT and INTERSECT
Returns distinct values by comparing the results of two queries. EXCEPT returns any distinct values
from the left query that are not also found on the right query. INTERSECT returns any distinct
values that are returned by both the query on the left and right sides of the INTERSECT operand.
The basic rules for combining the result sets of two queries that use EXCEPT or INTERSECT are the
following:
The number and the order of the columns must be the same in all queries.
The data types must be compatible.
SELECT e.Name, e.Dept_Id FROM Employee e EXCEPT (SELECT Name, Dept_Id FROM Employee s
WHERE s.Dept_Id <> 3)
SELECT e.Name, e.Dept_Id FROM Employee e INTERSECT (SELECT Name, Dept_Id FROM Employee
s WHERE s.Dept_Id <> 3)
45. DRL - JOINS
42
JOINS
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each.
JOINs in SQL Server can be classified as follows:
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
CROSS JOIN
INNER JOIN
The INNER JOIN returns all the matching rows from multiple tables where the join condition is
met.
46. DRL - JOINS
43
Syntax (INNER JOIN)
SELECT <column name(s)>
FROM <table1>
INNER JOIN <table2>
ON <table1.column name> = <table2.column name>;
Example
SELECT e.Name, d.Dept_Name as 'Department Name', e.Salary as 'Salary'
FROM EMPLOYEE e
INNER JOIN Department d
ON e.Dept_Id = d.Dept_Id ;
48. DRL - JOINS
45
LEFT OUTER JOIN
The LEFT JOIN returns all rows from table on the left with the matching rows in the table on the right.
The result is returned as NULL in the right side when there is no match.
49. DRL - JOINS
46
Syntax (LEFT OUTER JOIN)
SELECT <column name(s)>
FROM table1
LEFT OUTER JOIN <table2>
ON <table1.column_name> = <table2.column_name>;
Example
SELECT e.Name, d.Dept_Name as 'Department Name', e.Salary as 'Salary'
FROM EMPLOYEE e
LEFT OUTER JOIN Department d
ON e.Dept_Id = d.Dept_Id ;
50. DRL - JOINS
47
RIGHT JOIN
The RIGHT JOIN returns all rows from table on the right with the matching rows in the table on the
left. The result is returned as NULL in the left side when there is no match.
51. DRL - JOINS
48
SYNTAX (RIGHT OUTER JOIN):
SELECT <column name(s)>
FROM table1
RIGHT OUTER JOIN <table2>
ON <table1.column_name> = <table2.column_name>;
Example
SELECT e.Name, d.Dept_Name as 'Department Name', e.Salary as 'Salary'
FROM EMPLOYEE e
RIGHT JOIN Department d
ON e.Dept_Id = d.Dept_Id
52. DRL - JOINS
49
FULL OUTER JOIN
The FULL OUTER JOIN returns the combined result of the LEFT and RIGHT joins. It will return all the rows
of the tables on the left and the right side.
The highlighted area in the below Venn diagram shows the result of an FULL OUTER JOIN clause.
53. DRL - JOINS
50
SYNTAX (FULL OUTER JOIN):
SELECT <column name(s)>
FROM <table1>
FULL OUTER JOIN table2
ON <table1.column_name> = <table2.column_name>;
Example
SELECT e.Name, d.Dept_Name as 'Department Name', e.Salary as 'Salary'
FROM EMPLOYEE e
FULL OUTER JOIN Department d
ON e.Dept_Id = d.Dept_Id
54. DRL - JOINS
51
CROSS JOIN
In CROSS JOIN, each row from first table joins with all the rows of another table. If there are m rows from
Table1 and n rows from Table2, then result set of these tables will have m*n rows.
56. DRL - JOINS
53
SYNTAX (CROSS OUTER JOIN):
SELECT * FROM <table1>
CROSS JOIN <table2> ;
Example
SELECT * FROM Employee
CROSS JOIN Dept ;
57. DRL - JOINS
54
Self Join
A self-join is a query in which a table is joined (compared) to itself.
Self-joins are used to compare values in a column with other values in the same column in the same
table.
58. DRL - JOINS
55
SYNTAX (SELF JOIN):
SELECT a.<column name>, b.<column name>...
FROM <table1> a,< table1> b
WHERE a.<common field> = b.<common field>;
Example
SELECT a.EmpNo,a.Name,b.Name AS ManagerName from Employee a, Employee b
WHERE a.MgrId=b.EmpNo;
59. SQL - FUNCTION
56
Functions in SQL Server can be categorized into
Built-in functions
Rowset functions
Aggregate functions
Ranking functions
Scalar functions
User-defined functions
Ranking Function
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first
row in each partition.
Following ranking functions are supported:
RANK
ROW_NUMBER
DENSE_RANK
NTITLE
60. SQL - FUNCTION
57
SYNTAX
ROW_NUMBER ( )
OVER ( [ PARTITION BY value expression , ... [ n ] ] order_by_clause )
Example
SELECT EmployeeId,Name,Salary, ROW_NUMBER ( ) OVER (ORDER BY Salary)
AS SalRank FROM Employee
Scalar Functions: Operate on a single
value and then return a single value.
Scalar functions are categorized into
sub sections such as Date and Time,
String, Logical, Security, etc.
List of scalar functions that operate on strings
61. SQL - FUNCTION
58
Syntax
SELECT CONCAT (<column name1>,<column name2>)
FROM <table name>;
Example
SELECT CONCAT (Empno, Salary) FROM Employee;
CONCAT () : Returns a string that is the result of concatenating two or more string values.
Syntax
SELECT LEN (<column name1>,<column name2>)
FROM <table name>;
Example
SELECT LEN (Empno, Salary) FROM Employee;
LEN () : The LEN() function returns the length of the value in a text field.
62. SQL - FUNCTION
59
LTRIM () : Returns a character expression after it removes leading blanks.
RTRIM () : Returns a character string after truncating all trailing blanks.
SYNTAX
SELECT Ltrim(column name) FROM <table name>;
SELECT Rtrim(column name) FROM <table name>;
Example
SELECT Ltrim(Name) FROM Employee ;
Syntax
SELECT ROUND(<column name>,decimals)
FROM table_name;
Example
SELECT Id, ROUND(((Salary/100)*15), 0) AS "15% of Salary" FROM Employee ;
ROUND() : The ROUND() function is used to round a numeric field to the number of decimals specified.
63. SQL - FUNCTION
60
Syntax
SELECT SUBSTRING(<column name>,start, length) AS Alias FROM <table name>;
Example
SELECT Name, SUBSTRING(Name, 1, 5) AS Initial FROM Employee
SUBSTRING(): The SUBSTRING() returns a substring of a string
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Types of aggregate functions are:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
64. SQL - FUNCTION
61
User Defined Function (UDF)
SQL Server user-defined functions are routines that accept parameters, perform an action, such as a
complex calculation, and return the result of that action as a value.
The return value can either be a single scalar value or a result set.
The benefits of using user-defined functions in SQL Server are:
They allow modular programming.
They allow faster execution.
They can reduce network traffic.
66. SQL - FUNCTION
63
Example (To add two numbers):
CREATE FUNCTION AddTwoNumbers
(
@a int,
@b int
) RETURNS int
AS
BEGIN
RETURN @a + @b
END ;
67. SQL - FUNCTION
64
Example (To find name of a employee):
Create Function [dbo].[GetName]
(
@empId Int
)
Returns Varchar(50)
Begin
Return (Select Name from Employee
where Empno=@empId)
END
68. SQL - FUNCTION
65
Executing a UDF
PRINT <function name >(@input parameter(s))
OR
SELECT dbo.AddTwoNumbers(30,20)
PRINT <function name >(@input parameter(s))
OR
SELECT dbo.AddTwoNumbers(30,20)
69. SQL - FUNCTION
66
Deterministic functions
Deterministic functions always returns the same output result all the time it is executed for same
input values.
Examples: ROUND, ISNULL, COALESCE etc.
Nondeterministic functions
Nondeterministic functions may return different results each time they are executed.
Functions that call extended stored procedures are nondeterministic.
User-defined functions that create side effects on the database are not recommended.
Examples: GETDATE, RAND, GETUTCDATE etc.
70. SQL - FUNCTION
67
Deterministic functions Example :
ISNULL : Replaces NULL with the specified replacement value
Syntax
ISNULL ( check_expression , replacement_value );
Example
SELECT ISNULL(salary,0) from Employee ;
COALESCE : Evaluates the arguments in order and returns the current value of the first expression that
initially does not evaluate to NULL
Syntax
COALESCE ( expression [ ,...n ] ) ;
Example
Select COALESCE(commission,salary,0) from Employee ;
71. SQL - FUNCTION
68
Nondeterministic functions Example :
To get random number
SELECT RAND() AS RandomNo
To get the current date
SELECT GETDATE() AS CurrentDate
GROUP BY
Groups are defined as set of rows grouped into a set of summary rows based on the values of column
expression. Only one resultant row is retrieved per group.
A simple GROUP BY clause does not include GROUPING SETS, CUBE, ROLLUP, WITH CUBE, or WITH
ROLLUP. GROUP BY (), grand total, is considered a simple GROUP BY.
Syntax
SELECT <column name>, aggregate_function(column_name)
FROM <table name>
WHERE <condition>
GROUP BY <column name>;,
72. SQL - FUNCTION
69
Example1:
SELECT Name, MAX(Salary)
FROM Employee GROUP BY Name;,
Example2(Group By with Join):
SELECT d.Dept_Name as 'Department Name',e.Salary
FROM EMPLOYEE e
JOIN Department d
ON e.Dept_Id = d.Dept_Id
GROUP BY e.Salary,d.Dept_Name;
73. DRL - SUBQUERY
70
The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another
subquery.
A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can also be a
multiplerow operator, such as IN, ANY, or ALL.
A subquery can be treated as an inner query, which is a SQL query placed as a part of another query
called as outer query.
The inner query executes first before its parent query so that the results of inner query can be passed to
the outer query.
74. DRL - SUBQUERY
71
Guidelines
A subquery must be enclosed in parentheses.
A subquery must be placed on the right side of the comparison operator.
Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be added
in to a subquery. You can use a ORDER BY clause in the main SELECT statement (outer query) which
will be last clause.
Use single-row operators with single-row subqueries.
If a subquery (inner query) returns a null value to the outer query, the outer query will not return
any rows when using certain comparison operators in a WHERE clause
75. DRL - SUBQUERY
72
Type of Subqueries
Single row subquery : Returns zero or one row.
Multiple row subquery : Returns one or more rows.
Correlated subqueries : Reference one or more columns in the outer SQL statement. The subquery is
known as a correlated subquery because the subquery is related to the outer SQL statement.
76. DRL - SUBQUERY
73
Single row subquery
You can place a subquery in the WHERE clause of another query.
SYNTAX
SELECT <select_list> FROM <table name> WHERE expr operator
(SELECT <select_list> FROM <table name> ) ;
Example
SELECT Name FROM Employee WHERE salary =
(SELECT Salary FROM Employee WHERE EmpId=101 ) ;
77. DRL - SUBQUERY
74
Multiple Row subquery:
IN/NOT IN operator is used to check a value within a set of values. The list of values may come from
the results returned by a subquery.
SYNTAX
SELECT <select_list> FROM <table name> WHERE operator (IN/>/</<=/>=…) (SELECT <select_list>
FROM <table name> ) ;
Example
SELECT Name, Salary FROM employee WHERE Salary > (SELECT MIN(Salary)
FROM employee GROUP BY deptno)
78. DRL - SUBQUERY
75
Using IN, Any and All
IN :An IN subquery condition is TRUE if the value of the expression matches one or more of the
values from the subquery
Any : The ANY operator compares a value to each value returned by a subquery. <ANY means
less than the maximum. >ANY means more than the minimum. =ANY is equivalent to IN.
All : The ALL operator compares a value to every value returned by a subquery. >ALL means
more than the maximum and <ALL means less than the minimum.
SELECT Name, Salary FROM employee WHERE Salary IN (SELECT MIN(Salary ) FROM employee
GROUP BY deptno);
SELECT name, sal FROM employee WHERE sal > ANY ( SELECT MIN(sal) FROM employee
GROUP BY dept_no)
SELECT name, sal FROM employee WHERE sal > ALL ( SELECT MIN(sal) FROM employee GROUP
BY dept_no)
79. DRL - SUBQUERY
76
Correlated Subquery
SQL Correlated Subqueries are used to select data from a table referenced in the outer query.
In this type of queries, a table alias (also called a correlation name) must be used to specify which
table reference is to be used.
SYNTAX
select Name ,Salary ,Deptno from Employee a where
a.Salary < (select AVG(Salary) from Employee b
where a. Deptno = b. Deptno )
80. SQL - VIEW
77
View is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database
81. SQL - VIEW
78
Advantages of database view
A database view allows you to simplify complex queries.
A database view helps limit data access to specific users.
A database view provides extra security layer.
Disadvantages of database view
Performance: querying data from a database view can be slow especially if the view is created based
on other views.
Tables dependency: you create view based on underlying tables of the a database. Whenever you
change the structure of those tables that view associates with, you have to change the view as well.
82. SQL - VIEW
79
Syntax
CREATE VIEW <view name> AS
SELECT <column name(s)>
FROM <table name>
[WHERE condition]
Example
CREATE VIEW EMPlOYEE_VU AS
SELECT Name, Salary
FROM Employee
WHERE Salary>5000
83. SQL - VIEW
80
Syntax
SELECT * / <column name(s)>
FROM <view name>
Example
SELECT * FROM EMPlOYEE_VU
Retrieving data from a view
Syntax
INSERT INTO EMPlOYEE_VU VALUES (‘John',2000)
Example
INSERT INTO EMPlOYEE_VU VALUES (‘John',2000)
Inserting data by using a view
84. SQL - VIEW
81
Syntax
UPDATE <view name>
SET <column name> = <value>
[WHERE condition(s)]
Example
UPDATE EMPlOYEE_VU SET Salary=5200
WHERE salary=5500
Updating data using a view
85. SQL - VIEW
82
Complex views
Complex views can be constructed on more than one base table. In particular, complex views can
contain:
join conditions
a group by clause
a order by clause
Example
CREATE VIEW complex_view AS
SELECT emp.Empno, emp.name, emp.Deptno, dept. Name
FROM Employee emp INNER JOIN Dept
ON emp.deptno = dept.deptno;
Syntax
DROP VIEW <view name>
Example
DROP VIEW EMPlOYEE_VU
Dropping a View
86. SQL Constraints
83
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by the
constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the
table is created (inside the ALTER TABLE statement).
In SQL, we have the following constraints:
NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row for a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination
of two or more columns) have an unique identity which helps to find a particular record in a table
more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another
table
CHECK - Ensures that the value in a column meets a specific condition
DEFAULT - Specifies a default value when specified none for this column
88. SQL Constraints
85
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you cannot
insert a new record, or update a record without adding a value to this field.
CREATE TABLE Employee
(
Id int NOT NULL ,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
89. SQL Constraints
86
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.
CREATE TABLE Employee (
Id int NOT NULL,
Ph VARCHAR(12) UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
ALTER TABLE Employee ADD CONSTRAINT Emp_const UNIQUE (ph)
90. SQL Constraints
87
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values.
A primary key column cannot contain NULL values.
Most tables should have a primary key, and each table can have only ONE primary key.
CREATE TABLE Employee (
Id int NOT NULL,
Ph VARCHAR(12) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
ALTER TABLE Employee ADD CONSTRAINT emp_cons_pk Primary Key (ph)
91. SQL Constraints
88
SQL Foreign KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
CREATE TABLE Employee
(
Empno int NOT NULL PRIMARY KEY,
Name VARCHAR(20) NOT NULL,
DeptNo int FOREIGN KEY REFERENCES Dept(DeptNo)
)
ALTER TABLE Employee ADD FOREIGN KEY (Deptno) REFERENCES Dept (Deptno)
92. SQL Constraints
89
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
CREATE TABLE Employee
(
Id int NOT NULL CHECK(Id>10),
Ph VARCHAR(12) Primary Key,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
ALTER TABLE Employee ADD CONSTRAINT chk_Person CHECK (Id>0)
93. SQL Constraints
90
SQL 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.
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL, P_Id int,
OrderDate date DEFAULT GETDATE()
)
ALTER TABLE Employee ALTER COLUMN OrderDate SET DEFAULT GETDATE()
To DROP a Constraint
ALTER TABLE <table_Name> DROP CONSTRAINT <Constraint name>
94. SQL - Procedure
91
A stored procedure is a group of sql statements that has been created and stored in the database.
Accept input parameters and return multiple values in the form of output parameters to the calling
procedure or batch.
Contain programming statements that perform operations in the database, including calling other
procedures.
Return a status value to a calling procedure or batch to indicate success or failure (and the reason for
failure)
Stored Procedure Vs Function
Stored Procedures Functions
May or may not return values Return at least one output.
Can be used to solve the business logic. Can be used for calculations.
Functions can be called from Procedure Procedures cannot be called from Function.
Procedures is a Pre-compiled statement Function is not a Pre-compiled statement.
Can affect the state of the database. Can’t affect the state of the database.
Can’t be invoked from a sql statement e.g. SELECT Can be invoked by a SELECT statement.
95. SQL - Procedure
92
Advantages of using stored procedures :
Stored procedure allows modular programming :
You can create the procedure once, store it in the database, and call it any number of times in
your program.
Stored Procedure allows faster execution :
They are parsed and optimized when they are first executed, and a compiled version of the
stored procedure remains in memory cache for later use.
Stored Procedure can reduce network traffic :
An operation requiring hundreds of lines of Transact-SQL code can be performed through a
single statement that executes the code in a procedure, rather than by sending hundreds of
lines of code over the network
Stored procedures provide better security to your data
96. SQL - Procedure
93
Limitations:
Stored procedure languages are quite often vendor-specific. Switching to another vendor's database
most likely requires rewriting any existing stored procedures.
Changes to stored procedures are more difficult to keep track of within a version control system
than other code. Changes must be reproduced as scripts to be stored in the project history to be
included, and differences in procedures can be more difficult to merge and track correctly.
97. SQL - Procedure
94
Syntax
CREATE PROCEDURE <procedure name>
(
[ @parameters(s) <data type> ] -- Optional
) AS
BEGIN
:
END
Example
CREATE PROCEDURE GetEmpdetails
(
@empid Int
) AS BEGIN
SELECT * FROM Employee WHERE empid=@empid
END ;
98. SQL - Procedure
95
While loop
While loop is a control flow statement that allows code to be executed repeatedly based on a given
boolean condition.
The execution of statements in the WHILE loop can be controlled from inside the loop with the
BREAK and CONTINUE keywords.
WHILE Boolean_expression { sql_statement | statement_block | BREAK | CONTINUE }
Syntax
Example (While Loop )
DECLARE @int INT SET @int = 1 WHILE (@int <=5) BEGIN PRINT @int SET @int = @int + 1 END
Example (WHILE Loop with CONTINUE and BREAK keywords )
DECLARE @int INT SET @int = 1 WHILE (@int <=5) BEGIN PRINT @int SET @int = @int + 1 CONTINUE IF
@int>3 BREAK; END
99. Transactional Control Language (TCL)
96
TCL
TCL is abbreviation of Transactional Control Language. It is used to manage different transactions
occurring within a database.
A transaction is a sequence of one or more SQL statements that together form a logical unit of work.
COMMIT – Saves work done in transactions
ROLLBACK – Restores database to original state since the last COMMIT command in transactions
SAVE TRANSACTION – Sets a save point within a transaction
100. Transactional Control Language (TCL)
97
Using a transaction:
Example (Using Rollback):
begin tran t
declare @id int;
set @id=5;
insert into Employee (EmpNo,Name)values(@id,'Suresh')
if(@id<10)
begin
Print 'An id less than 10 is not valid; query is rolled back';
rollback tran t;
end
Else
begin
print 'data is inserted'
end
101. Transactional Control Language (TCL)
98
Using a transaction:
Example (Using Savepoint):
BEGIN TRAN
INSERT INTO Employee (Name) VALUES ('Tomm')
SAVE TRAN Savepoint1
INSERT INTO Employee (Name) VALUES ('John')
ROLLBACK TRAN Savepoint1
COMMIT TRAN
102. CURSOR
99
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis.
Cursor- Life Cycle
A Cursor executes in the following five steps:
Declare
Open
Fetch
Close
Deallocate
Cursor - Life Cycle
Declare Cursor: A cursor is declared by defining the SQL statement that returns a result set.
Open: A Cursor is opened and populated by executing the SQL statement defined by the cursor.
Fetch: When cursor is opened, rows can be fetched from the cursor one by one or in a block to do
data manipulation.
Close: After data manipulation, we should close the cursor explicitly.
Deallocate: Finally, we need to delete the cursor definition and released all the system resources
associated with the cursor.
103. CURSOR
100
Syntax
[DECLARE < @variable(s) > <data type>]-- Optional
DECLARE <cursor name> CURSOR FOR
SELECT Statement OPEN <cursor name>
DECLARE <variable using for select> <datatype>
FETCH NEXT FROM <cursor name> INTO <variable>
WHILE (@@FETCH_STATUS = 0)
BEGIN
:
END
CLOSE <cursor name>
DEALLOCATE <cursor name>
104. CURSOR
100
Example
DECLARE mycursor CURSOR FOR
SELECT id FROM Employee
OPEN mycursor
DECLARE @id INT
FETCH NEXT FROM mycursor INTO @id
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT(@id)
FETCH NEXT FROM mycursor INTO @id
END
CLOSE mycursor
DEALLOCATE mycursor
105. Data Control Language (DCL)
101
DCL (Data Control Language)
GRANT: to allow specified users to perform specified tasks
REVOKE: to cancel previously granted or denied permissions.
106. Data Control Language (DCL)
102
Syntax (GRANT) :
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
Example (GRANT) :
GRANT SELECT ON employee TO user1;
Syntax (Revoke) :
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name} ;
Example (Revoke) :
REVOKE SELECT ON employee FROM user1 ;
107. Data Control Language (DCL)
103
Privileges and Roles:
Privileges: Privileges defines the access rights provided to a user on a database object.
1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or DELETE data
from database objects to which the privileges apply.
Roles: Roles are a collection of privileges or access rights.
Creating Roles:
Syntax :
CREATE ROLE <role name> ;
Example :
CREATE ROLE TestRole ;
108. Data Control Language (DCL)
104
Managing Roles:
Creating a role :
Grant a CREATE TABLE privilege to the ROLE TestRole :
Grant the role to a user :
To revoke a CREATE TABLE privilege from TestRole :
CREATE ROLE TestRole ;
GRANT <CREATE TABLE/Select/insert/update/delete…> TO TestRole ;
GRANT TestRole TO user1 ;
REVOKE CREATE TABLE FROM TestRole ;
109. Data Control Language (DCL)
105
To drop a role from the database
Syntax :
DROP ROLE role_name ;
Example :
DROP ROLE TestRole ;
110. INDEX
106
INDEX:
An Index is a physical structure contains pointers to the data.
Index is used to speed up queries.
Effective indexes are one of the best ways to improve performance in a database application.
The users cannot see the indexes, they are just used to speed up queries.
Types:
Clustered index
Non-clustered index
111. INDEX
107
Advantages :
Their use in queries usually results in much better performance.
They make it possible to quickly retrieve (fetch) data.
They can be used for sorting.
Unique indexes guarantee uniquely identifiable records in the database.
Disadvantages :
They decrease performance on inserts, updates, and deletes.
Indexes are stored on the disk, and the amount of space required will depend on the size of the
table, and the number and types of columns used in the index, hence it consumes diskspace.
112. INDEX
108
Clustered index
A clustered index is something that reorganizes the way records in the table are physically stored.
Each database table may have only one clustered index.
Non-clustered index
It is a special type of index in which the logical order of the index does not match the physical stored
order of the rows on disk.
It is created outside of the database table and contain a sorted list of references to the table itself.
Each database table may have multiple non-clustered index(s).
113. INDEX
109
Syntax (Creating an Index) :
CREATE [Clustered/Nonclustered ] INDEX <index name> ON <table name>(<column name>)
Example :
CREATE Nonclustered INDEX INDX_Empno ON Employee (Name)
Syntax (Dropping an Index) :
DROP INDEX table_name.index_name
Example :
DROP INDEX Employee.INDX_Empno
114. TRIGGER
110
Stored Procedures Trigger
We can execute a stored procedure whenever we
want with the help of the exec command
A trigger can only be executed whenever an event
(insert, delete, and update) is fired on the table on
which the trigger is defined.
We can call a stored procedure from inside
another stored procedure & can be executed from
a TRIGGER.
We can't directly call another trigger within a
trigger. And it can’t be executed from a Stored-
Procedure.
Stored procedures can be scheduled through a job
to execute on a predefined time.
We can't schedule a trigger.
Stored procedure can take input parameters We can't pass parameters as input to a trigger.
We can use transaction statements like begin
transaction, commit transaction, and rollback
inside a procedure.
We can't use transaction statements inside a
trigger.
We can call a stored procedure from the front end
(e. g.:-.asp files, .aspx files, .ascx files, etc.).
We can't call a trigger from front end .
A trigger is a special kind of stored procedure that automatically executes when an event occurs in the
database server.
115. TRIGGER
111
Types:
DML trigger: DML triggers execute when a user tries to modify data through a data manipulation
language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.
DDL trigger: DDL triggers execute in response to a variety of data definition language (DDL) events.
These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements.
LOGON trigger: Logon triggers fire in response to the LOGON event that is raised when a user
sessions is being established.
Microsoft SQL Server supports triggers either “After or Instead of” an insert, update or delete operation
INSTEAD OF triggers can be defined on either tables or views.
116. TRIGGER
112
Advantages of trigger.
By using triggers, business rules and transactions are easy to store in database and can be used
consistently even if there are future updates to the database.
SQL triggers provide an alternative way to check the integrity of data.
SQL triggers are very useful to audit the changes of data in tables.
Disadvantages of trigger
Decrease in performance of the database: By the complex nature of the database programs take
more time to execute and there can be hidden performance downtimes.
Unlike stored procedures and packages, triggers are not held in the database in a compiled form.
Every time a trigger is fired, the code must be recompiled. It makes system run slower.
Triggers execute invisible to client-application application. They are not visible or can be traced in
debugging code.
117. TRIGGER
113
Syntax
CREATE TRIGGER name ON table
[FOR/AFTER/INSTEAD OF]
[INSERT, UPDATE, DELETE]
AS
BEGIN
:
END
Example
CREATE PROCEDURE [dbo].[MyPro]
AS
BEGIN
Update Emp
Set Sal=Sal+100
END; --------------------------------------------------
Procedure Created. Implementation of the created
procedure by a Trigger:CREATE TRIGGER
[dbo].[Mytrigger]
ON Emp
AFTER DELETE
AS
BEGIN
EXEC MyPro ;
END
118. NORMALIZATION
114
Normalization is the process of efficiently organizing data in a database.
Used to eliminate the redundant data and ensuring that data dependencies make sense.
The Normal Forms
Normalization, referred to as 1NF to 5NF.
In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF.
Fifth normal form is very rarely seen and won't be discussed in this article.
120. NORMALIZATION
116
First Normal Form (1NF)
First normal form (1NF) sets the very basic rules for an organized database: Eliminate duplicative
columns from the same table.
Create separate tables for each group of related data and identify each row with a unique column
or set of columns (the primary key).
Second Normal Form (2NF)
Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
Create relationships between these new tables and their predecessors through the use of foreign
keys.
2NF attempts to reduce the amount of redundant data in a table by extracting it, placing it in new
table(s) and creating relationships between those tables.
Third Normal Form (3NF):
A database is in third normal form if it satisfies the following conditions:
It is in second normal form
There is no transitive functional dependency
By transitive functional dependency, we mean we have the following relationships in the table: A
is functionally dependent on B, and B is functionally dependent on C.