SQL302 Intermediate SQL
Upcoming SlideShare
Loading in...5
×
 

SQL302 Intermediate SQL

on

  • 485 views

SQL302 Intermediate SQL using Microsoft SQL Server. Covers additional uses of subqueries, set functions, table expressions, with clause, new SQL window functions.

SQL302 Intermediate SQL using Microsoft SQL Server. Covers additional uses of subqueries, set functions, table expressions, with clause, new SQL window functions.

Statistics

Views

Total Views
485
Views on SlideShare
485
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

SQL302 Intermediate SQL SQL302 Intermediate SQL Document Transcript

  • Orange Coast Database Associates Course PowerPoint Slides (800)355-9855 or http://www.dhdursoassociates.com SQL302 Intermediate SQL Using Microsoft SQL Server Orange Coast Database Associates Specializing in Microsoft Office, Access, SQL, and related technologies Classes custom designed for Working Professionals http://www.dhdursoassociates.com San Juan Capistrano, CA (800)355-9855Accelerated Computer Training for Working Professionals Bookstore Case
  • Welcome to SQL302 – Intermediate SQL Using MS SQL Server An accelerated course in intermediate SQL for experienced SQL users. P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.comBookstore SQL302 1 Intermediate SQL • Introduction (s) • Facilities • Course Packet (contents may vary) – Student questionnaire – Collaterals (Maps, Catalogs, Etc.) – PowerPoint handouts for all sessions – Evaluation form – Training certificateBookstore SQL302 2 1
  • SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2012. All rights reserved.Bookstore2 SQL302 Module 2 3 SQL302 Resources• Bookstore database scripts found on box.com at http://tinyurl.com/SQLScripts• Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases• Follow up questions? sql.support@dhdursoassociates.comBookstore SQL302 Module 1 4 2
  • About Us 5 Intermediate SQL Curriculum SQL322W SQL302 SQL312 MySQL** Transact-SQL Oracle** •*= first day only •**=under SQL3xxS* developmentBookstore SQL302 6 3
  • Intermediate SQL• Assumes prior knowledge of SQL equivalent to SQL202.• Quick pace for experienced computer users• End-user, not programmer, oriented• Focus is on SQL, not Management Studio• SQL302s is first two modules of SQL302.Bookstore SQL302 7 Intermediate SQL SQL Covered (Day 1: All Day): • Select – More filters & operators – Case, cast, convert – Subqueries – Table expressions – Joins – Set operations – Window functionsBookstore SQL302 8 4
  • Intermediate SQL SQL Covered (Day 2: AM Only): • Data Updates – Select into – Update from, using subqueries – Delete from • Data structures – Alter – Synonyms – ViewsBookstore SQL302 9 Intermediate SQL Course Format: • 3 Sessions • Lecture • Demo • Student “hands-on” • Many exercises are cumulative – later examples build on queries created earlierBookstore SQL302 10 5
  • Intermediate SQL Course Schedule (“1/2” day sessions): • Session 1 – Intermediate SQL • Session 2 – Multi-table Retrieval • Session 3 – Modifying data and data structuresBookstore SQL302 11 NotesBookstore SQL302 12 6
  • SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server2008 T-SQL Fundamentals by Itzik Ben-gan Module 1 – Relational Database Background, CASE, Cast & Convert, Subqueries, Table ExpressionsBookstore SQL302 Module 1 1 Note on SQL302 Slides • Many of these slides were originally designed to support a single SQL course which was used for any of MS Access, MySQL, Oracle and SQL Server. • As such you may see here slides developed in any one of the above products. • We are in the process of migrating the vendor specific slides out into their own slide sets.Bookstore2 SQL302 Module 2 2 1
  • Warning!• Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. New Name Old Name Orders Order_filled Order_Lines OrderlinesBookstore2 SQL302 Module 2 3 SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2012. All rights reserved.Bookstore2 SQL302 Module 2 4 2
  • SQL302 Resources• Bookstore database scripts found on box.com at http://tinyurl.com/SQLScripts• Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases• Follow up questions? sql.support@dhdursoassociates.comBookstore SQL302 Module 1 5 SQL Programming• Course focus is SQL language• Widely used for: – Database administration – Enterprise application development – Data driven web sites• A foundation skill for eBusiness and almost all major business applications that use relational databasesBookstore SQL302 Module 1 6 3
  • SQL302• Students should have taken SQL202 or have equivalent experience. It is assumed students know basic SQL.• We will use the Management Studio in this class, but the focus will be on SQL scriptingBookstore SQL302 Module 1 7 Relational Database Evolution• Based on Codd’s paper• Early commercial efforts focused on Unix• First mainframe implementation by IBM - precursor to today’s DB2• First PC implementation in early 80’s by OracleBookstore SQL302 Module 1 8 4
  • Relational Database Basics• Storage • Indexes• Databases • Views• Tables • Cursors• Rows • Application interfaces• ColumnsBookstore SQL302 Module 1 9 Relational Database TableBookstore SQL302 Module 1 10 5
  • Constraints• Database • Other Business Rule – Domain – Triggers – Uniqueness – Stored Procedures – Relationship Cardinality • 1 to 1 • 1 to NBookstore SQL302 Module 1 11 Relational Database with constraintsBookstore SQL302 Module 1 12 6
  • Database Management Systems Positioning Chart Cost VLDB Enterprise Workgroup Single user Spreadsheet # UsersBookstore SQL302 Module 1 13 System Architecture File Server Architecture Access MDB AccessBookstore SQL302 Module 1 14 7
  • System Architecture Client/Server Architecture Oracle SQL DB Visual Access Basic AppBookstore SQL302 Module 1 15 System Architecture Web Architecture Web Oracle Server DB SQL BrowserBookstore SQL302 Module 1 16 8
  • Approaching SQL• Relatively simple• Two main environments – Interactive (This course) – Embedded • Static (Compiled) • DynamicBookstore SQL302 Module 1 17 SQL StandardizationANSI standardization – First standard in 1986 – SQL 89 – SQL 92 – SQL 99• Various vendor extensions – Microsoft/Sybase: T-SQL – Oracle: PL/SQLBookstore SQL302 Module 1 18 9
  • SQL Conformance• Entry• Intermediate• Advanced• Most are at least entry levelBookstore SQL302 Module 1 19 SQL Statements• Data Manipulation Language (DML)• Data Control Language (DCL)• Data Definition Language (DDL)• Note: SQL 99 changes these to seven types including DQL Data Query LanguageBookstore SQL302 Module 1 20 10
  • SQL DDL• Data definition language (DDL) – Create, alter, drop, etc. – Frequently implemented via various CASE tools: Visio, Embarcadero, ERWin, etc. – But very useful for database administrationBookstore SQL302 Module 1 21 SQL DCL• Data Control Language (DDL) – Grant – Revoke – Deny – ConstraintsBookstore SQL302 Module 1 22 11
  • SQL DQL• Data Manipulation Language (DML) – SelectBookstore SQL302 Module 1 23 SQL DML• Data Manipulation Language (DML) – Insert – Update – DeleteBookstore SQL302 Module 1 24 12
  • SQL Statement Processing Parse Validate Optimize Access Plan ExecuteBookstore SQL302 Module 1 25 Sample Database(s)• Before we continue (note: instructor may have already done this)…• Load the sample database(s) if not already loaded – Use supplied SQL Script (after class this script may be found on Box.com).Bookstore SQL302 Module 1 26 13
  • Text Conventions• In Access character strings are normally surrounded by double quotes – “Jones”• In an enterprise database such as Oracle or SQL Sever enclose text strings in single quotes – ‘Jones’Bookstore SQL302 Module 1 27 Date Conventions• In an enterprise database such as Oracle or SQL Sever, enclose dates in single quotes – ‘2004-12-23’ MySQL – ’12-23-2004’ SQL Server – ’23-DEC-04’ OracleBookstore SQL302 Module 1 28 14
  • Select statement clauses SELECT… INTO… FROM… WHERE… GROUP BY… HAVING… ORDER BY…Bookstore SQL302 Module 1 29 SELECT See SQL202 for syntax and semantics of basic SELECT statementBookstore SQL302 Module 1 30 15
  • On Your Own• Find books written by Mark Twain• Show title, publisher, yearBookstore SQL302 Module 1 31 Complex Predicates Follow normal boolean logic Select customer_last_name, customer_street From customers Where (customer_last_name = ‘Jones’ or customer_last_name = ‘Smith’)and customer_state=‘NY’Bookstore SQL302 Module 1 32 16
  • Select with Complex WhereBookstore SQL302 Module 1 33 Complex Where ResultBookstore SQL302 Module 1 34 17
  • Special Operators • Can be used in where clause • Covered in this class (SQL302) – Exists (Covered in section on Joins) – Like extensions – Any, some, all • Previously Covered in SQL202 – LIKE – IN – BETWEEN – IS NULLBookstore SQL302 Module 1 35 Like Extensions• ANSI wildcards• Where customer_last_name like ‘[JK]o%’ like ‘[J-M]%’ like [^abc]%Bookstore SQL302 Module 1 36 18
  • Any, some, All• Any, some • All• Modifies comparison • Modifies comparison operator operator• Ex: expr > any (1,2,3) • Ex: expr > all(1,2,3) means expr would would have to be have to be greater greater than 3 than the minimum which is 1Bookstore SQL302 Module 1 37 On Your Own• Find all customers with a last name that starts with a through m• Find all customers that live in a state that does not start with mBookstore SQL302 Module 1 38 19
  • Case• Used to return a choice from two or more alternatives• Two forms – Searched case – Unsearched caseBookstore SQL302 Module 1 39 Unsearched (Simple) CASE• This form of case has a selector which takes on a value used to select an alternative• Syntax: Select case <selector> When <value1> then <expr1>, When <value2> then <expr2>, … Else <statement> EndBookstore SQL302 Module 1 40 20
  • Unsearched (Simple Case)• Example: expand the order filled status columns in the orders tableBookstore SQL302 Module 1 41 Searched CASE• This form of the Case statement does not have a selector• Syntax: Select case When <condition1> then <expr1>, When <condition2> then <expr2>, … Else <statement> EndBookstore SQL302 Module 1 42 21
  • Searched CASE• Example: list names of referring customers, self in no referrerBookstore SQL302 Module 1 43 CAST• Function to cast a column to a different data type; same idea as cast in c programming• Syntax: CAST ( expression AS data_type [ ( length ) ] )Bookstore SQL302 Module 1 44 22
  • CAST• Example: combine author name and publication year into one columnBookstore SQL302 Module 1 45 CAST resultsBookstore SQL302 Module 1 46 23
  • Convert• Function to convert from one data type to another; mostly replaced by cast• Syntax CONVERT ( data_type [ ( length ) ] , expression [ , style ] )Bookstore SQL302 Module 1 47 Convert• Example: – Remove time from display of a datetime columnBookstore SQL302 Module 1 48 24
  • Convert resultsBookstore SQL302 Module 1 49 Subqueries• One select statement embedded in another• Can be nested multiple levels deep• Can be used in select, from and where clauses• Two types: – Uncorrelated – executes inner query then outer – Correlated – executes inner query once for each outer query rowBookstore SQL302 Module 2 50 25
  • Uncorrelated Subquery• In list (covered in sql202 basic class)• Single valuedBookstore SQL302 Module 2 51 Uncorrelated Subquery select isbn, quantity from orderlines where order_numb in (select order_numb from orders where order_date between ‘1/1/99’ and ‘12/31/99’);Bookstore SQL302 Module 2 52 26
  • Single-valued Subquery• Subqueries can be used where an expression returns a scalar or single value – calculations – comparisons• Can be used in select list, from clause and where clauseBookstore SQL302 Module 2 53 Single-valued Subquery• Example – Show all orderlines with an order total greater than the average for all orderlines• Code use bookstore; SELECT isbn, quantity , (select avg(quantity) from orderlines) as [Average Quantity] FROM orderlines AS ol WHERE quantity > (select avg(quantity) from orderlines)Bookstore SQL302 Module 2 54 27
  • Correlated Subquery with Exists• Inner subquery executed once for each outer row• Exists will return true or false depending on whether the result will have any rows or not• Can be a quick way to test for existence of records (parent records, say) as used in application enforcement of referential integrityBookstore SQL302 Module 2 55 Correlated subquery with Exists SELECT isbn, quantity FROM orderlines AS ol WHERE exists (select * from orders o where ol.order_numb = o.order_numb and o.order_date between ‘1/1/99’ and ‘12/31/99’);Bookstore SQL302 Module 2 56 28
  • Derived Tables• Sort of a named subquery• Allows you to access columns inside the subquery from the containing outer query• Syntax <select statement> as derivedtablenameBookstore SQL302 Module 2 57 Derived Tables• Example: List the number of orders per year• Code use bookstore; select order_year, count(order_numb) from( select YEAR(order_date) as order_year, order_numb from orders) as d group by order_year;Bookstore SQL302 Module 2 58 29
  • Common Table Expressions• Can be used to define a subquery that can be reused within an SQL statement• Syntax With CTE_name (column list) As ( Select statement ) <outer query that uses the CTE>Bookstore SQL302 Module 2 59 Common Table Expressions• Example: show order_lines with cost more than the average. Demonstrate two techniques: – Technique 1 - Using subqueries w/out a CTE – Technique 2 - With CTE’sBookstore SQL302 Module 2 60 30
  • Technique 1 – w/out CTEselect isbn, cost_each, (select AVG(cost_each)from orderlines)from orderlineswhere cost_each > (select AVG(cost_each) from orderlines)order by isbn;Bookstore SQL302 Module 2 61 Technique 2 – using a CTEwith average_cost_cte(average_cost)as(select AVG(cost_each)from orderlines)select isbn, cost_each, average_costfrom orderlines, average_cost_ctewhere cost_each > average_costorder by isbn;Bookstore SQL302 Module 2 62 31
  • SQL Exercises • List all customers whose last name does not end with s or t. • Find all customers who have not placed an order. • Find all order lines with an amount less than the average. Include the order date without the time. • List all books with a price greater than the average price for all books. Show the variance from the average, too. Use a CTE.Bookstore SQL302 Module 1 [end module] 63 NotesBookstore SQL302 Module 1 64 32
  • SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T- SQL Fundamentals by Itzki Ben-gan Workshop 2 – Joins, Set Operations, Window FunctionsBookstore SQL302 Module 2 1 Note on SQL302 Slides • These slides were originally designed to support a single SQL course which was used for any of MS Access, MySQL, Oracle and SQL Server. • As such you may see here slides developed in any one of the above products. • We are in the process of migrating the Oracle, Access, and MySQL slides out into their own slide sets. The SQL302 slides will cover Microsoft SQL Server.Bookstore SQL302 Module 2 2 1
  • Warning!• Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. New Name Old Name Orders Order_filled Order_Lines OrderlinesBookstore SQL302 Module 2 3 SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2012All rights reserved.Bookstore SQL302 Module 2 4 2
  • SQL302 Resources• Bookstore database scripts found on box.net at http://tinyurl.com/SQLScripts• Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases• Follow up questions? sql.support@dhdursoassociates.comBookstore SQL302 Module 2 5 Relational Database with constraints (from text)Bookstore SQL302 Module 2 6 3
  • Sample Employees DatabaseBookstore2 & SQL204 Module 1 7Employees More conventions• Names can be surrounded with “ “ or [ ] as in [order details].• Some of the PowerPoint slides may have this convention.• Better practice is to use an underscore as in order_details.Bookstore SQL302 Module 2 8 4
  • SQL302 SQL Programming Part 1 – Joins: Natural, Self and OuterBookstore SQL302 Module 2 9 Joins• Inner (Covered in SQL202 course)• Natural Join• Self• Data Warehouse operators• Outer – Left – Right – Full• Cross• Theta• We will cover some of the more advanced or subtle aspects of joins in this classBookstore SQL302 Module 2 10 5
  • Natural Joins• Table1 natural join table3 – automatically uses columns with same name• Table 1 natural join table2 using(<column- list>• Not yet available in SQL ServerBookstore SQL302 Module 2 11 Correlation Names (Table Aliases)• Can abbreviate references to tables• For example: Select e.name, j.payrange From employees as e Inner join job_information as j On e.jobcode = j.jobcode;Bookstore SQL302 Module 2 12 6
  • Self Joins• Implements a recursive relationship• Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation namesBookstore SQL302 Module 2 13 Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;Bookstore SQL302 Module 2 14 7
  • Bookstore SQL302 Module 2 15 Datawarehouse clauses• Two keywords that can be added to a grouped query – Rollup – Cube• Places additional summary rows in the result set• Result set is a true relational result setBookstore SQL302 Module 2 16 8
  • Rollup• Example: calculate average salaries by job_title_code and managerBookstore SQL302 Module 2 17 Rollup resultsBookstore SQL302 Module 2 18 9
  • cube• Similar to rollup but computes summary rows in all dimensionsBookstore SQL302 Module 2 19 Cube results• Add a new set of rows which total by yearBookstore SQL302 Module 2 20 10
  • Bookstore SQL302 Module 2 21 Outer Joins• Left – selects all rows from the left or first table, even if no match exists in the other table – Widely used in commercial practice – Especially useful for reporting – Can be slower and interfere with optimizer• Right – same idea but all rows from right table• Full – all rows form both tablesBookstore SQL302 Module 2 22 11
  • Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition>Bookstore SQL302 Module 2 23 Left Outer Join• List all customers with their orders• Include customers with no orders as wellBookstore SQL302 Module 2 24 12
  • Left-Join Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date from customers as c left join orders as o on c.customer_numb = o.customer_numbBookstore SQL302 Module 2 25 Left Join with ResultsBookstore SQL302 Module 2 26 13
  • Negative Left Join• List all the customers who have not placed any orders• This is an example of a query which finds unmatched recordsBookstore SQL302 Module 2 27 Negative Left-Join (Unmatched) Basic Example: SELECT customer_first_name, customer_last_name, order_numb, order_date from customers as c left join orders as o on c.customer_numb = o.customer_numb Where order_numb is null;Bookstore SQL302 Module 2 28 14
  • Bookstore SQL302 Module 2 29 Left Join w/ Partial Match• List all customers along with any orders placed in 1999• If they did not place 1999 orders we still want to include them in the printoutBookstore SQL302 Module 2 30 15
  • Left Join w/ Partial Match Example: SELECT customer_first_name, customer_last_name, order_numb, order_date from customers as c Left join (select customer_numb, order_numb, order_date From orders Where year(order_date) = 1999) as d on c.customer_numb = d.customer_numb;Bookstore SQL302 Module 2 31 Own Your Own• List all books and their order totals for 1999• Show the book even if there were no orders placed in 1999Bookstore SQL302 Module 2 32 16
  • Theta Joins• Theta joins involve inequalities in the matching conditions• Can be used for some interesting queries which do not involve the usual primary key to foreign key matchingsBookstore SQL302 Module 2 33 Theta join• Find all customers that live at the same address – Requires a self join of the customers table on address fieldBookstore SQL302 Module 2 34 17
  • Theta join results • Can be further processed with a union query to consolidate names into a single listBookstore SQL302 Module 2 35 SQL302 SQL Programming Part 3– Set OperationsBookstore SQL302 Module 2 36 18
  • Set Operations• More on unions• Intersect• ExceptBookstore SQL302 Module 2 37 Unions• Combines two or more tables• Tables must be union compatibleBookstore SQL302 Module 2 38 19
  • Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>Bookstore SQL302 Module 2 39 Unions• Example: consolidate two columns into one columnBookstore SQL302 Module 2 40 20
  • Union consolidation result• Customers in same cityBookstore SQL302 Module 2 41 Unions• Example: add a total row to a query result• Code: use bookstore; select order_numb , sum(quantity) as "Quantity" , sum(cost_line)as "Total Cost" from orderlines group by order_numb union select NULL, sum(quantity), sum(cost_line) from orderlines;Bookstore SQL302 Module 2 42 21
  • unions• Example: add an element to a pick listBookstore SQL302 Module 2 43 intersect• The intersect operator finds rows in common between two tables• Syntax Select <column-list> from <table1> intersect Select <same-columns> from <table2>Bookstore SQL302 Module 2 44 22
  • intersect• Example: find cities in common between sources and customers• Code select customer_city, customer_state, customer_zip from customers intersect select source_city, source_state, source_zip from sources; SQL302 Module 2Bookstore 45 Except• Finds all rows from first table that are not found in the second table• Syntax: Select <column-list> from <table1> except Select <same-columns> from <table2>Bookstore SQL302 Module 2 46 23
  • except• Example: find sources that are not located in any of our customer’s cities• Code select source_city, source_state, source_zip from sources except select customer_city, customer_state, customer_zip from customers;SQL302 Module 2Bookstore 47 SQL302 SQL Programming Part 4 – Window FunctionsBookstore SQL302 Module 2 48 24
  • Aggregate Functions• Count• Sum• Min• Max• Avg• Often used in conjunction with grouping and window functionsBookstore SQL302 Module 2 49 Window Functions• Sort of like grouping, but aggregates can be taken along with straight columns in the select list• The function is applied over a window – Partition by column – Partition by ()Bookstore SQL302 Module 2 50 25
  • Window Functions Basic syntax: Select …, aggregate function(<column>) over (partition by <column>) From <table> where <predicate>Bookstore SQL302 Module 2 51 Window Functions Example: Show salary along with average for the job_title and overall Code: use employeedb; select soc_sec_no, name, salary , SUM(salary) over(partition by job_title_code) as [Job Code Average] , SUM(salary) over() as [Average] from employees;Bookstore SQL302 Module 2 52 26
  • Exercise• List all customers and their orders – Name nicely formatted – With orders in the year of 1999 (do not use between, etc.) – Show total order quantities and amounts – Only include orders with more than three order linesBookstore SQL302 Module 2 53 NotesBookstore SQL302 Module 2 54 27
  • NotesBookstore SQL302 Module 2 55 NotesBookstore SQL302 Module 2 56 28
  • SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T- SQL Fundamentals by Itzki Ben-gan Workshop 3 – Modifying Data, Managing the DatabaseSQL Server/Employees SQL302 Module 3 1 Note on SQL302 Slides • These slides were originally designed to support the single SQL302 course which was used for any of MS Access, Oracle and SQL Server. • As such you may see here slides developed in any one of the above products. • We are in the process of migrating the Oracle MySQL, and MS Access slides out into their own slide sets. These SQL302 slides will focus on Microsoft SQL Server.SQL Server/Employees SQL302 Module 3 2 1
  • Warning!• Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. New Name Old Name Orders Order_filled Order_Lines OrderlinesSQL Server/Employees SQL302 Module 3 3 SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2011. All rights reserved.SQL Server/Employees SQL302 Module 3 4 2
  • SQL302 Resources• Bookstore database scripts found on box.net at http://tinyurl.com/SQLScripts• Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases• Follow up questions? sql.support@dhdursoassociates.comSQL Server/Employees SQL302 Module 3 5 SQL302 Module 3• Part 1 – Modifying Data• Part 2 – Managing Database StructuresSQL Server/Employees SQL302 Module 3 6 3
  • SQL302 SQL Programming Part 1 – Modifying DataSQL Server/Employees SQL302 Module 3 7 Relational Database with constraints (from text)SQL Server/Employees SQL302 Module 3 8 4
  • Sample Employees DatabaseBookstore2 & SQL204 Module 1 9Employees Transactions • Statements can be grouped into transactions • All must succeed • If so they are all committed • If not they are all rolled back • Helps guarantee data is consistentSQL Server/Employees POS/410 Workshop 3 10 5
  • SQL Server Transactions Syntax begin transaction Statements … … if @@error = 0 Commit transaction else Rollback errorSQL Server/Employees POS/410 Workshop 3 11 Data Modification Statements • End-user rarely sees these statements • Application developer prepares these statements “behind the scenes” based on forms or web pages filled out by userSQL Server/Employees SQL302 Module 3 12 6
  • Data Modification Statements • This course (SQL302) – Select Into – Table Valued Constructors (TVCs) – Update – Delete • Basic DML already covered in SQL202SQL Server/Employees SQL302 Module 3 13 Select into• Select….into will copy a table• Uses a regular SQL statement with into clause before the from not after• Syntax: Select <select list> Into <tablename> From <tablename>SQL Server/Employees SQL302 Module 3 14 7
  • Select into• Example: – Copy a subset of the employees table to a temporary working table• Code:SQL Server/Employees SQL302 Module 3 15 Insert with TVC• Newer form of insert statement long available in MySQL• Can shorten your code• Each element in the insert list can actually be an expression but we will use literals in this classSQL Server/Employees SQL302 Module 3 16 8
  • Insert with TVCSQL Server/Employees SQL302 Module 3 17 Update and Delete • Updates and deletes can use subqueries • SQL Server allows update and delete statements to be based on joins, too • We will review this in the next few slides.SQL Server/Employees SQL302 Module 3 18 9
  • Update• You can use subqueries in an update. – In where predicate – To set the field value UPDATE table SET columnname = value from subquery [WHERE condition with subquery]SQL Server/Employees SQL302 Module 3 19 UPDATE w/ Subquery in where• Example: Increase range minimums for unused job codesSQL Server/Employees SQL302 Module 3 20 10
  • UPDATE ResultsSQL Server/Employees SQL302 Module 3 21 UPDATE FROM Statement SQL Server allows updates from a table, including joined tables. As an example one could update quantity on hand in an inventory table from a transaction table. UPDATE table SET columnname = value… [FROM tablelist] [WHERE condition]SQL Server/Employees SQL302 Module 3 22 11
  • Update from• Example: increase managerial salariesSQL Server/Employees SQL302 Module 3 23 UPDATE From ResultsSQL Server/Employees SQL302 Module 3 24 12
  • Update w/ subquery in set clause• Update employee temp table – set salaries to the average for that codeSQL Server/Employees SQL302 Module 3 25 DELETE FROM Statement SQL Server allows deletes from a table based on a subquery or a join condition. Basic syntax: DELETE [from] table FROM tablelist [WHERE condition]SQL Server/Employees SQL302 Module 3 26 13
  • Delete from• Example: Delete unused job titlesSQL Server/Employees SQL302 Module 3 27 DELETE FROM ResultsSQL Server/Employees SQL302 Module 3 28 14
  • Delete and Referential Integrity• Can affect referential integrity when deleting a “parent” row• Can do following with child… – Cascade: delete the child row – Set null: set the child’s foreign key null – Set default: as above but to default value – No action: don’t allow delete of parent row• Referential integrity can be established when creating or modifying table structures which we will look at later in the classSQL Server/Employees SQL302 Module 3 29 SQL302 SQL Programming Part 2– Managing Database StructuresSQL Server/Employees SQL302 Module 3 30 15
  • Managing Database Structures• Create• Alter• Synonyms• ViewsSQL Server/Employees SQL302 Module 3 31 Managing Database Structures• We will first create a table and then use the alter command to – Add columns – Modify columns – Add constraintsSQL Server/Employees SQL302 Module 3 32 16
  • Creating Tables• Use create statement• Specify: – Columns with data types and column constraints – Table constraints • Foreign key references • Primary key designationSQL Server/Employees SQL302 Module 3 33 Create Table Basic syntax: Create table <table-name> ( <column1> <datatype> <constraints> ,.. <column1> <datatype> <constraints> … <table constraints> );SQL Server/Employees SQL302 Module 3 34 17
  • Create Table Example 1: SQL202 Create summary table (we will do this step by step using the alter statement in succeeding slides) Create table summary( isbn varchar(20) primary key, How_many int check (how_many >= 0), Constraint isbn_fk Foreign key (isbn) references books(isbn) )SQL Server/Employees SQL302 Module 3 35 Create Table Example 2: Create summary table Create table #summary( isbn varchar(20) primary key);SQL Server/Employees SQL302 Module 3 36 18
  • Modifying a Table Design• Applies to tables• Use ALTER statement – Add columns – Delete columns – Rename columns – Add column constraints – Add table constraintsSQL Server/Employees SQL302 Module 3 37 Modifying a Table Design Basic syntax: Alter <table-name> Add <field-name>, Add <table-constraint>, Alter <field-name> Etc.SQL Server/Employees SQL302 Module 3 38 19
  • Add a column Example: add a column to hold how many times a book has been sold alter table #summary Add how_many numeric(5,2);SQL Server/Employees SQL302 Module 3 39 Modify a column• Example – Change the how many column to an integer• Code alter table #summary alter column how_many int;SQL Server/Employees SQL302 Module 3 40 20
  • New column resultsSQL Server/Employees SQL302 Module 3 41 Column Constraints• Primary key• Not NULL• CHECK clause• Default• UniqueSQL Server/Employees SQL302 Module 3 42 21
  • Add a column constraint Example: modify the how many column so there is a check constraint on how_many alter table #summary add constraint check (how_many >=0);SQL Server/Employees SQL302 Module 3 43 Table Constraints• Primary Key• Foreign Key• Compare fields against each other. I.e. ship_date >= order_dateSQL Server/Employees SQL302 Module 3 44 22
  • Add a table constraint Example: add a foreign key constraint with cascade optionsSQL Server/Employees SQL302 Module 3 45 Constraints on Summary TableSQL Server/Employees SQL302 Module 3 46 23
  • Synonyms• Can create another name for an object – Used to provide a shorthand way to refer a long, fully qualified table name – Used where we want scripts to use an old name as well as the newer name• Syntax: – Create <synonym> for <objectname>SQL Server/Employees SQL302 Module 3 47 Synonyms• Example: – create a synonym for the orderlines table• Code create synonym orderlines for order_lines;SQL Server/Employees SQL302 Module 3 48 24
  • Views• Think of a view as a named query wherein the definition is stored in the database• Can be read like a table• Some are updateableSQL Server/Employees SQL302 Module 3 49 Views Basic syntax: Create view <view-name> (<column-list>) As <select statement> Column list can be used to name the output columns instead of using the names in the select listSQL Server/Employees SQL302 Module 3 50 25
  • Creating a ViewSQL Server/Employees SQL302 Module 3 51 Using Views• Can be used like a table subject to various limitations – Cannot insert into grouped queries, etc. – Etc.• Sample select from syntax: select column-list from employee_viewSQL Server/Employees SQL302 Module 3 52 26
  • Inserting into a view• Must insert into all required columns in underlying table• Sample code:SQL Server/Employees SQL302 Module 3 53 Using a ViewSQL Server/Employees SQL302 Module 3 54 27
  • SQL302 [end of course]SQL Server/Employees SQL302 Module 3 55 NotesSQL Server/Employees SQL302 Module 3 56 28
  • Orange Coast Database Associates Course Material (800)355-9855 or http://www.dhdursoassociates.com Accelerated Computer Training Orange Coast Database Associates Specializing in Microsoft Office, Access, SQL, and related technologies Computer Training, Programming & Consulting 32422 Alipaz St., Suite A-15 San Juan Capistrano, CA (800)355-9855 (Toll Free) | (949)489-1472 (Direct) | (949)485-6284 (Fax) http://www.dhdursoassociates.com | sales@dhdursoassociates.comAccelerated Computer Training for Working Professionals