132 - SQL
132 - SQL
T-SQL History
Note:
Select the Database Before Executing Query or write
Use Keyword + DB Name on top of the Query
Commenting T-SQL Code
/*
This is a comment
*/
--This is a comment
Batch
Recall that a batch is a series of one or more
statements submitted and executed at the
same time
Example:
delete sales
where stor_id = "5023"
and ord_num = "AB-123-DEF-425-1Z3"
delete salesdetail
where stor_id = "5023"
and ord_num = "AB-123-DEF-425-1Z3"
select * from sales
where stor_id = "5023"
select * from salesdetail
where stor_id = "5023"
go
Data Definition Language
Modifying Data in Tables
Create Table
Alter Table
Drop Table
Create Table
Syntax:
Example
CREATE TABLE Employee
(ID int Primary Key,
FName char(50) Not Null,
LName char(50),
Address char(50),
Birth_Date date);
Drop Table
Syntax:
Example
Drop Table Employee
Alter Table
Syntax:
ALTER TABLE table_name ADD column_name datatype
Example
ALTER TABLE employee ADD City varchar(30)
Modifying Data in Tables
Modifying Data in Tables
Inserting Data into Tables
Deleting Data from Tables
Updating Data in Tables
INSERT Fundamentals
INSERT Syntax:
INSERT [INTO] table_or_view [(column_list)] data_values
INSERT Statement Examples
Using a Simple INSERT Statement
INSERT INTO Production.UnitMeasure
VALUES (N'F2', N'Square Feet', GETDATE());
DELETE Syntax:
DELETE table_or_view
FROM table_sources
WHERE search_condition
DELETE Statement Definitions
UPDATE Syntax:
UPDATE table_or_view
SET column_name = expression
FROM table_sources
WHERE search_condition
UPDATE Statement Definitions
UPDATE Sales.SalesPerson
Simple UPDATE Statement SET Bonus = 6000;
UPDATE SomeTable
SET Column = Value
UPDATE Sales.SalesPerson
SET Bonus = Bonus * 2;
UPDATE Sales.SalesPerson
SET SalesYTD = SalesYTD + SubTotal
FROM Sales.SalesPerson AS sp
JOIN Sales.SalesOrderHeader AS so
ON sp.BusinessEntityID = so.SalesPersonID
AND so.OrderDate = (SELECT MAX(OrderDate)
FROM Sales.SalesOrderHeader
WHERE SalesPersonID =
sp.BusinessEntityID);
Before After
SalesYTD SalesYTD
-------------- --------------
677558.4653 721382.488
4557045.0459 4593234.5123
Data Query Language
SELECT Statement
26
Retrieving Columns in a Table
USE ITI;
GO
SELECT *
FROM Student
WHERE Age >20
USE ITI;
GO
SELECT *
FROM Instructor
WHERE Salary IS NULL;
Types of T-SQL Operators
Type Operators
• +, -, *, /, %
• Arithmetic operators
Vacation + SickLeave AS 'Total PTO'
• =
• Assignment operator
SET @MyCounter = 1
• String concatenation • +
SELECT LastName + ', ' + FirstName
operator AS Moniker
Using Comparison Operators
USE AdventureWorks2012;
GO
SELECT FirstName, LastName, MiddleName
FROM Person.Person
WHERE ModifiedDate >= ‘01/01/2004’
Using String Comparisons
➢ String Comparisons are used for data types of text, ntext, char,
nchar, varchar, and nvarchar
➢ Predicates are available for full or partial match comparisons
Returns only rows with first name of ‘John’ and last name of ‘Smith’
WHERE FirstName = ‘John’ AND LastName = ‘Smith’
Returns all rows with first name of ‘John’ and all rows with last name of
‘Smith’
WHERE FirstName = ‘John’ OR LastName = ‘Smith’
Returns all rows with first name of ‘John’ and last name not equal to
‘Smith’
WHERE FirstName = ‘John’ AND NOT LastName = ‘Smith’
Operator Precedence
~ (Bitwise Not)
Comparisons
=, >, <, >=, <=, <>, !=, !>, !<
NOT
AND
COALESCE() returns the first non NULL expression among its arguments,
similar to a CASE statement
SELECT CAST(COALESCE(hourly_wage * 40 * 52, salary,
commission * num_sales) AS money) AS 'Total Salary'
FROM wages
Formatting Result Sets
➢ Sorting Data
➢ Eliminating Duplicate Rows
➢ Labeling Columns in Result Sets
➢ Using String Literals
➢ Using Expressions
Sorting Data
➢ String Literals:
➢ Are constant values.
➢ Can be inserted into derived columns to format data.
➢ Can be used as alternate values in functions, such as the
ISNULL() function.
SELECT (LastName + ‘, ‘ + FirstName + ‘ ‘ +
ISNULL(SUBSTRING(MiddleName, 1, 1), ‘ ‘)) AS Name
FROM Person.Person
ORDER BY LastName, FirstName, MiddleName
Using Expressions
Joins:
✓• Can result in huge result sets that take several hours to complete!
Joining Tables by Using Non-Equi Joins
• The same Operators and Predicates used for Inner Joins can be used for
Not-Equal Joins
Result Set:
ProductSubcateogoryID ListPrice
-----------------------------------
23 8.99
23 9.50
...
(8 row(s) affected)
Equijoins and Non-Equijoins
Using Equal Operator not satisfy all join conditions.
• INTERSECT returns any distinct values that are returned by both the query on the left
and right sides of the INTERSECT operand
EXCEPT Example:
SELECT ProductID
FROM Production.Product
EXCEPT
SELECT ProductID
FROM Production.WorkOrder
INTERSECT Example:
SELECT ProductID
FROM Production.Product
INTERSECT
SELECT ProductID
FROM Production.WorkOrder
Order of Precedence of UNION, EXCEPT,
and INTERSECT
EXCEPT, INTERSECT, and UNION are evaluated in the context of the following
precedence:
1 Expressions in parentheses
Select name
from Employee
where Dno in
( select Dnumber from dept
where location=‘giza’)
Sub-Queries (Cont’d )
✓ 1- Highest Salary
✓ 2- Deptno for this Employee
✓ 3- Department name
Select name
From employee
Where Not Exists ( select * from dependent where ssn=Essn)
Exists Condition With DML
DELETE FROM suppliers
WHERE Not EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);
Aggregate Functions
COUNT , SUM , MAX, MIN and AVG
Grant Revoke
http://msdn.microsoft.com/en-us/library/bb264565.aspx