The document provides an overview of SQL Server training. It defines data and databases, explaining that a collection of data leads to a database. It also discusses database management systems (DBMS), explaining that a DBMS allows users to create, read, update and delete data in an organized way. The document also covers types of databases like hierarchical, network, relational and object-oriented databases. It focuses on relational database management systems (RDBMS) and discusses advantages like storing data uniquely and performing complex queries. Finally, it discusses Microsoft SQL Server in more detail.
2. WHAT IS DATA AND DATABASE ?
• Data is a collection of facts, such as numbers, words, measurements, observations or
even just descriptions of things.
• Collection of the data leads to Database i.e. for example, the complete data of a company
leads to a database for that company.
• Database should be saved in such a organized format so that the user/computer can
retrieve a piece of information from the database, so to achieve that DBMS come into the
picture.
Data
DataBase
WWW.ENOSISLEARNING.COM
3. DATABASE MANAGEMENT SYSTEM (DBMS)
• A DBMS makes it possible for end users to create, read, update and delete data in a
database. The DBMS essentially serves as an interface between the database and end
users or application programs, ensuring that data is consistently organized and remains
easily accessible.
• DBMS is that it lets end users and application programmers access and use the same
data while managing data integrity. Data is better protected and maintained when it can
be shared using a DBMS instead of creating new iterations of the same data stored in
new files for every new application. The DBMS provides a central store of data that can
be accessed by multiple users in a controlled manner.
Data
DatabaseDBMS
USER
APP
WWW.ENOSISLEARNING.COM
4. TYPES OF DBMS:
• Hierarchical database: In a hierarchical database, records contain information about
there groups of parent/child relationships, just like as a tree structure. The structure
implies that a record can have also a repeating information. In this structure Data follows
a series of records, It is a set of field values attached to it.
• Network database: A network databases are mainly used on a large digital computers. It
more connections can be made between different types of data, network databases are
considered more efficiency It contains limitations must be considered when we have to
use this kind of database.
• Relational database: In relational databases, the relationship between data files is
relational. These databases connect to the data in different files by using common data
numbers or a key field.
• Object-oriented database: It takes more than storage of programming language objects.
Object DBMS's increase the semantics of the C++ and Java .It provides full-featured
database programming capability, while containing native language compatibility.
WWW.ENOSISLEARNING.COM
5. ADVANTAGES OF RDBMS
• Data is only stored once (uniquely).
• Complex queries can be carried out.
• Better security.
• Cater for future requirements.
• Types of Relation Database Management System:
• Oracle.
• MySQL (open source).
• PostgreSQL (open source).
• SQLite (open source).
• Microsoft SQL Server.
WWW.ENOSISLEARNING.COM
6. MICROSOFT SQL SERVER
• Microsoft SQL Server is a relational database management system developed
by Microsoft. As a database server, it is a software product with the primary function of
storing and retrieving data as requested by other software applications—which may run
either on the same computer or on another computer across a network (including the
Internet).
• As of December 2016 the following versions are supported by Microsoft:
• SQL Server 2005
• SQL Server 2008 R2
• SQL Server 2012
• SQL Server 2014
• SQL Server 2016
WWW.ENOSISLEARNING.COM
8. STORING DATA USING SQL SERVER
SQL SERVER
MDF LDF
Stores data in This stores the user queries, logs
Page’s
contains
Page size 8 KB
1MB Contains 128 pages
WWW.ENOSISLEARNING.COM
9. LANGUAGE USED FOR MICROSOFT SERVER
• SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving
data stored in relational database.
• SQL is the standard language for Relation Database System. All relational database management systems
like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL as standard database
language.
• Also, they are using different dialects, such as:
• MS SQL Server using T-SQL, Oracle using PL/SQL, MS Access version
Why SQL?
• Allows users to access data in relational database management systems.
• Allows users to describe the data.
• Allows users to define the data in database and manipulate that data.
• Allows to embed within other languages using SQL modules, libraries & pre-compilers.
• Allows users to create and drop databases and tables
• Allows users to create view, stored procedure, functions in a database.
• Allows users to set permissions on tables, procedures and views
WWW.ENOSISLEARNING.COM
10. SQL COMMANDS:
• The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into groups based on their nature:
DDL - Data Definition Language:
• Command Description CREATE Creates a new table, a view of a table, or other object in database
• ALTER Modifies an existing database object, such as a table.
• DROP Deletes an entire table, a view of a table or other object in the database.
DML - Data Manipulation Language: Command Description
• INSERT Creates a record
• UPDATE Modifies records
• DELETE Deletes records
DCL - Data Control Language: Command Description
• GRANT Gives a privilege to user
• REVOKE Takes back privileges granted from user
DQL - Data Query Language: Command Description
• SELECT Retrieves certain records from one or more tables
WWW.ENOSISLEARNING.COM
11. DATABASE COSISTS OF TABLE:
• A table is set of data elements using a model of vertical columns and horizontal rows
where each columns are identified by its unique name .
• A cell in a table is a unit where the row and a column intersect also called as field.
• A table can have specified number of column but n number of rows.
• A row of a table is also called as tuple.
• When a data is filled in the table as per the column in an row then that particular data is
called as a record of that table.
EMPID EMP_NAME SALARY ADDRESS CONTACT
1 RON 15000 Vishrantwadi 123456789
WWW.ENOSISLEARNING.COM
12. CREATE DATABASE AND TABLE:
• To Create a data base we use the command :
• Create database [database name] for ex. Create database Company.
• After creation you have to perform operation on that database you have to use that
database for that the command is.
• Use [database name] for ex. Use Company.
• After creating a database in object explorer under database tab you can see newly
created database named Company ,Lets get introduced to sub tabs under a database.
Contains the table created under specific database
Contains diagram to show relationship of tables easily
Contains the table system views and user views of tables
Contains the stored procedures, functions and trigers
created for that database.
Contains the alternate short names given by user to other
database
WWW.ENOSISLEARNING.COM
13. CREATE A TABLE:
• To create a table inside a database use command:
Create table [table name] ([column name] data type [Constraint],…………. )
For example :
Create Table Employee(
[empid] [int] ,[empname] [nvarchar](40), [empaddress] [nvarchar](100), [salary] [int]
);
Then in Table tab you can see the new created table as given below.
WWW.ENOSISLEARNING.COM
Contains the key like primary, foreign keys for that table
Contains the number of columns in that table
Contains the Constraints such as check , default for table.
Contains the index for that specific table.
15. ALTER TABLE
WWW.ENOSISLEARNING.COM
• Using Alter command we can make changes in the table such as add a column, drop a
column or change data type of a column or delete a constraint in a table.
• Adding Colum :
• Syntax: Alter table [Table Name] add [Column Name 1] [Data Type] , …[Column Name n]
• Alter Column :
• Syntax: Alter table [Table Name] Alter Column [Column Name ] [ new Data Type]
• Drop Column:
• Syntax: Alter table [Table Name] Drop Column [Column Name ]
16. ADD CONSTRAINT USING ALTER TABLE
WWW.ENOSISLEARNING.COM
• Adding Not Null:
Syntax: Alter table [Table Name] Alter Column [column name] Data Type Not Null
• Adding UNIQUE CONSTRAINT:
Syntax: Alter table [Table Name] add constraint [constraint name ] Unique (Column Name)
• Adding DEFAULT CONSTRAINT:
Syntax: Alter table [Table Name] add constraint [constraint name ] Default (Default Value) for
(Column Name)
• Adding CHECK CONSTRAINT:
Syntax: Alter table [Table Name] add constraint [constraint name ] Check (Check Expression)
• Adding PRIMARY KEY:
Syntax: Alter table [Table Name] add constraint [constraint name ] Primary key (Column Name)
• Adding FOREGIN KEY:
Syntax: Alter table [Table Name] add constraint [constraint name ] Foreign key (Column Name)
References Refered_Table_Name(Column name).
17. INSERTING DATA
WWW.ENOSISLEARNING.COM
• To insert data inside a table in sql command used is
• Syntax :
• Insert Into [table name] values( column1_value,columne2_value,…….);
• If the data is in String or in Date format then you have to specify the data in inverted
commas for example:
• Insert into emp_details values(1,’HYDEN’,’NEW YORK’,10000)
In above table emp name and address are in nvarchar so the
The data is specified in inverted commas.
• If you have to enter data to specific columns then you have to mention the column names
that you have to enter for example :
• Insert into emp_details (empid,empname) values(2,’jack’).
• In the above example the data will enter into those particular two columns only and rest
will filled with NULL values if allowed to be NULL or else Error will occur.
18. SELECT
WWW.ENOSISLEARNING.COM
• Select command is used to retrieve a particular piece of information from the data or result set
or to select that information.
• For Example Select 4*4 , select * from [TableName]
•
• In above example * denotes all, i.e the available data inside the table will be return .
You can also specify specific columns that you want to select from the table seperated by comma
for example : select empid,empname from emp_details.
19. ALIASES IN SELECT
WWW.ENOSISLEARNING.COM
• Aliases are the temporary column name given to the column of the table while selecting
the information from the table so that it can be recognized by the user, sometimes we
perform mathematical or concatenation operation on the column so after executing query
there is no specific name is given to the column.
• For Example :
• select ename, sal+comm from emp
• select ename ,sal+comm as Total_Sal from emp
20. CLAUSES IN SQL SELECT
WWW.ENOSISLEARNING.COM
• There are different clauses in sql server used with select to filter the data according to the
user requirement , The clauses are mentioned below according to there priorities :
• SELECT [TOP ( top_expression ) ]
• [ ALL | DISTINCT ]
• { * | column_name | expression }
• [ FROM { table_source } ]
• [ WHERE <search_condition> ]
• [ GROUP BY <group_by_clause> ]
• [ HAVING <search_condition> ]
• [ ORDER BY <order_by_expression> ] [
• OPTION ( <query_option> [ ,...n ] ) ]
21. CLAUSES CONTINUED
WWW.ENOSISLEARNING.COM
• the logical processing order, or binding order, for a SELECT statement. This order determines
when the objects defined in one step are made available to the clauses in subsequent steps.
• FROM
• ON
• JOIN
• WHERE
• GROUP BY
• HAVING
• SELECT
• DISTINCT
• ORDER BY
• TOP
22. EXAMPLE ON SELECT
WWW.ENOSISLEARNING.COM
• Consider the following query as an example.
• SELECT country, YEAR(hiredate) AS yearhired, COUNT(*) AS numemployees FROM
HR.Employees WHERE hiredate >= '20030101' GROUP BY country, YEAR(hiredate)
HAVING COUNT(*) > 1 ORDER BY country , yearhired DESC;
• 1. Evaluate the FROM Clause In the first phase, the FROM clause is evaluated. That’s
where you indicate the tables you want to query and table operators like joins if
applicable. If you need to query just one table, you indicate the table name as the input
table in this clause.
23. SELECT EXAMPLE CONTINUE…
WWW.ENOSISLEARNING.COM
• 2. Filter Rows Based on the WHERE Clause The second phase filters rows based on the
predicate in the WHERE clause. Only rows for which the predicate evaluates to true are
returned.
• 3. Group Rows Based on the GROUP BY Clause This phase defines a group for each
distinct combination of values in the grouped elements from the input table. It then
associates each input row to its respective group.
24. SELECT EXAMPLE CONTINUE…
WWW.ENOSISLEARNING.COM
• 4. Filter Rows Based on the HAVING Clause This phase is also responsible for filtering
data based on a predicate, but it is evaluated after the data has been grouped; hence, it is
evaluated per group and filters groups as a whole.
• 5. process the SELECT Clause The fifth phase is the one responsible for processing the
SELECT clause. What’s interesting about it is the point in logical query processing where
it gets evaluated—almost last. That’s interesting considering the fact that the SELECT
clause appears first in the query.
25. SELECT EXAMPLE CONTINUE…
WWW.ENOSISLEARNING.COM
• 6. handle presentation Ordering The sixth phase is applicable if the query has an ORDER
BY clause. This phase is responsible for returning the result in a specific presentation
order according to the expressions that appear in the ORDER BY list. The query indicates
that the result rows should be ordered first by country (in ascending order by default), and
then by numemployees, descending, yielding the following output.
26. DIFFERENCE BETWEEN HAVING AND WHERE
WWW.ENOSISLEARNING.COM
• 1) Apart from SELECT queries, you can use WHERE clause
with UPDATE and DELETE clause but HAVING clause can only be used with SELECT
query. For example following query, which involve WHERE clause will work but other
which uses HAVING clause will not work :
• update DEPARTMENT set DEPT_NAME="NewSales" WHERE DEPT_ID=1 ; // works
fine
• update DEPARTMENT set DEPT_NAME="NewSales" HAVING DEPT_ID=1 ; // error
• 2) WHERE clause is used for filtering rows and it applies on each and every row,
while HAVING clause is used to filter groups in SQL.
• 3) One syntax level difference between WHERE and HAVING clause is that, former is
used before GROUP BY clause, while later is used after GROUP BY clause.
• 4) When WHERE and HAVING clause are used together in a SELECT query with
aggregate function, WHERE clause is applied first on individual rows and only rows
which pass the condition is included for creating groups. Once group is
created, HAVING clause is used to filter groups based upon condition specified.
27. OPERATORS IN SELECT
WWW.ENOSISLEARNING.COM
• There are different operators can be used with were clause in Select statement :
• AND
• OR
• BETWEEN
• NOT
• IN
• LIKE
• Wild Card Operators :
• %
• _
• [ ]
• [^]
28. JOINS
WWW.ENOSISLEARNING.COM
• SQL is a special-purpose programming language designed for managing information in a
relational database management system (RDBMS). The word relational here is key; it
specifies that the database management system is organized in such a way that there are
clear relations defined between different sets of data.
• The are two types of joins:
• Inner Join (Simple Join)
• Outer Join : There are different types of outer join mentioned bellow:
• Left Outer Join
• Right Outer Join
• Full Outer Join
• Cross Join
In next slide we will look into the complete detail’s of Joins.
29. UPDATE
WWW.ENOSISLEARNING.COM
• If you have to update the existing records in a table, Then Update Statement is used.
• Note : UPDATE statement is always used with where clause, If where clause is not used
with UPDATE statement then all the records will get updated.
• With the update table we can update multiple value’s of a row in the table at a time.
• Syntax :
• UPDATE table_name
SET column1=value1, column2 = value2, columnn = valuen,…..
WHERE some_column = some_value;
30. DELETE
WWW.ENOSISLEARNING.COM
• If you have to Delete the specifc records in a table, Then Update Statement is used.
• Note : DELETE statement is always used with where clause, If where clause is not used
with DELETE statement then all the records will get Delete.
• With the Delete we can delete multiple row’s in the table at a time.
• Syntax :
• DELETE FROM table_name
WHERE some_column=some_value;
31. T-SQL
WWW.ENOSISLEARNING.COM
• T-SQL stands for Transact Structure Query Language which is a Microsoft product and is
an extension of SQL Language which includes points like procedures, functions, Cursor,
Transaction.
• We Can also Declare variables in Sql Server that can be used to store the result from the
select query for further use.
• Syntax: Declare @ [Variable Name] [ Data Type]
• For Example: Declare @Name nvarchar(30);
• We can also set value to an particular variable like :
Set @Name = ‘Sachin’
• To store an result from a Select Statement, We can write query like
Select @name = ename from emp;
• We can also print the value of the variable using print command :
print ‘Name of Employee = ‘+@name
32. FUNCTIONS
WWW.ENOSISLEARNING.COM
• Function are block of statement to perform specific task which is used with the select
statement and cannot execute.
• User-defined functions can be nested; that is, one user-defined function can call another.
The nesting level is incremented when the called function starts execution, and
decremented when the called function finishes execution. User-defined functions can be
nested up to 32 levels. Exceeding the maximum levels of nesting causes the whole calling
function chain to fail.
• Types of User Defined Functions :
• Scalar Function
• Table Valued Function
• Function cannot return multi-valued table to retrieve multivalued data use stored
procedure.
• Syntax : Create function [ Function Name] (Parameters) Return [Data Type] As
Begin
End
33. EXAMPLE ON FUNCTION
WWW.ENOSISLEARNING.COM
• Scalar Function :
CREATE FUNCTION TotalSalary(@empid int) RETURNS int AS
BEGIN
DECLARE @sal int;
DECLARE @incentive int;
SELECT @sal=salary,@ incentive= incentive FROM emp Where Empno=@empid
IF (@sal IS NULL)
SET @sal = 0;
IF (@incentive IS NULL)
SET @ incentive = 0;
@sal=@sal+@ ncentive ;
RETURN @sal;
END;
GO
To use this function :
Select empno, ename, TotalSalary(empno) as TotalSalary from emp
34. PROCEDURE
WWW.ENOSISLEARNING.COM
• A stored procedure in SQL Server is a group of one or more Transact-SQL statements or
a reference to a Microsoft .NET Framework common runtime language (CLR) method.
• The following list describes some benefits of using procedures.
• Reduced server/client network traffic
• Stronger security
• Reuse of code
• Easier maintenance
• Syntax :
Create procedure <procedure_Name>
As Begin
<SQL Statement>
End
• Go
• Sql procedure cannot return Values so there is no return value in procedures.
35. EXAMPLE ON PROCEDURE
WWW.ENOSISLEARNING.COM
• CREATE PROCEDURE FullDetail @LastName nvarchar(50), @FirstName nvarchar(50)
AS
Begin
SELECT FirstName, LastName, Department FROM Employee
WHERE FirstName = @FirstName AND LastName = @LastName
AND EndDate IS NULL;
End
GO
• To execute this procedure after creating the procedure use Execute Or Exec Statement
For Example :
Exec FullDetail ‘Sachin’,’Tendulker’
36. CURSOR
WWW.ENOSISLEARNING.COM
• Cursor is a database object used by applications to manipulate data in a set on a row-by-row
basis, it's like recordset in ASP and Visual Basic.
DECLARE @fName varchar(50), @lName varchar(50)
DECLARE cursorName CURSOR
FOR Select firstName, lastName FROM myTable
OPEN cursorName
FETCH NEXT FROM cursorName INTO @fName, @lName
PRINT @fName + ' ' + @lName
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursorName INTO @fName, @lName
PRINT @fName + ' ' + @lName
END
CLOSE cursorName
37. TRANSACTIONS IN SQL
WWW.ENOSISLEARNING.COM
• A transaction is a unit of work that is performed against a database. Transactions are
units or sequences of work accomplished in a logical order, whether in a manual fashion
by a user or automatically by some sort of a database program.
• Properties of Transactions
• Transactions have the following four standard properties, usually referred to by the
acronym ACID −
• Atomicity − Ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure, and previous operations are
rolled back to their former state.
• Consistency − Ensures that the database properly changes state upon a successfully
committed transaction.
• Isolation − Enables transactions to operate independently of and transparent to each
other.
• Durability − Ensures that the result or effect of a committed transaction persists in case
of a system failure.
38. TRANSACTION CONTROL
WWW.ENOSISLEARNING.COM
• There are following commands used to control transactions −
• COMMIT − To save the changes.
Syntax : COMMIT;
• ROLLBACK − To roll back the changes, Rollback dosent work after commit.
ROLLBACK;
• SAVEPOINT − Creates points within groups of transactions in which to ROLLBACK.
SAVE TRANSACTION SAVEPOINT_NAME
ROLLBACK TO SAVEPOINT_NAME
39. INDEX
WWW.ENOSISLEARNING.COM
• Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very
similar to an index at the end of a book.
• Types of index:
• Create Index:
• CREATE INDEX index_name ON table_name
• Unique Index:
• CREATE UNIQUE INDEX index_name on table_name (column_name)
• Composite Index:
• CREATE INDEX index_name on table_name (column1, column2)
• Implicit Indexes :
• Implicit indexes are indexes that are automatically created by the database server
when an object is created. Indexes are automatically created for primary key
constraints and unique constraints.
• Drop Index:
• DROP INDEX tablename.index_name