0% found this document useful (0 votes)
15 views

DBA Session 3 SQL

Uploaded by

DaniTesfay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

DBA Session 3 SQL

Uploaded by

DaniTesfay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

SQL Commands: DCL and SET

Operators
WHAT IS T-SQL
o Short for Transact-SQL
o is a set of programming extensions that add several features to Structured Query

Language (SQL) including transaction control, exception and error handling, row

processing, and declared variables


o is central to using Microsoft SQL Server. All applications that communicate with an

instance of SQL Server do so by sending Transact-SQL statements to the server,

regardless of the user interface of the application.


o is the main language used to manage and manipulate data in Microsoft SQL Server
o is a dialect of standard SQL. SQL is a standard of both the International Organization

for Standards (ISO) and the American National Standards Institute (ANSI).
TYPES OF T-SQL
STATEMENTS
o T-SQL statements are broadly
divided into four types
₋ Data Definition Language -- DDL
₋ Data Manipulation Language – DML
₋ Data Control Language -- DCL
₋ Transaction Control Language -- TCL
Data Definition Language (DDL)

o Data Definition Language (DDL) is a vocabulary used to define data structures in SQL Server
o Used create, alter, or drop data structures (databases and database Objects)
o Below is what is listed as DDL statements in Microsoft website

CREATE Statements (Transact-SQL)

ALTER Statements (Transact-SQL)

DROP Statements (Transact-SQL)

ENABLE TRIGGER (Transact-SQL)

DISABLE TRIGGER (Transact-SQL)

TRUNCATE TABLE (Transact-SQL)

UPDATE STATISTICS (Transact-SQL)


o We will look at each statements in detail in the following slides
DDL –CREATE/ALTER/DROP STATEMENTS

o Use CREATE statements to define new entities. For example, use CREATE TABLE to add a new table to a

database

o Use ALTER statements to modify the definition of existing entities. For example, use ALTER TABLE to add a

new column to a table, or use ALTER DATABASE to set database options.

o SQL Server Transact-SQL contains a huge list of CREATE/ALTER/DROP statements. CREATE Statements

(Transact-SQL) , ALTER Statements (Transact-SQL) , DROP Statements (Transact-SQL).

o Follow these links for detailed information


₋ Create/Alter/Drop Databases Create/Alter/Drop Schemas

₋ Create/Alter/Drop Database Tables Create/Alter/Drop Views

₋ Create/Alter/Drop Stored Procedures Create/Alter/Drop DML triggers


DDL –CREATE / ALTER/ DROP
DATABASE
o Follow this link for the complete syntax : https://msdn.microsoft.com/en-us/library/ms176061.aspx
o Below is a Simple example for Creating, Altering and Dropping a database
------- Create database
USE master;
GO
CREATE DATABASE Test
ON
( NAME = Test_dat,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\TestDat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Test_log,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\TestLog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB ) ;
GO
------- Alter database
ALTER DATABASE Test
Modify Name = Test2
------- Drop database
DROP DATABASE Test2
DDL –CREATE / ALTER/ DROP
SCHEMAS
• Follow this link for the complete syntax : https://msdn.microsoft.com/en-us/library/ms189462.aspx

• Below is a Simple example for Create , Alter and Drop a Schemas


------- Create Schemas

USE AdventureWorks2012;

GO

CREATE SCHEMA MyNewSchema --AUTHORIZATION '[UserXX]'

CREATE TABLE MyNewTable (source int, cost int, partnumber int)

GO

------- Alter Schemas

ALTER SCHEMA MyNewSchema TRANSFER Person.Address;

------- DROP Schemas --- we have to first drop or transfer the tables in that schema before we drop the schema or it will throw an error

ALTER SCHEMA Person TRANSFER [MyNewSchema].Address;

DROP TABLE [MyNewSchema].[MyNewTable]

DROP SCHEMA MyNewSchema


DDL –CREATE / ALTER/ DROP
TABLES
o Follow this link for the complete syntax : https://msdn.microsoft.com/en-us/library/ms174979.aspx
o Below is a Simple CREATE TABLE Syntax (common if not using options)

CREATE TABLE

[ database_name . [ schema_name ] . | schema_name . ] table_name

( { <column_definition> } [ ,...n ] )

[;]
o Below is a Simple example for Creating, Altering and Dropping a Tables
₋ Create Tables

USE [AdventureWorks2022]

CREATE TABLE dbo.Employee

(EmployeeID int PRIMARY KEY CLUSTERED, EmployeeName nvarchar (25), DOB date);
DDL –CREATE / ALTER/ DROP
TABLES

o Alter Tables –Adds new column to the table (

https://msdn.microsoft.com/en-us/library/ms190273.aspx )

ALTER TABLE dbo.Employee ADD column_additional VARCHAR(20)

NULL ;

o DropTables – Removes the table from the database (

https://msdn.microsoft.com/en-us/library/ms173790.aspx )

DROP TABLE dbo.Employee


DDL –CREATE / ALTER/ DROP VIEWS

o Follow this link for the complete syntax :


https://msdn.microsoft.com/en-us/library/ms174979.aspx
o Below is a Simple Create View Syntax
CREATE VIEW <schema_name>.<view_name>
AS
<Select Statement>
DDL –CREATE / ALTER/ DROP
VIEWS
o Below is a Simple example for Creating, Altering and Dropping a Views
₋ Create View Example

USE [AdventureWorks2022];

GO

CREATE VIEW hiredate_view

AS

SELECT p.FirstName, p.LastName, e.BusinessEntityID, e.HireDate

FROM HumanResources.Employee e

JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID ;

GO
DDL –CREATE / ALTER/ DROP VIEWS

o Alter View
ALTER VIEW hiredate_view ----what has changed?

AS

SELECT p.FirstName, p.LastName, e.BusinessEntityID, e.HireDate

FROM HumanResources.Employee e

JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID

WHERE e.HireDate >'2005-01-01’ -----What has changed?

GO
o Drop View
DROP VIEW hiredate_view
DDL – CREATE / ALTER / DROP STORED
PROCEDURE
o Follow this link for the complete syntax : https://msdn.microsoft.com/en-us/library/ms187926.aspx
o Below is a Simple Create Stored Procedure Syntax
CREATE PROCEDURE <Schema_Name>.<Procedure_Name> <@param1, sysname, @p1> <datatype_for_param1, , int> = <default_value_for_param1, , 0>,
AS
<Statement…..>
-- Example to execute the stored procedure
EXECUTE <Schema_Name>.<Procedure_Name> <value_for_param1, , 1>

• Below is a Simple example for Creating, Altering and Dropping Stored Procedure
--------- Create Stored Procedures

CREATE PROCEDURE HumanResources.uspGetEmployees


@LastName nvarchar(50),
@FirstName nvarchar(50),
@department nvarchar(50)
AS
SELECT FirstName, LastName, JobTitle, Department
FROM HumanResources.vEmployeeDepartment
WHERE FirstName = @FirstName OR LastName = @LastName or Department=@department;
GO
EXECUTE HumanResources.uspGetEmployees N'Ackerman', N'Pilar', N'Tool Design';
--------- Alter Stored Procedures
Alter PROCEDURE HumanResources.uspGetEmployees @LastName nvarchar(50), @FirstName nvarchar(50), @department nvarchar(50) --What has changed?
AS
SELECT FirstName, LastName, JobTitle, Department
FROM HumanResources.vEmployeeDepartment
WHERE FirstName = @FirstName OR LastName = @LastName ; ---- what has changed?
GO
--------- Alter Stored Procedures
DROP PROCEDURE HumanResources.uspGetEmployees
DDL –CREATE / ALTER/ DROP TRIGGERS
• Follow this link for the complete syntax : https://msdn.microsoft.com/en-us/library/ms189799.aspx

• A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server

• There are three types of triggers in SQL server


1. DML : execute when a user tries to modify data using Insert, Update or Delete statements on a table or view
2. DDL: execute when a user runs Create, Alter or Drop statements
3. Logon: fire in response to the LOGON event that is raised when a user sessions is being established

• We will see the syntax and one simple example for each kind

1. DML TRIGGER
Simple DML Trigger Syntax
CREATE TRIGGER [ schema_name . ] [trigger_name]
ON { table | view }
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }


DDL –CREATE / ALTER/ DROP TRIGGERS
The following DML trigger prevents a row from being inserted in the Purchasing.PurchaseOrderHeader table -- when the credit
rating of the specified vendor is set to 5 (below average).
CREATE TRIGGER [Purchasing].[LowCredit] ON [Purchasing].[PurchaseOrderHeader]
AFTER INSERT
AS
IF EXISTS (SELECT *
FROM Purchasing.PurchaseOrderHeader AS p
JOIN inserted AS i
ON p.PurchaseOrderID = i.PurchaseOrderID
JOIN Purchasing.Vendor AS v
ON v.BusinessEntityID = p.VendorID
WHERE v.CreditRating = 5
)
BEGIN
RAISERROR ('A vendor''s credit rating is too low to accept new purchase orders.', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;

This statement attempts to insert a row into the PurchaseOrderHeader table for a vendor that has a below average credit rating.
The AFTER INSERT trigger is fired and the INSERT transaction is rolled back.
----Test the trigger
INSERT INTO Purchasing.PurchaseOrderHeader (RevisionNumber, Status, EmployeeID, VendorID, ShipMethodID, OrderDate, ShipDate, SubTotal, TaxAmt,
Freight)
VALUES (2 ,3 ,261 ,1652 ,4 ,GETDATE() ,GETDATE() ,44594.55 ,3567.564 ,1114.8638 );
GO
DDL –CREATE / ALTER/ DROP TRIGGERS

2. DDL TRIGGER : Trigger on a CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE STATISTICS
statement

• Simple DDL Trigger Syntax


CREATE TRIGGER trigger_name
ON { ALL SERVER | DATABASE }
{ FOR | AFTER } { event_type | event_group } [ ,...n ]
AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] }
• Example
USE MASTER
GO
CREATE TRIGGER ddl_trig_database
ON ALL SERVER
FOR CREATE_DATABASE
AS
SELECT 'Database Created on' + ' ' + convert (nvarchar(17), GETDATE())
GO
-test the trigger
create database [test3]
--Clean up
DROP DATABASE [test3]

DROP TRIGGER ddl_trig_database


ON ALL SERVER;
GO
DDL – CREATE / ALTER/ DROP TRIGGERS

2. Logon TRIGGER : Trigger on a CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE STATISTICS statement
• Simple Logon Trigger Syntax
CREATE TRIGGER trigger_name
ON ALL SERVER
{ FOR| AFTER } LOGON
AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] }
• Example
---Preparation
USE master;
GO
CREATE LOGIN login_test WITH PASSWORD = '3KHJ6dhx(0xVYsdf' MUST_CHANGE,
CHECK_EXPIRATION = ON;
GO
GRANT VIEW SERVER STATE TO login_test;
GO
-- Create the logon Trigger
CREATE TRIGGER connection_limit_trigger
ON ALL SERVER WITH EXECUTE AS 'login_test'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN()= 'login_test'
ROLLBACK;
END;
---Clean up (DROPPING)
drop trigger connection_limit_trigger
ON ALL SERVER;
GO
DDL Summary
CREATE Statements (Transact-SQL) –covered in the pervious Slides
ALTER Statements (Transact-SQL) ---covered in the pervious Slides
DROP Statements (Transact-SQL) ---covered in the pervious Slides

DISABLE TRIGGER (Transact-SQL) and ENABLE TRIGGER (Transact-SQL)


• Disable Trigger is used to disable triggers that are temporarily unused. Dropping a trigger is the way to go if we don’t want it
permanently. Enable Trigger enables a trigger that has explicitly been disabled
CREATE TRIGGER safety
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "safety" to drop or alter tables!'
ROLLBACK;
GO
DISABLE TRIGGER safety ON DATABASE;
GO
ENABLE TRIGGER safety ON DATABASE;
GO
TRUNCATE TABLE (Transact-SQL) removes all rows from a table or specified partitions of a table, without logging the individual row deletions
USE AdventureWorks2012;
GO
SELECT COUNT(*) AS BeforeTruncateCount
FROM HumanResources.JobCandidate;
GO
TRUNCATE TABLE HumanResources.JobCandidate;
GO
SELECT COUNT(*) AS AfterTruncateCount
FROM HumanResources.JobCandidate;
GO
UPDATE STATISTICS (Transact-SQL) --- Will be discussed in later chapters
DML
o Data Manipulation Language (DML) is a vocabulary used to retrieve, add, modify or remove data from a

SQL Server database


o Below is what is listed as DML statements in Microsoft website

• SELECT (Transact-SQL) • BULK INSERT (Transact-SQL)


• INSERT (Transact-SQL) • READTEXT (Transact-SQL)**
• UPDATE (Transact-SQL) • UPDATETEXT (Transact-SQL)**

• DELETE (Transact-SQL) • WRITETEXT (Transact-SQL)**

• MERGE (Transact-SQL)
o We will look at the basic DML statements in more detail in the following slides
o Others marked with ** are reading assignments.
DML –SELECT STATEMENTS
• Retrieves rows from the database and enables the selection of one or many rows or columns from one or many tables in SQL
Server.

• The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:
SELECT [column List]
FROM [Table/s Name]
WHERE [List Of Criteria]
GROUP BY group_by_expression
HAVING search_condition
ORDER BY order_expression [ ASC | DESC ]

• The following example returns all rows and all columns in Sales.SalesOrderHeader table. Notice that it returns 31,465 rows
SELECT *
FROM [AdventureWorks2012].[Sales].[SalesOrderHeader]

• The following example limits the columns to be returned to OrderDate, Status, CustomerID and SubTotal by specifying the
column names. It also limits the number of rows returned to orders that are places after January 1, 2008 by using a WHERE
clause. Notice that the number of rows are 13,811 rather than 31,465 rows are returned by the previous script.
SELECT [OrderDate], [Status], [CustomerID], [SubTotal]
FROM [AdventureWorks2012].[Sales].[SalesOrderHeader]
WHERE OrderDate>'2008-01-01‘
DML –SELECT STATEMENTS
In summary , a basic SELECT statement that returns data from a single table consists of three different parts

1. The SELECT Key word for COLUMN LISTING

• The column list follows the SELECT keyword and is where you specify the columns you want to return from your table. The columns are
identified by specifying the column name. If multiple columns are listed they are separated by commas.

• To select all the columns from a table, we use an asterisk (*) instead of specify the individual column names. However it is always a good idea to
specify column names to account for changing table structure.

2. The FROM Clause

• The FROM clause is where you identify the table from which you want to select data.

• In this level we are only discussing selecting data from a single table in the FROM clause. Note the FROM clause can identify multiple tables
from which to select data by using JOINS.

• You can identify the table by using just the table name where the schema is dbo, or table name and Schema name or database name, schema
name and table name

3. The WHERE Clause


• The WHERE clause of a SELECT statement is optional.

• The WHERE clause is used to constrain the rows that are returned from a SELECT statement.

• The database engine evaluates each row against the WHERE clause and then only returns rows if they meet the search condition or conditions
identified in the WHERE clause.
DML –SELECT STATEMENTS
•Using the AS key word to create Table and Column Aliases. It is allowed to omit the AS keyword. It is however best practice to add it to make
code readable.
1. Table aliases: The readability of a SELECT statement can be improved by giving a table an alias . If an alias is assigned to a table, all explicit
references to the table in the Transact-SQL statement must use the alias, not the table name

SELECT S.[OrderDate] , S.[Status], S.[CustomerID] , S.[SubTotal]


FROM [AdventureWorks2012].[Sales].[SalesOrderHeader] AS S
WHERE OrderDate>'2008-01-01'

2. Column Aliases – are used to give human friendly names for columns on your query result. Note that it will not change the column name on
the actual table in the database. Also Note the use of [] character.

SELECT [OrderDate] AS [Order Date], [Status], [CustomerID] AS [Customer ID], [SubTotal] AS [Sub Total]
FROM [AdventureWorks2012].[Sales].[SalesOrderHeader]
WHERE OrderDate>'2008-01-01‘

2. Using SELECT with column headings and calculations

SELECT [OrderDate], [Status], [CustomerID] , [SubTotal], ([SubTotal] -50 ) AS [Discounted Total]


FROM [AdventureWorks2012].[Sales].[SalesOrderHeader]
WHERE OrderDate>'2008-01-01‘

3. Using DISTINCT to prevent duplicate rows. Note that if we don’t have DISTINCT in this statement, the number of rows would be 290 instead
of just 67
SELECT DISTINCT JobTitle
FROM HumanResources.Employee
ORDER BY JobTitle;
4. Using TOP to limit the data retrieved from a table. Note that the number of rows returned are the same as the one on the TOP keyword
SELECT TOP 5 JobTitle
FROM HumanResources.Employee
DML –SELECT STATEMENTS
•Using select statements to create Permanent or Temporary tables.
select * from dbo.NewProducts -- check if this table exists
_______________________________________________________________
SELECT *
INTO dbo.NewProducts -- This usually is a temporary table (#NewProducs)
FROM Production.Product
WHERE ListPrice > $25
AND ListPrice < $100;
GO
________________________________________________________________
select * from dbo.NewProducts

• Using Subqueries in SELECT STATEMENTS


SELECT DISTINCT Name
FROM Production.Product
WHERE ProductModelID IN
(SELECT ProductModelID
FROM Production.ProductModel
WHERE Name LIKE 'Long-Sleeve Logo Jersey%');

• Ordering your records by using the ORDER BY clause.

Note that you can order by a single column or multiple columns. It will order by the order of the columns in the order by clause from left to right. Use
ASC (A-Z) or DESC(Z-A). By default the order by clause will order in an Ascending order.

SELECT Name, ProductNumber, ListPrice AS Price


FROM Production.Product
ORDER BY Name DESC ----OR ASC
DML –SELECT STATEMENTS
• Summarizing Data Using a Simple GROUP BY Clause and AGGREGATE Functions

• SQL Server has the following aggregate functions :


AVG CHECKSUM_AGG
COUNT COUNT_BIG
MAX GROUPING, GROUPING_ID
MIN STDEV , STDEVP
SUM VAR , VARP

• Whenever we use aggregate functions in a SELECT statement, we have to use a GROUP BY Clause to group the result set

--- Groups by a single column


SELECT SalesOrderID, SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID -- see what happens when you omit the group by clause
ORDER BY SalesOrderID;

--- Groups by a multiple column


SELECT ProductID, SpecialOfferID, AVG(UnitPrice) AS [Average Price], SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY ProductID, SpecialOfferID -- see what happens when you omit SpecialOfferID from the group by clause
ORDER BY ProductID;
DML –SELECT STATEMENTS
• Using the Having Clause

• Having specifies a search condition for a group or an aggregate.

• It can be used only with the SELECT statement.

• HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a
WHERE clause. Note the use of OPERATORS. (= , >, >=, <, <=, <>, Like, Not Like, IN , Not IN……)
SELECT SalesOrderID, SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID
HAVING SUM(LineTotal) > 100000.00
ORDER BY SalesOrderID ;

• Note that the Number of roes returned when using the Having clause is 54 instead of 31,465 when not used.
SELECT ProductID, AVG(OrderQty) AS AverageQuantity, SUM(LineTotal) AS Total
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING SUM(LineTotal) > $1000000.00 AND AVG(OrderQty) < 3;

END OF SELECT AT LEAST FOR NOW


DML –INSERT STATEMENTS
• Adds one or more rows to a table or a view in SQL Server

• The basic Syntax for INSERT statement is :


INSERT INTO [SCHEMA].[TableName]
(Column1, Column2, Column 3...)
VALUES
(ValueForColumn1, ValueForColumn2, ValueForColumn3...)
GO
• Inserting a single row of data. Note that because values for all columns are supplied and are listed in the same order as
the columns in the table, the column names do not have to be specified in the column list
INSERT INTO Production.UnitMeasure
VALUES (N'FT', N'Feet', '20080414');

• Inserting data that is not in the same order as the table columns. We have to explicitly specify the
values that are inserted into each column
INSERT INTO Production.UnitMeasure (Name, UnitMeasureCode, ModifiedDate)
VALUES (N'Square Yards', N'Y2', GETDATE());

• Inserting a multiple rows of data


INSERT INTO Production.UnitMeasure
VALUES (N'FT2', N'Square Feet ', '20080923')
, (N'Y', N'Yards', '20080923'), (N'Y3', N'Cubic Yards', '20080923');
DML –INSERT STATEMENTS – Most common
• Using the SELECT and EXECUTE options to insert data from other tables
----PREPARATION WORK --- CREATED A TABLE AND STORED PROCEDURE TO BE USED FOR THE INSERT USING SELECT AND EXECURTE EXAMPLE
______________________________________________________________________________________________________________________

CREATE TABLE dbo.EmployeeSales CREATE PROCEDURE dbo.uspGetEmployeeSales


( DataSource varchar(20) NOT NULL, AS
BusinessEntityID varchar(11) NOT NULL, SET NOCOUNT ON;
LastName varchar(40) NOT NULL, SELECT 'PROCEDURE', sp.BusinessEntityID, c.LastName, sp.SalesYTD
FROM Sales.SalesPerson AS sp
SalesDollars money NOT NULL
INNER JOIN Person.Person AS c
); ON sp.BusinessEntityID = c.BusinessEntityID
GO WHERE sp.BusinessEntityID LIKE '2%'
ORDER BY sp.BusinessEntityID, c.LastName;
GO

_________________________________________________________________________________________________________________________________
• INSERT...SELECT example
------SELECT * FROM dbo.EmployeeSales (HAS 0 ROWS)
INSERT INTO dbo.EmployeeSales
SELECT 'SELECT', sp.BusinessEntityID, c.LastName, sp.SalesYTD
FROM Sales.SalesPerson AS sp
INNER JOIN Person.Person AS c
ON sp.BusinessEntityID = c.BusinessEntityID
WHERE sp.BusinessEntityID LIKE '2%'
ORDER BY sp.BusinessEntityID, c.LastName;

----SELECT * FROM dbo.EmployeeSales (HAS 17 ROWS)


• INSERT...EXECUTE procedure example
INSERT INTO dbo.EmployeeSales
EXECUTE dbo.uspGetEmployeeSales;
GO
----SELECT * FROM dbo.EmployeeSales (HAS 34 ROWS)
DML –UPDATE STATEMENTS
• Changes (Modifies) existing data in a table or view in SQL Server

• The basic Syntax for UPDATE Statement is :


UPDATE [schema_name . ] [table_name ]
SET column_name = expression
[ FROM from_clause ]
[ WHERE <search_condition>]
• Using a simple UPDATE statement
UPDATE Person.Address
SET ModifiedDate = GETDATE(); --(19614 row(s) affected)
• Updating multiple columns
UPDATE Sales.SalesPerson
SET Bonus = 6000, CommissionPct = .10, SalesQuota = NULL; --(17 row(s) affected)
• Limiting the Rows that Are Updated USING the WHERE clause
UPDATE Production.Product
SET Color = N'Metallic Red'
WHERE Name LIKE N'Road-250%' AND Color = N'Red';
• Specifying a computed value
UPDATE Production.Product
SET ListPrice = ListPrice * 2;
DML –UPDATE STATEMENTS
• Using UPDATE in a stored procedure
CREATE PROCEDURE HumanResources.Update_VacationHours
@NewHours smallint
AS
SET NOCOUNT ON;
UPDATE HumanResources.Employee
SET VacationHours = @NewHours
WHERE CurrentFlag = 1;
GO --EXEC HumanResources.Update_VacationHours 40; SELECT VacationHours from HumanResources.Employee

• Updating a table Based on Data From Other Tables


UPDATE Sales.SalesPerson
SET SalesYTD = SalesYTD + SubTotal
FROM Sales.SalesPerson AS sp JOIN Sales.SalesOrderHeader AS so
ON sp.BusinessEntityID = so.SalesPersonID
WHERE so.OrderDate = '2008-06-01';

• Using UPDATE in a TRY…CATCH Block


BEGIN TRANSACTION;
BEGIN TRY
-- Intentionally generate a constraint violation error.
UPDATE HumanResources.Department
SET Name = N'MyNewName'
WHERE DepartmentID BETWEEN 1 AND 2;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber ,ERROR_STATE() AS ErrorState ,ERROR_LINE() AS ErrorLine ,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
DML –DELETE STATEMENTS
• Removes one or more rows from a table or view in SQL Server

• The basic Syntax for DELETE statement is :


DELETE FROM [schema. ] table_name
[ WHERE <search_condition> ]

• Deleting all rows. Note that this is not common, if you have to delete all rows use TRUNCATE
DELETE FROM Sales.SalesPersonQuotaHistory; --deletes all 160 rows

• Using the WHERE clause to limit the rows to be deleted


DELETE FROM Production.ProductCostHistory
WHERE StandardCost > 1000.00;--- deletes 50 rows that qualify the condition in the where clause
• Deleting rows in one table depending on data on another table
DELETE FROM Sales.SalesPersonQuotaHistory
FROM Sales.SalesPersonQuotaHistory AS spqh
INNER JOIN Sales.SalesPerson AS sp
ON spqh.BusinessEntityID = sp.BusinessEntityID
WHERE sp.SalesYTD > 2500.00;

• Capturing the results of the DELETE statement


DELETE Sales.ShoppingCartItem
OUTPUT DELETED.*
WHERE ShoppingCartID = 20621;
DML –MERGE STATEMENTS
• Performs insert, update, or delete operations on a target table based on the results of a join with a source
table.

• For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based
on differences found in the other table

• The basic Syntax for MERGE statement is :

MERGE [AS TARGET]


USING [AS SOURCE]
ON
[WHEN MATCHED
THEN ]
[WHEN NOT MATCHED [BY TARGET]
THEN ]
[WHEN NOT MATCHED BY SOURCE
THEN ];

• Better explained by an example


DML –MERGE STATEMENTS
• A simple merge example
MERGE INTO Sales.SalesReason AS Target
USING (VALUES ('Recommendation','Other'), ('Review', 'Marketing'), ('Internet', 'Promotion'))
AS Source (NewName, NewReasonType)
ON Target.Name = Source.NewName
WHEN MATCHED THEN
UPDATE SET ReasonType = Source.NewReasonType
WHEN NOT MATCHED BY TARGET THEN
INSERT (Name, ReasonType) VALUES (NewName, NewReasonType); ----Three rows affected --2 added, 1 updated

Before Merge After Merge


DML Summary

Follow the link to learn more about these statements

• SELECT (Transact-SQL) ………covered in the pervious Slides


• INSERT (Transact-SQL) ………covered in the pervious Slides
• UPDATE (Transact-SQL) ………covered in the pervious Slides
• DELETE (Transact-SQL) ………covered in the pervious Slides
• MERGE (Transact-SQL) ………covered in the pervious Slides
• BULK INSERT (Transact-SQL) –Will be discussed in future classes
• READTEXT (Transact-SQL) –Reading assignment UPDATETEXT (Transact-SQL)---Reading assignment
• WRITETEXT (Transact-SQL)---Reading assignment
DCL – DATA CONTROL LANGUAGE
• Short for Data Control Language

• Is a subset of the Structured Query Language (SQL) that allows database administrators to configure
security access to databases

• DCL is the simplest of the SQL subsets, as it consists of only three commands:
1. GRANT
2. REVOKE
3. DENY

• Combined, these three commands provide administrators with the flexibility to set and remove
database permissions in an extremely granular fashion.
DCL -- GRANT
• The GRANT command is used by administrators to add new permissions to a database user. It has a very
simple syntax, defined as follows:
GRANT [privilege] GRANT SELECT
ON [object] ON [HR].[Employees]
TO [user] TO Joe

Privilege: database permission or set of permissions. Examples include CREATE DATABASE, SELECT,
INSERT, UPDATE, DELETE, EXECUTE, and CREATE VIEW

Object may be any database object. Typically the object will be either a database, function, stored procedure,
table or view

User may be any database user. You may also substitute a role for the user in this clause if you wish to make use
of role-based database security.

If you include the optional WITH GRANT OPTION clause at the end of the GRANT command, you not only
grant the specified user the permissions defined in the SQL statement, but also give the user the ability to grant
those same permissions to other database users.
DCL -- REVOKE
• The REVOKE command is used to remove database access from a user previously granted such access. The
syntax for this command is defined as follows:
REVOKE [GRANT OPTION FOR] [permission] REVOKE SELECT
ON [object] ON [HR].[Employees]
FROM [user] FROM Joe

Permission specifies the database permissions that you wish to remove from the identified user. The command
will revoke both GRANT and DENY assertions previously made for the identified permission.

Object may be any database object. Typically the object will be either a database, function, stored procedure,
table or view

User may be any database user. You may also substitute a role for the user in this clause if you wish to make use
of role-based database security.

The GRANT OPTION FOR clause removes the specified user's ability to grant the specified permission to
other users. It is important to note that if you include the GRANT OPTION FOR clause in a REVOKE statement,
the primary permission is NOT revoked. This clause causes ONLY the granting ability to be revoked.
DCL - DENY

• The DENY command may be used to explicitly prevent a user from receiving a particular permission.. The
syntax for this command is defined as follows:

DENY [permission] DENY DELETE


ON [object] ON [HR].[Employees]
TO [user] TO Matthew

• The parameters for the DENY command are identical to those used for the GRANT command
TCL – TRANSACTION CONTROL LANGUAGE

• TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a
database

• Transaction Control Language (TCL) is playing an important role in SQL. Transaction control language is used for statements
are used to manage the changes made by DML statements. It allows statements to be grouped together into logical
transactions. There are lots of TCL commands which are used in SQL in which some are namely defined as follows:

1. Commit a transaction: Saves work done in transactions

Syntax: Demonstration of using commit in SQL server transaction


COMMIT [TRAN | TRANSACTION] [TRANSACTION_NAME | TRANSACTION_VARIABLE_NAME]

Example: Demonstration of using commit in SQL server transaction


BEGIN TRANSACTION T1
GO
UPDATE Userlogin SET Name ='James Baswar' WHERE ID = '101'
GO
COMMIT TRANSACTION T1; ----- COMMIT TRANSACTION T1
GO
TCL…
2. Savepoint: Savepoint command is used for identify a point in a transaction to which you can later roll back. Savepoints are
useful in situations where errors are unlikely to occur. The use of a savepoint to roll back part of a transaction in the case of an
infrequent error can be more efficient than having each transaction test to see if an update is valid before making the update.
Updates and rollbacks are expensive operations, so savepoints are effective only if the probability of encountering the error is low
and the cost of checking the validity of an update beforehand is relatively high.
Syntax: Demonstration of using Savepoint in SQL server transaction
SAVE [TRAN | TRANSACTION ] [SQVEPOINT_NAME | SAVEPOINT_VARIABLE_NAME]
Example
CREATE TABLE TESTSAVEPOINT(PRODUCT_ID INT PRIMARY KEY, PRODUCT_NAME VARCHAR(50))
GO
BEGIN TRANSACTION T1;
GO
INSERT INTO TESTSAVEPOINT VALUES (1001 , 'MOUSE')
INSERT INTO TESTSAVEPOINT VALUES (1002 , 'KEYBOARD')
UPDATE TESTSAVEPOINT SET PRODUCT_NAME = 'MONITOR' WHERE PRODUCT_ID = 1002
GO
SAVE TRANSACTION SAVEP1; ---------- CREATING FIRST SAVEPOINT SAVEP1
GO
INSERT INTO TESTSAVEPOINT VALUES (1003, 'KEYBOARD')
INSERT INTO TESTSAVEPOINT VALUES (1004, 'PRINTER')
GO
SAVE TRANSACTION SAVEP2; ---------- CREATING FIRST SAVEPOINT SAVEP1
GO
INSERT INTO TESTSAVEPOINT VALUES (1005, 'SCANNER')
UPDATE TESTSAVEPOINT SET PRODUCT_NAME = 'CPU' WHERE PRODUCT_ID = 1005

ROLLBACK TRANSACTION SAVEP2 ---- TRANSACTION ROLLBACKED TO SAVEPOINT SAVEP2 SO IT'S VALUE NOT INSERTED
INTO TABLE
INSERT INTO TESTSAVEPOINT VALUES (1006,'SCANNER')
COMMIT TRANSACTION T1;
TCL….
3. Rollback transaction: Rollback command is used for restore database to original since last commit. Rollback transaction
erases all data modifications made from the start of the transaction or to a savepoint. The ROLLBACK statement in SQL cancels
the proposed changes in a pending database transaction. The transaction can be rolled back completely by specifying the
transaction name in the ROLLBACK statement.

Syntax: Demonstration using rollback in SQL transaction


ROLLBACK [TRAN | TRANSACTION ] [SAVEPOINT_NAME | SAVEPOINT_VARRIABLE ] ;

Example: Demonstration using rollback in SQL transaction


CREATE TABLE TESTROLLBACK(EMPID INT PRIMARY KEY, EMPNAME VARCHAR(20) )
GO
INSERT INTO TESTROLLBACK VALUES (1001,'JAMES GOSLING')
GO
BEGIN TRANSACTION T1; -------BEGIN TRANSACTION
GO
INSERT INTO TESTROLLBACK VALUES (1002,'RAHMAAN')
GO
SAVE TRANSACTION SAVEP1; ------CREATE SAVE POINT IN TRANSACTION
GO
INSERT INTO TESTROLLBACK VALUES (1003,'PETERE BABHBAD')
INSERT INTO TESTROLLBACK VALUES (1004,'HERMAINI')
UPDATE TESTROLLBACK SET EMPNAME = 'ARUN SINGH' WHERE EMPID =1003
GO
ROLLBACK TRANSACTION SAVEP1 ; ----------- ROLLBACK TRANSACTION TO SAVEP1 SAVEPOINT
GO
COMMIT TRANSACTION T1; --- COMMIT TRANSACTION T1 TO SAVE ALL WORK DONE
TCL..
4. Set transaction: Set transaction command is used for Change transaction options like isolation level and what rollback
segment to use. Only one of the isolation level options can be set at a time, and it remains set for that connection until it is
explicitly changed. All read operations performed within the transaction operate under the rules for the specified isolation level
unless a table hint in the FROM clause of a statement specifies different locking or versioning behavior for a table.
Syntax: Demonstration of using set transaction isolation level in SQL server
SET TRANSACTION ISOLATION LEVEL
{ READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SNAPSHOT | SERIALIZABLE} ;

Example: Demonstration of using set transaction isolation level in SQL server


CREATE TABLE TESTSETTRANSACTION(STU_ID INT PRIMARY KEY, STU_NAME VARCHAR(30), STU_DESCRIPTION VARCHAR(100))
GO
INSERT INTO TESTSETTRANSACTION VALUES (100, 'HARRY WATSON' ,'HARRY DO NOT ATTEND 100% COLLEGE')
INSERT INTO TESTSETTRANSACTION VALUES (101, 'BRUCLI GOVINDA ' ,'BRUCLI IS A INTELLIGENT BOY ')
GO
SET TRANSACTION ISOLATION LEVEL READ COMMITTED ;
GO
BEGIN TRAN T1;
GO
UPDATE TESTSETTRANSACTION SET STU_NAME = 'ARUN RAMALINGAM' WHERE STU_ID = 100
SELECT * FROM TESTSETTRANSACTION
GO
BEGIN TRAN T2 ;
GO
SELECT * FROM TESTSETTRANSACTION
GO
COMMIT TRAN T2;
GO
COMMIT TRAN T1;
GO
More on T-SQL – Combining Tables
• We can combining tables by using the following depending on what we like to query

1. Using JOINS – Combines columns

• CROSS JOINS
• INNER JOINS
• OUTER JOINS
• SELF JOINS

2. Using Set Operators –Combines rows


• UNION ALL
• UNION
• INTERSECT
• EXCEPT

➢ In the interest of time and scope, Subqueries are not covered here, but those are also used for combining tables
More on T-SQL – Combining Tables - JOINS
• The tables are usually related through keys, such as a foreign key in one side and a primary key in the other. Then you can use
joins to query the data from the different tables and match the rows that need to be related. There are four general types:

1. Cross Joins
A cross join is the simplest type of join, though not the most commonly used one. This join performs what’s known as a
Cartesian product of the two input tables. If you have m rows in table T1 and n rows in table T2, the result of a cross join
between T1 and T2 is a virtual table with m × n rows.

2. Inner Joins
With an inner join, you can match rows from two tables based on a predicate—usually one that compares a primary key value in
one side to a foreign key value in another side.

3. Outer Joins
With outer joins, you can request to preserve all rows from one or both sides of the join, never mind if there are matching rows in
the other side based on the ON predicate. By using the keywords LEFT OUTER JOIN (or LEFT JOIN for short), you ask to
reserve the left table. The join returns what an inner join normally would—that is, matches (call those inner rows). In addition,
the join also returns rows from the left that had no matches in the right table (call those outer rows), with NULLs used as
placeholders in the right side. The other Outer Join keyword is RIGHT OUTER JOIN (or RIGHT JOIN for short)

4. Self Join
A table can be joined to itself in a self-join. Use a self-join when you want to create a result set that joins records in a table with
other records in the same table. To list a table two times in the same query, you must provide a table alias for at least one of
instance of the table name. This table alias helps the query processor determine whether columns should present data from the
right or left version of the table. The famous example for this is Employee Manager hierarchy in Employee tables.
More on T-SQL – Combining Tables - JOINS
• Types of Joins can be represented as follows pictorially
More on T-SQL – Combining Tables - JOINS
• Joins representations with Venn Diagrams -→ Remember back in the days at school, well it is back! ☺
More on T-SQL – Combining Tables - JOINS
• Let us look at Joins with Examples:
1. Cross Join
SELECT p.BusinessEntityID, t.Name AS Territory
FROM Sales.SalesPerson p
CROSS JOIN Sales.SalesTerritory t
ORDER BY p.BusinessEntityID; -- The result set contains 170 rows (SalesPerson has 17 rows and SalesTerritory has 10; 17 multiplied by 10 equals 170)
2. Inner Join
SELECT p.FirstName, p.LastName, e.HireDate, e.JobTitle
FROM HumanResources.Employee AS e
INNER JOIN Person.Person AS p
ON e.BusinessEntityID = p.BusinessEntityID --- returns value only when this values are matching
ORDER BY p.LastName
3. Left Outer Join
SELECT p.Name, pr.ProductReviewID
FROM Production.Product p
LEFT OUTER JOIN Production.ProductReview pr
ON p.ProductID = pr.ProductID -- returns every value on the product table whether there is a match or not. Non matched product IDs will yield Null
4. Right Outer Join
SELECT st.Name AS Territory, sp.BusinessEntityID
FROM Sales.SalesTerritory st
RIGHT OUTER JOIN Sales.SalesPerson sp
ON st.TerritoryID = sp.TerritoryID ; -- returns every value on the SalesPerson table whether there is a match or not. Non matched TerritoryIDs will yield Null
5. Full Outer Join
SELECT p.Name, sod.SalesOrderID
FROM Production.Product p
FULL OUTER JOIN Sales.SalesOrderDetail sod
ON p.ProductID = sod.ProductID
6. Self Join
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName, e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM tblEmployee e1
JOIN tblEmployee e2
ON e1.emp_mgr_id = e2.emp_id
T-SQL – Combining Tables - SET
OPERATORS

 UNION
 UNION ALL
 INTERSECT
 EXCEPT
T-SQL – Combining Tables - SET OPERATORS

o Set operators operate on two result sets of queries, comparing


complete rows between the results.

o T-SQL supports three set operators:

₋ UNION and UNION ALL

₋ INTERSECT

₋ EXCEPT
T-SQL – Combining Tables - SET
OPERATORS

o UNION and UNION ALL

₋ UNION: A set operator unifies the results of the two


input queries.

₋ As a set operator, UNION has an implied DISTINCT


property, meaning that it does not return duplicate
rows.

₋ UNION ALL is a multi set operator where it returns


duplicate rows.
Basic rules of UNION

o To combine the result sets of two quires, we have to obey that:


₋ The number and the order of the columns must be the same in all quires
₋ The datatype must be compatible
o Syntax
{ <query_specification> | ( <query_expression> ) }

{ UNION [ ALL ]
{ <query_specification> |
( <query_expression> ) }
[ ...n ] }
T-SQL – Combining Tables - SET
OPERATORS

o INTERSECT

₋ The INTERSECT operator returns only distinct rows that are


common to both sets.

₋ In other words, if a row appears at least once in the first set


and at least once in the second set, it will appear once in
the result of the INTERSECT operator.
T-SQL – Combining Tables - SET
OPERATORS

o EXCEPT

₋ The EXCEPT operator performs set difference. It


returns distinct rows that appear in the first query but
not the second.
UNION vs JOIN

o UNION
₋ used to concatenate result set from two queries
₋ Doesn’t create individual rows from column gathered from two
tables
o JOIN
₋ Compares column from two tables
₋ It creates result set /rows composed of columns from
two tables
SET OPERATORS Examples
o First lest prepare a table to be used in the examples

SELECT ProductModelID, Name


INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID between 1 AND 8;
Union

o Example
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
UNION
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
ORDER BY Name ;
UNION ALL

Example

USE [AdventureWorks2022];
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
UNION ALL
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
ORDER BY Name
INTERSET

o EXAMPLE
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
INTERSECT
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
ORDER BY Name
Except

o Example
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
EXCEPT
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
ORDER BY Name
Summary

Except

Set Operators
Set operators operate on two result sets of queries, comparing complete rows between the results. T-SQL supports three set
operators: UNION,INTERSECT, and EXCEPT; it also supports one multiset operator: UNION ALL
1. UNION and UNION ALL
The UNION set operator unifies the results of the two input queries. As a set operator, UNION has an implied DISTINCT
property, meaning that it does not return duplicate rows. UNION ALL returns duplicate rows too.

2. INTERSECT
The INTERSECT operator returns only distinct rows that are common to both sets. In other words, if a row appears at least once
in the first set and at least once in the second set, it will appear once in the result of the INTERSECT operator.

3. EXCEPT
The EXCEPT operator performs set difference. It returns distinct rows that appear in the first query but not the second.

T-SQL – Combining Tables -


More on T-SQL – Combining Tables - SET OPERATORS

• First lest prepare a table to be used in the examples


SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID between 1 AND 8;
• Let us look at Set Operators with Examples
1. Union
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
UNION
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
ORDER BY Name -- The result set contains 100 rows
2. Union All
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
UNION ALL
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
ORDER BY Name -- The result set contains 108 rows … the additional 8 rows are duplicates
3. Intersect
SELECT ProductModelID, Name, ProductModelID
FROM Production.ProductModel a
WHERE ProductModelID between 1 AND 100
INTERSECT
SELECT ProductModelID, Name, ProductModelID
FROM dbo.Gloves b
More on T-SQL – Combining Tables - Summary

JOINS

Set Operators
Except
The expert in everything
was once a beginner

Just begin practicing and you will become an expert

You might also like