Download presentation
Presentation is loading. Please wait.
Published byPeregrine Howard Modified over 9 years ago
1
Best Practices Transact-SQL
2
Transact-SQL Syntax Elements Batch Directives Comments Identifiers Types of Data Variables System Functions Operators Expressions Control-of-Flow Language Elements Reserved Keywords
3
Batch Directives GO Delineates batches of Transact-SQL statements to tools and utilities Is not an actual Transact-SQL statement EXEC Executes a user-defined function, system procedure, user-defined stored procedure, or an extended stored procedure Controls the execution of a character string within a Transact-SQL batch
4
Comments In-line Comments Block Comments SELECT productname, (unitsinstock - unitsonorder) -- Calculates inventory, supplierID FROM products GO SELECT productname, (unitsinstock - unitsonorder) -- Calculates inventory, supplierID FROM products GO /* This code retrieves all rows of the products table and displays the unit price, the unit price increased by 10 percent, and the name of the product. */ USE northwind SELECT unitprice, (unitprice * 1.1), productname FROM products GO /* This code retrieves all rows of the products table and displays the unit price, the unit price increased by 10 percent, and the name of the product. */ USE northwind SELECT unitprice, (unitprice * 1.1), productname FROM products GO Example 3 Example 1
5
Identifiers Standard Identifiers First character must be alphabetic Other characters can include letters, numerals, or symbols Identifiers starting with symbols have special uses Delimited Identifiers Use when names contain embedded spaces Use when reserved words are portions of names Enclose in brackets ([ ]) or quotation marks (" ")
6
Naming Guidelines for Identifiers Keep Names Short Use Meaningful Names Where Possible Use Clear and Simple Naming Conventions Use an Identifier That Distinguishes Types of Object Views Stored procedures Keep Object Names and User Names Unique Sales table and sales role
7
Types of Data Numbers Dates Characters Binary Unique Identifiers (GUID) SQL Variants Image and Text Table Cursor User-defined
8
Variables User-defined with DECLARE @ Statement Assigned Values with SET or SELECT @ Statement Variables Have Local Scope USE northwind DECLARE @EmpID varchar(11),@vlName char(20) SET @vlname = 'Dodsworth' SELECT @EmpID = employeeid FROM employees WHERE LastName = @vlname SELECT @EmpID AS EmployeeID GO USE northwind DECLARE @EmpID varchar(11),@vlName char(20) SET @vlname = 'Dodsworth' SELECT @EmpID = employeeid FROM employees WHERE LastName = @vlname SELECT @EmpID AS EmployeeID GO
9
System Functions Aggregate Functions Scalar Functions Rowset Functions SELECT * FROM OPENQUERY (OracleSvr, 'SELECT name, id FROM owner.titles') USE northwind SELECT AVG (unitprice) AS AvgPrice FROM products GO USE northwind SELECT AVG (unitprice) AS AvgPrice FROM products GO USE northwind SELECT DB_NAME() AS 'database‘ GO USE northwind SELECT DB_NAME() AS 'database‘ GO
10
System Function Examples SELECT 'ANSI:', CONVERT(varchar(30), GETDATE(), 102) AS Style UNION SELECT 'Japanese:', CONVERT(varchar(30), GETDATE(), 111) UNION SELECT 'European:', CONVERT(varchar(30), GETDATE(), 113) GO SELECT 'ANSI:', CONVERT(varchar(30), GETDATE(), 102) AS Style UNION SELECT 'Japanese:', CONVERT(varchar(30), GETDATE(), 111) UNION SELECT 'European:', CONVERT(varchar(30), GETDATE(), 113) GO Result StyleStyle ANSI: Japanese: European: 1998.03.19 1998/03/19 19 Mar 1998 16:34:40:616 Example 1
11
Operators Types of Operators Arithmetic Comparison String concatenation Logical Operator Precedence Levels
12
Expressions Combination of Symbols and Operators Evaluation to Single Scalar Value Result Data Type Dependent on the Elements Within the Expression USE northwind SELECT OrderID, ProductID,(UnitPrice * Quantity) as ExtendedAmount FROM [Order Details] WHERE (UnitPrice * Quantity) > 10000 GO USE northwind SELECT OrderID, ProductID,(UnitPrice * Quantity) as ExtendedAmount FROM [Order Details] WHERE (UnitPrice * Quantity) > 10000 GO
13
Control-of-Flow Language Elements Statement Level BEGIN … END block IF … ELSE block WHILE constructs Row Level CASE function DECLARE @n tinyint SET @n = 5 IF (@n BETWEEN 4 and 6) BEGIN WHILE (@n > 0) BEGIN SELECT @n AS 'Number',CASE WHEN (@n % 2) = 1 THEN 'EVEN' ELSE 'ODD' END AS 'Type' SET @n = @n - 1 END ELSE PRINT 'NO ANALYSIS‘ GO DECLARE @n tinyint SET @n = 5 IF (@n BETWEEN 4 and 6) BEGIN WHILE (@n > 0) BEGIN SELECT @n AS 'Number',CASE WHEN (@n % 2) = 1 THEN 'EVEN' ELSE 'ODD' END AS 'Type' SET @n = @n - 1 END ELSE PRINT 'NO ANALYSIS‘ GO Example 2
14
Reserved Keywords Identifier Names That Have Special Meaning Transact-SQL keywords ANSI SQL-92 keywords ODBC reserved keywords Do Not Use Reserved Keywords for Identifier Names
15
Retrieving Data by Using the SELECT Statement Using the SELECT Statement Specifying Columns Using the WHERE Clause to Specify Rows
16
SELECT [ALL | DISTINCT] FROM { } [,…n] WHERE Partial Syntax Using the SELECT Statement Select List Specifies the Columns WHERE Clause Specifies the Condition Restricting the Query FROM Clause Specifies the Table
17
Specifying Columnsemployeeidemployeeidlastnamelastnamefirstnamefirstnametitletitle 1 1 Davolio Nancy Sales Representative 2 2 Fuller Andrew Vice President, Sales 3 3 Leverling Janet Sales Representative 4 4 Peacock Margaret Sales Representative 5 5 Buchanan Steven Sales Manager 6 6 Suyama Michael Sales Representative 7 7 King Robert Sales Representative 8 8 Callahan Laura Inside Sales Coordinator 9 9 Dodsworth Anne Sales Representative USE northwind SELECT employeeid, lastname, firstname, title FROM employees GO USE northwind SELECT employeeid, lastname, firstname, title FROM employees GO
18
Using the WHERE Clause to Specify Rows employeeidemployeeidlastnamelastnamefirstnamefirstnametitletitle 5 5 Buchanan Steven Sales Manager USE northwind SELECT employeeid, lastname, firstname, title FROM employees WHERE employeeid = 5 GO USE northwind SELECT employeeid, lastname, firstname, title FROM employees WHERE employeeid = 5 GO
19
Filtering Data Using Comparison Operators Using String Comparisons Using Logical Operators Retrieving a Range of Values Using a List of Values as Search Criteria Retrieving Unknown Values
20
Using Comparison Operators USE northwind SELECT lastname, city FROM employees WHERE country = 'USA' GO USE northwind SELECT lastname, city FROM employees WHERE country = 'USA' GOlastnamelastnamecitycity Davolio Seattle Fuller Tacoma Leverling Kirkland Peacock Redmond Callahan Seattle Example 1
21
Using String Comparisons USE northwind SELECT companyname FROM customers WHERE companyname LIKE '%Restaurant%' GO USE northwind SELECT companyname FROM customers WHERE companyname LIKE '%Restaurant%' GOcompanynamecompanyname GROSELLA-Restaurante Lonesome Pine Restaurant Tortuga Restaurante
22
Using Logical Operators USE northwind SELECT productid, productname, supplierid, unitprice FROM products WHERE (productname LIKE 'T%' OR productid = 46) AND (unitprice > 16.00) GO USE northwind SELECT productid, productname, supplierid, unitprice FROM products WHERE (productname LIKE 'T%' OR productid = 46) AND (unitprice > 16.00) GOproductidproductidproductnameproductnamesupplieridsupplieridunitpriceunitprice 14 Tofu 6 6 23.25 29 Thüringer Rostbratwurst 12 123.79 62 Tarte au sucre 29 49.3 Example 1
23
Retrieving a Range of Values USE northwind SELECT productname, unitprice FROM products WHERE unitprice BETWEEN 10 AND 20 GO USE northwind SELECT productname, unitprice FROM products WHERE unitprice BETWEEN 10 AND 20 GOproductnameproductnameunitpriceunitprice Chai 18 Chang 19 Aniseed Syrup 10 Genen Shouyu 15.5 Pavlova 17.45 Sir Rodney’s Scones 10 … … … … Example 1
24
USE northwind SELECT companyname, country FROM suppliers WHERE country IN ('Japan', 'Italy') GO USE northwind SELECT companyname, country FROM suppliers WHERE country IN ('Japan', 'Italy') GO Using a List of Values as Search Criteriacompanynamecompanynamecountrycountry Tokyo Traders Japan Mayumi’s Japan Formaggi Fortini s.r.l. Italy Pasta Buttini s.r.l. Italy Example 1
25
Retrieving Unknown Values USE northwind SELECT companyname, fax FROM suppliers WHERE fax IS NULL GO USE northwind SELECT companyname, fax FROM suppliers WHERE fax IS NULL GO companynamecompanynamefaxfax Exotic Liquids NULL New Orleans Cajun Delights NULL Tokyo Traders NULL Cooperativa de Quesos ‘Las Cabras’ NULL … … … …
26
Formatting Result Sets Sorting Data Eliminating Duplicate Rows Changing Column Names Using Literals
27
Sorting Data USE northwind SELECT productid, productname, categoryid, unitprice FROM products ORDER BY categoryid, unitprice DESC GO USE northwind SELECT productid, productname, categoryid, unitprice FROM products ORDER BY categoryid, unitprice DESC GOproductidproductidproductnameproductnamecategoryidcategoryidunitpriceunitprice 38 Cote de Blaye 1 1 263.5000 43 Ipoh Coffee 1 1 46.0000 2 2 Chang 1 1 19.0000 … … … … … … … … 63 Vegie-spread 2 2 43.9000 8 8 Northwoods Cranberry Sauce 2 2 40.0000 61 Sirop d'érable 2 2 28.5000 … … … … … … … … Example 1
28
Eliminating Duplicate Rows USE northwind SELECT DISTINCT country FROM suppliers ORDER BY country GO USE northwind SELECT DISTINCT country FROM suppliers ORDER BY country GOcountrycountry Australia Brazil Canada Denmark Finland France Germany Italy Japan Netherlands Norway Singapore Spain Sweden UK USA Example 1
29
Changing Column Names USE northwind SELECT firstname AS First, lastname AS Last,employeeid AS 'Employee ID:' FROM employees GO USE northwind SELECT firstname AS First, lastname AS Last,employeeid AS 'Employee ID:' FROM employees GOFirstFirstLastLast Employee ID: Nancy Davolio 1 1 Andrew Fuller 2 2 Janet Leverling 3 3 Margaret Peacock 4 4 Steven Buchanan 5 5 Michael Suyama 6 6 Robert King 7 7 Laura Callahan 8 8 Anne Dodsworth 9 9
30
Using Literals USE northwind SELECT firstname, lastname,'Identification number:', employeeid FROM employees GO USE northwind SELECT firstname, lastname,'Identification number:', employeeid FROM employees GOFirstFirstLastLast Employee ID: Nancy Davolio Identification Number: 1 Andrew Fuller Janet Leverling Margaret Peacock Steven Buchanan Michael Suyama Robert King Laura Callahan Anne Dodsworth Identification Number: 2 Identification Number: 3 Identification Number: 4 Identification Number: 5 Identification Number: 6 Identification Number: 7 Identification Number: 8 Identification Number: 9
31
How Queries Are Processed Uncached Queries (Ad Hoc) Cached Queries Execute Compile Optimize Resolve Parse First Execution Execute Compile Optimize Resolve Parse Subsequent Execution Execute Procedure Cache Procedure Cache
32
Performance Considerations Not Search Conditions May Slow Data Retrieval LIKE Search Conditions Slow Data Retrieval Exact Matches or Ranges May Speed Data Retrieval ORDER BY Clause May Slow Data Retrieval
33
Listing the TOP n Values Lists Only the First n Rows of a Result Set Specifies the Range of Values in the ORDER BY Clause Returns Ties if WITH TIES Is Used USE northwind SELECT TOP 5 orderid, productid, quantity FROM [order details] ORDER BY quantity DESC GO USE northwind SELECT TOP 5 orderid, productid, quantity FROM [order details] ORDER BY quantity DESC GO USE northwind SELECT TOP 5 WITH TIES orderid, productid, quantity FROM [order details] ORDER BY quantity DESC GO USE northwind SELECT TOP 5 WITH TIES orderid, productid, quantity FROM [order details] ORDER BY quantity DESC GO Example 1 Example 2
34
Using Aggregate Functions Aggregate function DescriptionDescription AVG Average of values in a numeric expression COUNT Number of values in an expression COUNT (*) Number of selected rows MAX Highest value in the expression MIN Lowest value in the expression SUM Total values in a numeric expression STDEV Statistical deviation of all values STDEVP Statistical deviation for the population VAR Statistical variance of all values VARP Statistical variance of all values for the population
35
Using Aggregate Functions with Null Values Most Aggregate Functions Ignore Null Values COUNT(*) Function Counts Rows with Null Values USE northwind SELECT COUNT (*) FROM employees GO USE northwind SELECT COUNT (*) FROM employees GO USE northwind SELECT COUNT(reportsto) FROM employees GO USE northwind SELECT COUNT(reportsto) FROM employees GO Example 1 Example 2
36
GROUP BY Fundamentals Using the GROUP BY Clause Using the GROUP BY Clause with the HAVING Clause
37
Using the GROUP BY Clause USE northwind SELECT productid, orderid,quantity FROM orderhist GO USE northwind SELECT productid, orderid,quantity FROM orderhist GO USE northwind SELECT productid,SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid GO USE northwind SELECT productid,SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid GOproductidproductidtotal_quantitytotal_quantity 1 1 15 2 2 35 3 3 45 productidproductidorderidorderidquantityquantity 1 1 1 1 5 5 1 1 1 1 10 2 2 1 1 2 2 2 2 25 3 3 1 1 15 3 3 2 2 30 productidproductidtotal_quantitytotal_quantity 2 2 35 Only rows that satisfy the WHERE clause are grouped USE northwind SELECT productid,SUM(quantity) AS total_quantity FROM orderhist WHERE productid = 2 GROUP BY productid GO USE northwind SELECT productid,SUM(quantity) AS total_quantity FROM orderhist WHERE productid = 2 GROUP BY productid GO
38
Using the GROUP BY Clause with the HAVING Clause USE northwind SELECT productid, orderid,quantity FROM orderhist GO USE northwind SELECT productid, orderid,quantity FROM orderhist GO USE northwind SELECT productid, SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid HAVING SUM(quantity)>=30 GO USE northwind SELECT productid, SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid HAVING SUM(quantity)>=30 GOproductidproductidtotal_quantitytotal_quantity 2 2 35 3 3 45 productidproductidorderidorderidquantityquantity 1 1 1 1 5 5 1 1 1 1 10 2 2 1 1 2 2 2 2 25 3 3 1 1 15 3 3 2 2 30
39
Generating Aggregate Values Within Result Sets Using the GROUP BY Clause with the ROLLUP Operator Using the GROUP BY Clause with the CUBE Operator Using the GROUPING Function
40
Description Using the GROUP BY Clause with the ROLLUP Operator USE northwind SELECT productid, orderid, SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid, orderid WITH ROLLUP ORDER BY productid, orderid GO USE northwind SELECT productid, orderid, SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid, orderid WITH ROLLUP ORDER BY productid, orderid GOproductidproductidorderidorderidtotal_quantitytotal_quantity NULL 95 1 1 NULL 15 1 1 1 1 5 5 1 1 2 2 10 2 2 NULL 35 2 2 1 1 10 2 2 2 2 25 3 3 NULL 45 3 3 1 1 15 3 3 2 2 30 Grand total Summarizes only rows for productid 1 Detail value for productid 1, orderid 1 Detail value for productid 1, orderid 2 Summarizes only rows for productid 2 Detail value for productid 2, orderid 1 Summarizes only rows for productid 3 Detail value for productid 3, orderid 1 Detail value for productid 3, orderid 2
41
Using the GROUP BY Clause with the CUBE Operator The CUBE operator produces two more summary values than the ROLLUP operator USE northwind SELECT productid, orderid, SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid, orderid WITH CUBE ORDER BY productid, orderid GO USE northwind SELECT productid, orderid, SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid, orderid WITH CUBE ORDER BY productid, orderid GO Description Grand total Summarizes all rows for orderid 1 Summarizes all rows for orderid 2 Summarizes only rows for productid 1 Detail value for productid 1, orderid 1 Detail value for productid 1, orderid 2 Summarizes only rows for productid 2 Detail value for productid 2, orderid 1 Detail value for productid 2, orderid 2 Summarizes only rows for productid 3 Detail value for productid 3, orderid 1 Detail value for productid 3, orderid 2 productidproductidorderidorderidtotal_quantitytotal_quantity NULL 95 NULL 1 1 30 NULL 2 2 65 1 1 NULL 15 1 1 1 1 5 5 1 1 2 2 10 2 2 NULL 35 2 2 1 1 10 2 2 2 2 25 3 3 NULL 45 3 3 1 1 15 3 3 2 2 30
42
1 represents summary values in the preceding column 0 represents detail values in the preceding column 95 30 65 15 5 10 35 10 25 45 15 30 Using the GROUPING Function SELECT productid, GROUPING (productid),orderid, GROUPING (orderid),SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid, orderid WITH CUBE ORDER BY productid, orderid GO SELECT productid, GROUPING (productid),orderid, GROUPING (orderid),SUM(quantity) AS total_quantity FROM orderhist GROUP BY productid, orderid WITH CUBE ORDER BY productid, orderid GO productid NULL 1 1 1 2 2 2 3 3 3 1 1 1 0 0 0 0 0 0 0 0 0 orderid 1 2 1 2 1 2 1 2 1 0 0 1 0 0 1 0 0 1 0 0 total_quantity
43
Using the COMPUTE and COMPUTE BY Clauses COMPUTE BYCOMPUTE USE northwind SELECT productid, orderid, quantity FROM orderhist ORDER BY productid, orderid COMPUTE SUM(quantity) BY productid COMPUTE SUM(quantity) GO USE northwind SELECT productid, orderid, quantity FROM orderhist ORDER BY productid, orderid COMPUTE SUM(quantity) BY productid COMPUTE SUM(quantity) GO USE northwind SELECT productid, orderid,quantity FROM orderhist ORDER BY productid, orderid COMPUTE SUM(quantity) GO USE northwind SELECT productid, orderid,quantity FROM orderhist ORDER BY productid, orderid COMPUTE SUM(quantity) GOproductidproductidorderidorderidquantityquantity 1 1 1 1 5 5 1 1 2 2 10 2 2 1 1 2 2 2 2 25 3 3 1 1 15 3 3 2 2 30 sum 95 productidproductidorderidorderidquantityquantity 1 1 1 1 5 5 1 1 2 2 10 sum 15 2 2 1 1 10 2 2 2 2 25 sum 35 3 3 1 1 15 3 3 2 2 30 sum 45 sum 95
44
Using Aliases for Table Names Example 1 (without an alias name) Example 2 (with an alias name) USE joindb SELECT buyer_name, s.buyer_id, qty FROM buyers AS b INNER JOIN sales AS s ON b.buyer_id = s.buyer_id GO USE joindb SELECT buyer_name, s.buyer_id, qty FROM buyers AS b INNER JOIN sales AS s ON b.buyer_id = s.buyer_id GO USE joindb SELECT buyer_name, sales.buyer_id, qty FROM buyers INNER JOIN sales ON buyers.buyer_id = sales.buyer_id GO USE joindb SELECT buyer_name, sales.buyer_id, qty FROM buyers INNER JOIN sales ON buyers.buyer_id = sales.buyer_id GO
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.