DBA Session 3 SQL
DBA Session 3 SQL
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
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
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
o SQL Server Transact-SQL contains a huge list of CREATE/ALTER/DROP statements. CREATE Statements
USE AdventureWorks2012;
GO
GO
------- 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
CREATE TABLE
( { <column_definition> } [ ,...n ] )
[;]
o Below is a Simple example for Creating, Altering and Dropping a Tables
₋ Create Tables
USE [AdventureWorks2022]
(EmployeeID int PRIMARY KEY CLUSTERED, EmployeeName nvarchar (25), DOB date);
DDL –CREATE / ALTER/ DROP
TABLES
https://msdn.microsoft.com/en-us/library/ms190273.aspx )
NULL ;
https://msdn.microsoft.com/en-us/library/ms173790.aspx )
USE [AdventureWorks2022];
GO
AS
FROM HumanResources.Employee e
GO
DDL –CREATE / ALTER/ DROP VIEWS
o Alter View
ALTER VIEW hiredate_view ----what has changed?
AS
FROM HumanResources.Employee e
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
• A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server
• 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 ] }
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
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
• 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
• 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.
• 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
• 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
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‘
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
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.
• Whenever we use aggregate functions in a SELECT statement, we have to use a GROUP BY Clause to group the result set
• 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;
• 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());
_________________________________________________________________________________________________________________________________
• 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;
• 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
• For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based
on differences found in the other table
• 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:
• 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:
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.
• CROSS JOINS
• INNER JOINS
• OUTER JOINS
• SELF JOINS
➢ 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
₋ INTERSECT
₋ EXCEPT
T-SQL – Combining Tables - SET
OPERATORS
{ UNION [ ALL ]
{ <query_specification> |
( <query_expression> ) }
[ ...n ] }
T-SQL – Combining Tables - SET
OPERATORS
o INTERSECT
o EXCEPT
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
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.
JOINS
Set Operators
Except
The expert in everything
was once a beginner