1 Introduction
1 Introduction
Query
OLTP
Results
OLAP
Client SQL Server
Authentication modes
Windows Authentication
Mixed Authentication
System DataBases
Master DataBase:
The master database records all the system-level information
for a SQL Server system. This includes instance-wide
metadata such as logon accounts . Also, master is the
database that records the existence of all other databases
and the location of those database files and records
model DataBase:
is used as the template for all databases created on an
instance of SQL Server
System DataBases
Msdb DataBase
is used by SQL Server Agent for scheduling alerts and jobs
and by other features
TembDB
is used by SQL Server Agent for saving Temporary user
objects that are explicitly created, such as: global or local
temporary tables, temporary stored procedures, table
variables, or cursors
Introduction to
Transact-SQL
The Transact-SQL Programming Language
In-line Comments
Example
Example 11
SELECT productname
SELECT productname
,, (unitsinstock
(unitsinstock -- unitsonorder)
unitsonorder) --
-- Calculates
Calculates inventory
inventory
,, supplierID
supplierID
FROM
FROM products
products
GO
GO
Block Comments
Example
Example 33
/*
/*
This
This code
code retrieves
retrieves all
all rows
rows of
of the
the products
products table
table
and
and displays
displays the
the unit
unit price,
price, the
the unit
unit price
price increased
increased
by
by 10
10 percent,
percent, and
and the
the name
name of
of the
the product.
product.
*/
*/
USE
USE northwind
northwind
SELECT
SELECT unitprice,
unitprice, (unitprice
(unitprice ** 1.1),
1.1), productname
productname
FROM
FROM products
products
GO
GO
Using the SELECT Statement
Partial Syntax
SELECT
SELECT [ALL
[ALL || DISTINCT]
DISTINCT] <select_list>
<select_list>
FROM
FROM {<table_source>}
{<table_source>} [,…n]
[,…n]
WHERE
WHERE <search_condition>
<search_condition>
Specifying Columns
USE
USE northwind
northwind
SELECT
SELECT employeeid,
employeeid, lastname,
lastname, firstname,
firstname, title
title
FROM
FROM employees
employees
GO
GO
employeeid
employeeid lastname
lastname firstname
firstname title
title
11 Davolio
Davolio Nancy
Nancy Sales
SalesRepresentative
Representative
22 Fuller
Fuller Andrew
Andrew Vice
VicePresident,
President,Sales
Sales
33 Leverling
Leverling Janet
Janet Sales
SalesRepresentative
Representative
44 Peacock
Peacock Margaret
Margaret Sales
SalesRepresentative
Representative
55 Buchanan
Buchanan Steven
Steven Sales
SalesManager
Manager
66 Suyama
Suyama Michael
Michael Sales
SalesRepresentative
Representative
77 King
King Robert
Robert Sales
SalesRepresentative
Representative
88 Callahan
Callahan Laura
Laura Inside
InsideSales
SalesCoordinator
Coordinator
99 Dodsworth
Dodsworth Anne
Anne Sales
SalesRepresentative
Representative
Using the WHERE Clause to Specify Rows
USE
USE northwind
northwind
SELECT
SELECT employeeid,
employeeid, lastname,
lastname, firstname,
firstname, title
title
FROM
FROM employees
employees
WHERE
WHERE employeeid
employeeid == 55
GO
GO
employeeid
employeeid lastname
lastname firstname
firstname title
title
55 Buchanan
Buchanan Steven
Steven Sales
SalesManager
Manager
Filtering Data
Example
Example 11
USE
USE northwind
northwind
SELECT
SELECT lastname,
lastname, city
city
FROM
FROM employees
employees
WHERE
WHERE country
country == 'USA'
'USA'
GO
GO
lastname
lastname city
city
Davolio
Davolio Seattle
Seattle
Fuller
Fuller Tacoma
Tacoma
Leverling
Leverling Kirkland
Kirkland
Peacock
Peacock Redmond
Redmond
Callahan
Callahan Seattle
Seattle
This example retrieves the orderid and customerid columns
with order dates that are older than 8/1/96 from the orders
table.
USE northwind
SELECT orderid, customerid
FROM orders
WHERE orderdate < ’8/1/96’
GO
Using String Comparisons
USE
USE northwind
northwind
SELECT
SELECT companyname
companyname
FROM
FROM customers
customers
WHERE
WHERE companyname
companyname LIKE
LIKE '%Restaurant%'
'%Restaurant%'
GO
GO
companyname
companyname
GROSELLA-Restaurante
GROSELLA-Restaurante
Lonesome
LonesomePine
PineRestaurant
Restaurant
Tortuga
TortugaRestaurante
Restaurante
Example
Example 11
USE
USE northwind
northwind
SELECT
SELECT productid,
productid, productname,
productname, supplierid,
supplierid, unitprice
unitprice
FROM
FROM products
products
WHERE
WHERE (productname
(productname LIKE
LIKE 'T%'
'T%' OR
OR productid
productid == 46)
46)
AND
AND (unitprice
(unitprice >> 16.00)
16.00)
GO
GO
productid
productid productname
productname supplierid
supplierid unitprice
unitprice
14
14 Tofu
Tofu 66 23.25
23.25
29
29 Thüringer
ThüringerRostbratwurst
Rostbratwurst 12
12 123.79
123.79
62
62 Tarte
Tarteau
ausucre
sucre 29
29 49.3
49.3
The following example retrieves products with product names that begin
with
the letter T or that have a product identification number of 46 and a price
greater than $16.00. Compare the query in Example 1 to that in Example 2.
Notice that because the expressions are grouped differently, the queries are
processed differently and return different result sets.
USE northwind
SELECT productid, productname, supplierid, unitprice
FROM products
WHERE (productname LIKE ’T%’)
OR (productid = 46 AND unitprice > 16.00)
Retrieving a Range of Values
Example
Example 11
USE
USE northwind
northwind
SELECT
SELECT productname,
productname, unitprice
unitprice
FROM
FROM products
products
WHERE
WHERE unitprice
unitprice BETWEEN
BETWEEN 10
10 AND
AND 20
20
GO
GO
productname
productname unitprice
unitprice
Chai
Chai 18
18
Chang
Chang 19
19
Aniseed
AniseedSyrup
Syrup 10
10
Genen
GenenShouyu
Shouyu 15.5
15.5
Pavlova
Pavlova 17.45
17.45
Sir
SirRodney’s
Rodney’sScones
Scones 10
10
…… ……
Using a List of Values as Search Criteria
Example
Example 11
USE
USE northwind
northwind
SELECT
SELECT companyname,
companyname, country
country
FROM
FROM suppliers
suppliers
WHERE
WHERE country
country IN
IN ('Japan',
('Japan', 'Italy')
'Italy')
GO
GO
companyname
companyname country
country
Tokyo
TokyoTraders
Traders Japan
Japan
Mayumi’s
Mayumi’s Japan
Japan
Formaggi
FormaggiFortini
Fortinis.r.l.
s.r.l. Italy
Italy
Pasta
PastaButtini
Buttinis.r.l.
s.r.l. Italy
Italy
Retrieving Unknown Values
USE
USE northwind
northwind
SELECT
SELECT companyname,
companyname, fax
fax
FROM
FROM suppliers
suppliers
WHERE
WHERE fax
fax IS
IS NULL
NULL
GO
GO
companyname
companyname fax
fax
Exotic
ExoticLiquids
Liquids NULL
NULL
New
NewOrleans
OrleansCajun
CajunDelights
Delights NULL
NULL
Tokyo
TokyoTraders
Traders NULL
NULL
Cooperativa
CooperativadedeQuesos
Quesos‘Las
‘LasCabras’
Cabras’ NULL
NULL
…… ……
Formatting Result Sets
Sorting Data
Eliminating Duplicate Rows
Changing Column Names
Using Literals
Sorting Data
Example
Example 11
USE
USE northwind
northwind
SELECT
SELECT productid,
productid, productname,
productname, categoryid,
categoryid, unitprice
unitprice
FROM
FROM products
products
ORDER
ORDER BY
BY categoryid,
categoryid, unitprice
unitprice DESC
DESC
GO
GO
productid
productid productname
productname categoryid
categoryid unitprice
unitprice
38
38 Cote
Cotede
deBlaye
Blaye 11 263.5000
263.5000
43
43 Ipoh
IpohCoffee
Coffee 11 46.0000
46.0000
22 Chang
Chang 11 19.0000
19.0000
…… …… …… ……
63
63 Vegie-spread
Vegie-spread 22 43.9000
43.9000
88 Northwoods
NorthwoodsCranberry
CranberrySauce
Sauce 22 40.0000
40.0000
61
61 Sirop
Siropd'érable
d'érable 22 28.5000
28.5000
…… …… …… ……
Eliminating Duplicate Rows
country
country
Australia
Australia
Brazil
Brazil
Example
Example 11 Canada
Canada
USE
USE northwind
northwind Denmark
Denmark
SELECT
SELECT DISTINCT
DISTINCT country
country Finland
Finland
FROM
FROM suppliers
suppliers France
France
ORDER
ORDER BY
BY country
country Germany
Germany
GO
GO Italy
Italy
Japan
Japan
Netherlands
Netherlands
Norway
Norway
Singapore
Singapore
Spain
Spain
Sweden
Sweden
UK
UK
USA
USA
Changing Column Names
USE
USE northwind
northwind
SELECT
SELECT firstname
firstname AS
AS First,
First, lastname
lastname AS
AS Last
Last
,employeeid
,employeeid AS
AS 'Employee
'Employee ID:'
ID:'
FROM
FROM employees
employees
GO
GO
First
First Last
Last Employee
EmployeeID:
ID:
Nancy
Nancy Davolio
Davolio 11
Andrew
Andrew Fuller
Fuller 22
Janet
Janet Leverling
Leverling 33
Margaret
Margaret Peacock
Peacock 44
Steven
Steven Buchanan
Buchanan 55
Michael
Michael Suyama
Suyama 66
Robert
Robert King
King 77
Laura
Laura Callahan
Callahan 88
Anne
Anne Dodsworth
Dodsworth 99
Using Literals
USE
USE northwind
northwind
SELECT
SELECT firstname,
firstname, lastname
lastname
,'Identification
,'Identification number:',
number:', employeeid
employeeid
FROM
FROM employees
employees
GO
GO
First
First Last
Last Employee
EmployeeID:
ID:
Nancy
Nancy Davolio
Davolio Identification
IdentificationNumber:
Number: 11
Andrew
Andrew Fuller
Fuller Identification
IdentificationNumber:
Number: 22
Janet
Janet Leverling
Leverling Identification
IdentificationNumber:
Number: 33
Margaret
Margaret Peacock
Peacock Identification
IdentificationNumber:
Number: 44
Steven
Steven Buchanan
Buchanan Identification
IdentificationNumber:
Number: 55
Michael
Michael Suyama
Suyama Identification
IdentificationNumber:
Number: 66
Robert
Robert King
King Identification
IdentificationNumber:
Number: 77
Laura
Laura Callahan
Callahan Identification
IdentificationNumber:
Number: 88
Anne
Anne Dodsworth
Dodsworth Identification
IdentificationNumber:
Number: 99
Grouping and Summarizing
Data
Listing the TOP n Values
Example
Example 11
USE
USE northwind
northwind
SELECT
SELECT TOP
TOP 55 orderid,
orderid, productid,
productid, quantity
quantity
FROM
FROM [order
[order details]
details]
ORDER
ORDER BY
BY quantity
quantity DESC
DESC
GO
GO
Example 2
Example 2
USE
USE northwind
northwind
SELECT
SELECT TOP
TOP 55 WITH
WITH TIES
TIES orderid,
orderid, productid,
productid, quantity
quantity
FROM
FROM [order
[order details]
details]
ORDER
ORDER BY
BY quantity
quantity DESC
DESC
GO
GO
Using the GROUP BY Clause
USE northwind USE northwind
SELECT productid, orderid SELECT productid
,quantity ,SUM(quantity) AS total_quantity
FROM orderhist FROM orderhist
GO GROUP BY productid
GO
productid
productid orderid
orderid quantity productid
quantity productid total_quantity
total_quantity
11 11 55 11 15
15
11 11 10
10 22 35
Only rows that 35
22 11 10
10 satisfy the WHERE 33 45
clause are grouped 45
22 22 25
25
productid
productid total_quantity
total_quantity
33 11 15
15
22 35
35
33 22 30
30
USE northwind
SELECT productid
,SUM(quantity) AS total_quantity
FROM orderhist
WHERE productid = 2
GROUP BY productid
GO
Using the GROUP BY Clause with the HAVING Clause
Example
Example 11
USE
USE northwind
northwind
Select
Select categoryname,productname
categoryname,productname
From
From categories
categories inner
inner join
join products
products
On
On categories.categoryid
categories.categoryid == products.categoryid
products.categoryid
GO
GO
Using Outer Joins
Example
Example 11
Select
Select companyname,orderdate
companyname,orderdate
From
From customers
customers left
left outer
outer join
join orders
orders
On
On customers.customerid
customers.customerid == orders.customerid
orders.customerid
GO
GO
Using Cross Joins
Example
Example 11
Select suppliers.companyname,shippers.companyname
From suppliers cross join shippers
Joining More Than Two Tables
Example
Example 11
Select
Select productname,orderdate
productname,orderdate
From
From products inner
products inner join
join [order
[order details]
details]
On
On products.productid=[order details]. productid
products.productid=[order details]. productid
Inner
Inner join
join orders
orders
On
On [order
[order details].orderid=
details].orderid= orders.orderid
orders.orderid
Where orderdate=‘7/8/96’
Where orderdate=‘7/8/96’
GO
GO
Joining a Table to Itself
Example
Example 33
Select mgr.empname,e.empname
From emp as mgr inner join emp as e
On mgr.empid= e.supervisor
Combining Multiple Result Sets
USE
USE northwind
northwind
SELECT
SELECT (firstname
(firstname ++ '' '' ++ lastname)
lastname) AS
AS name
name
,city,
,city, postalcode
postalcode
FROM
FROM employees
employees
UNION
UNION
SELECT
SELECT companyname,
companyname, city,
city, postalcode
postalcode
FROM
FROM customers
customers
GO
GO
Modifying Data
Inserting a Row of Data by Values
USE
USE northwind
northwind
INSERT
INSERT customers
customers
(customerid,
(customerid, companyname,
companyname, contactname,
contactname, contacttitle
contacttitle
,address,
,address, city,
city, region,
region, postalcode,
postalcode, country,
country, phone
phone
,fax)
,fax)
VALUES
VALUES ('PECOF',
('PECOF', 'Pecos
'Pecos Coffee
Coffee Company',
Company', 'Michael
'Michael Dunn'
Dunn'
,'Owner',
,'Owner', '1900
'1900 Oak
Oak Street',
Street', 'Vancouver',
'Vancouver', 'BC'
'BC'
,'V3F
,'V3F 2K1',
2K1', 'Canada',
'Canada', '(604)
'(604) 555-3392'
555-3392'
,'(604)
,'(604) 555-7293')
555-7293')
GO
GO
Inserting a Row of Data by Values
USE
USE northwind
northwind
INSERT
INSERT customers
customers
(customerid,
(customerid, companyname,
companyname, contactname,
contactname, contacttitle
contacttitle
,address,
,address, city,
city, region,
region, postalcode,
postalcode, country,
country, phone
phone
,fax)
,fax)
VALUES
VALUES ('PECOF',
('PECOF', 'Pecos
'Pecos Coffee
Coffee Company',
Company', 'Michael
'Michael Dunn'
Dunn'
,'Owner',
,'Owner', '1900
'1900 Oak
Oak Street',
Street', 'Vancouver',
'Vancouver', 'BC'
'BC'
,'V3F
,'V3F 2K1',
2K1', 'Canada',
'Canada', '(604)
'(604) 555-3392'
555-3392'
,'(604)
,'(604) 555-7293')
555-7293')
GO
GO
Using the INSERT…SELECT Statement
USE
USE northwind
northwind
INSERT
INSERT customers
customers
SELECT
SELECT substring(firstname,
substring(firstname, 1,
1, 3)
3)
++ substring
substring (lastname,
(lastname, 1,
1, 2)
2)
,lastname,
,lastname, firstname,
firstname, title,
title, address,
address, city
city
,region,
,region, postalcode,
postalcode, country,
country, homephone,
homephone, NULL
NULL
FROM
FROM employees
employees
GO
GO
Creating a Table Using the SELECT INTO Statement
USE
USE northwind
northwind
SELECT
SELECT productname
productname AS
AS products
products
,unitprice
,unitprice AS
AS price
price
,(unitprice
,(unitprice ** 1.1)
1.1) AS
AS tax
tax
INTO
INTO #pricetable
#pricetable
FROM
FROM products
products
GO
GO
Using the DELETE Statement
USE
USE northwind
northwind
delete
delete emp
emp where
where empname=‘heba’
empname=‘heba’
GO
GO
Deleting Rows Based on Other Tables
USE
USE northwind
northwind
UPDATE
UPDATE products
products
SET
SET unitprice
unitprice == (unitprice
(unitprice ** 1.1)
1.1)
GO
GO
Updating Rows Based on Other Tables
update products
set unitprice =unitprice+2
from products inner join suppliers
on products.supplierid=suppliers.supplierid
where country='usa'
Ex: Create Database
Data
Datamodification
modificationisis
1 sent
sentby
byapplication
application
Modification
Modificationisisrecorded
recorded
3 inintransaction
Buffer transactionlog
logon
ondisk
disk
Cache
Disk
Data
Datapages
pagesare
arelocated
locatedin,
in, Disk
2 or
orread
readinto,
into,buffer
buffercache
cache
and
andmodified
modified
Checkpoint
Checkpointwrites
writes
4 committed
committedtransactions
transactions
totodatabase
database
(
name='test_sec',
filename='d:\test.ndf',
size=10mb,
filegrowth=10%,
maxsize=40mb
)
log on
(
name='test_log',
filename='d:\test.ldf',
size=10mb,
filegrowth=10%,
maxsize=40mb
)
Creating Filegroups
)
log on
(
name='test_log',
filename='d:\test.ldf',
size=10mb,
filegrowth=10%,
maxsize=40mb
)
Adding Objects To File Groups
Person
Contact
(Server1.AdventureWorks.Person.Contact)
Sales
Customer
(Server1.AdventureWorks.Sales.Customer)
dbo
ErrorLog AdventureWorks
(Server1.AdventureWorks.dbo.ErrorLog)
Advantage of schema
Person
SELECT * FROM Contact
Lance
(Default schema = Person)
Contact
ErrorLog
What Are System-Supplied Data Types?