SlideShare une entreprise Scribd logo
1  sur  96
Télécharger pour lire hors ligne
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-9855




Accelerated 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.com

Bookstore                             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 certificate




Bookstore                            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.com

Bookstore                              SQL302 Module 1   4




                                                             2
About Us                        5




     Intermediate SQL Curriculum

     SQL322W     SQL302              SQL312
     MySQL**   Transact-SQL          Oracle**



                                •*= first day only
                                •**=under
               SQL3xxS*         development



Bookstore            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 functions



Bookstore                    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
               – Views

Bookstore                   SQL302                9




                Intermediate SQL

    Course Format:

     •      3 Sessions
     •      Lecture
     •      Demo
     •      Student “hands-on”
     •      Many exercises are cumulative –
            later examples build on queries
            created earlier

Bookstore                   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 structures

Bookstore                 SQL302           11




                       Notes




Bookstore                 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 Expressions
Bookstore                          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                            Orderlines


Bookstore2                             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.com

Bookstore              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 databases

Bookstore              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
  scripting


Bookstore        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
  Oracle


Bookstore        SQL302 Module 1              8




                                                  4
Relational Database Basics
•   Storage                       •   Indexes
•   Databases                     •   Views
•   Tables                        •   Cursors
•   Rows                          •   Application interfaces
•   Columns




Bookstore                SQL302 Module 1                       9




      Relational Database Table




Bookstore                SQL302 Module 1                   10




                                                                   5
Constraints
• Database                         • Other Business Rule
      – Domain                          – Triggers
      – Uniqueness                      – Stored Procedures
      – Relationship
        Cardinality
            • 1 to 1
            • 1 to N




Bookstore                 SQL302 Module 1                     11




        Relational Database with constraints




Bookstore                 SQL302 Module 1                     12




                                                                   6
Database Management Systems

                    Positioning Chart


    Cost                          VLDB
                           Enterprise
                       Workgroup
                  Single user
            Spreadsheet
                                     # Users
Bookstore                SQL302 Module 1                13




             System Architecture

 File Server
 Architecture
                                               Access
                                               MDB



                      Access



Bookstore                SQL302 Module 1                14




                                                             7
System Architecture

 Client/Server
 Architecture
                                              Oracle
            SQL                             DB



             Visual                        Access
             Basic App


Bookstore                SQL302 Module 1               15




            System Architecture

 Web
 Architecture
                         Web                  Oracle
                         Server               DB


                                           SQL
            Browser



Bookstore                SQL302 Module 1               16




                                                            8
Approaching SQL
• Relatively simple
• Two main environments
      – Interactive (This course)
      – Embedded
             • Static (Compiled)
             • Dynamic




Bookstore                    SQL302 Module 1   17




                SQL Standardization
ANSI standardization
      –     First standard in 1986
      –     SQL 89
      –     SQL 92
      –     SQL 99
• Various vendor extensions
      – Microsoft/Sybase: T-SQL
      – Oracle: PL/SQL

Bookstore                    SQL302 Module 1   18




                                                    9
SQL Conformance
•   Entry
•   Intermediate
•   Advanced
•   Most are at least entry level




Bookstore            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 Language



Bookstore            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 administration



Bookstore                  SQL302 Module 1            21




                          SQL DCL
• Data Control Language (DDL)

      –     Grant
      –     Revoke
      –     Deny
      –     Constraints



Bookstore                  SQL302 Module 1            22




                                                           11
SQL DQL
• Data Manipulation Language (DML)
      – Select




Bookstore         SQL302 Module 1    23




                 SQL DML
• Data Manipulation Language (DML)
      – Insert
      – Update
      – Delete




Bookstore         SQL302 Module 1    24




                                          12
SQL Statement Processing

                              Parse

                            Validate

                           Optimize

                          Access Plan

                            Execute

Bookstore                  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’ Oracle




Bookstore             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
            statement




Bookstore              SQL302 Module 1   30




                                              15
On Your Own
• Find books written by Mark Twain
• Show title, publisher, year




Bookstore         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 Where




Bookstore          SQL302 Module 1   33




            Complex Where Result




Bookstore          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 NULL
Bookstore                      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 1

Bookstore             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 m




Bookstore             SQL302 Module 1                    38




                                                              19
Case
• Used to return a choice from two or more
  alternatives
• Two forms
      – Searched case
      – Unsearched case




Bookstore                     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>
      End
Bookstore                    SQL302 Module 1    40




                                                     20
Unsearched (Simple Case)
• Example: expand the order filled status
  columns in the orders table




Bookstore                    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>
      End
Bookstore                    SQL302 Module 1   42




                                                    21
Searched CASE
• Example: list names of referring
  customers, self in no referrer




Bookstore               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 column




Bookstore       SQL302 Module 1      45




            CAST results




Bookstore       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
        column




Bookstore              SQL302 Module 1              48




                                                         24
Convert results




Bookstore              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 row

Bookstore              SQL302 Module 2               50




                                                          25
Uncorrelated Subquery
• In list (covered in sql202 basic class)
• Single valued




Bookstore              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 clause


Bookstore               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 integrity




Bookstore                  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 derivedtablename



Bookstore            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’s




Bookstore                     SQL302 Module 2        60




                                                          30
Technique 1 – w/out CTE
select isbn, cost_each, (select
  AVG(cost_each)from orderlines)
from orderlines
where cost_each > (select AVG(cost_each) from
  orderlines)
order by isbn;




Bookstore           SQL302 Module 2             61




        Technique 2 – using a CTE
with average_cost_cte(average_cost)
as
(select AVG(cost_each)
from orderlines)
select isbn, cost_each, average_cost
from orderlines, average_cost_cte
where cost_each > average_cost
order 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




                      Notes




Bookstore             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
                            Functions
Bookstore                          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                         Orderlines


Bookstore                              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.com

Bookstore                 SQL302 Module 2                  5




        Relational Database with constraints (from text)




Bookstore                 SQL302 Module 2                  6




                                                               3
Sample Employees Database




Bookstore2 &          SQL204 Module 1             7
Employees




               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 Outer


Bookstore                  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 class
Bookstore                 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 Server



Bookstore               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 names



Bookstore                   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 set

Bookstore           SQL302 Module 2            16




                                                    8
Rollup
• Example: calculate average salaries by
  job_title_code and manager




Bookstore         SQL302 Module 2          17




            Rollup results




Bookstore         SQL302 Module 2          18




                                                9
cube
• Similar to rollup but computes summary
  rows in all dimensions




Bookstore         SQL302 Module 2             19




             Cube results
• Add a new set of rows which total by year




Bookstore         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 tables


Bookstore                 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 well




Bookstore                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_numb

Bookstore               SQL302 Module 2    25




              Left Join with Results




Bookstore               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 records




Bookstore               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 printout




Bookstore             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 1999




Bookstore                    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 matchings




Bookstore                  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
        field




Bookstore                  SQL302 Module 2                       34




                                                                      17
Theta join results




 • Can be further processed with a union query to
   consolidate names into a single list
Bookstore               SQL302 Module 2             35




                     SQL302

                 SQL Programming

                 Part 3– Set Operations


Bookstore               SQL302 Module 2             36




                                                         18
Set Operations
• More on unions
• Intersect
• Except




Bookstore          SQL302 Module 2   37




                Unions
• Combines two or more tables
• Tables must be union compatible




Bookstore          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
  column




Bookstore           SQL302 Module 2           40




                                                   20
Union consolidation result
• Customers in same city




Bookstore                 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 list




Bookstore         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 2
Bookstore                                        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 2
Bookstore                                      47




                 SQL302

             SQL Programming

            Part 4 – Window Functions


Bookstore           SQL302 Module 2            48




                                                    24
Aggregate Functions
•   Count
•   Sum
•   Min
•   Max
•   Avg
•   Often used in conjunction with grouping
    and window functions
Bookstore              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 lines


Bookstore               SQL302 Module 2               53




                        Notes




Bookstore               SQL302 Module 2               54




                                                           27
Notes




Bookstore   SQL302 Module 2   55




            Notes




Bookstore   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
                         Database
SQL 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                              Orderlines


SQL 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.com

SQL Server/Employees        SQL302 Module 3   5




                       SQL302 Module 3
• Part 1 – Modifying Data
• Part 2 – Managing Database Structures




SQL Server/Employees        SQL302 Module 3   6




                                                  3
SQL302

                       SQL Programming

                       Part 1 – Modifying Data


SQL Server/Employees          SQL302 Module 3             7




       Relational Database with constraints (from text)




SQL Server/Employees          SQL302 Module 3             8




                                                              4
Sample Employees Database




Bookstore2 &                   SQL204 Module 1      9
Employees




                          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
    consistent

SQL Server/Employees          POS/410 Workshop 3   10




                                                        5
SQL Server Transactions Syntax
                   begin transaction
                       Statements
                       …
                       …
                   if @@error = 0
                       Commit transaction
                   else
                       Rollback error

SQL 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 user



SQL 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
             SQL202

SQL 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 class


SQL Server/Employees       SQL302 Module 3          16




                                                         8
Insert with TVC




SQL 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 codes




SQL Server/Employees     SQL302 Module 3        20




                                                     10
UPDATE Results




SQL 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 salaries




SQL Server/Employees     SQL302 Module 3   23




                UPDATE From Results




SQL Server/Employees     SQL302 Module 3   24




                                                12
Update w/ subquery in set clause
• Update employee temp table – set salaries to the
  average for that code




SQL 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 titles




SQL Server/Employees     SQL302 Module 3   27




           DELETE FROM Results




SQL 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 class

SQL Server/Employees         SQL302 Module 3            29




                         SQL302

                       SQL Programming

               Part 2– Managing Database Structures


SQL Server/Employees         SQL302 Module 3            30




                                                             15
Managing Database Structures
•   Create
•   Alter
•   Synonyms
•   Views




SQL 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 constraints




SQL 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 designation


SQL 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 constraints

SQL 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 results




SQL Server/Employees    SQL302 Module 3   41




                  Column Constraints
•   Primary key
•   Not NULL
•   CHECK clause
•   Default
•   Unique



SQL 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_date




SQL Server/Employees        SQL302 Module 3   44




                                                   22
Add a table constraint

        Example: add a foreign key constraint
        with cascade options




SQL Server/Employees    SQL302 Module 3         45




   Constraints on Summary Table




SQL 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 updateable




SQL 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 list

SQL Server/Employees     SQL302 Module 3                50




                                                             25
Creating a View




SQL 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_view

SQL 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 View




SQL Server/Employees      SQL302 Module 3    54




                                                  27
SQL302




                       [end of course]
SQL Server/Employees     SQL302 Module 3   55




                         Notes




SQL 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.com




Accelerated Computer Training for Working Professionals

Contenu connexe

En vedette

Oracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guideOracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guidebupbechanhgmail
 
pl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledgepl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledgeMasood Khan
 
PL/SQL Code for Sample Projects
PL/SQL Code for Sample ProjectsPL/SQL Code for Sample Projects
PL/SQL Code for Sample Projectsjwjablonski
 
Advanced Database Lecture Notes
Advanced Database Lecture NotesAdvanced Database Lecture Notes
Advanced Database Lecture NotesJasour Obeidat
 
Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public RecordsRyan Thornburg
 
Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Tim Rootsaert
 
Preparing Students
Preparing StudentsPreparing Students
Preparing StudentsKatie Turner
 
AVB201.1 Microsoft Access VBA Module 1
AVB201.1 Microsoft Access VBA Module 1AVB201.1 Microsoft Access VBA Module 1
AVB201.1 Microsoft Access VBA Module 1Dan D'Urso
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Andres Agostini, Future Knowledgist
 
The Gap Between Online Journalism Education and Practice
The Gap Between Online Journalism Education and PracticeThe Gap Between Online Journalism Education and Practice
The Gap Between Online Journalism Education and PracticeRyan Thornburg
 
KaDouce AutoBio
KaDouce AutoBioKaDouce AutoBio
KaDouce AutoBioKarine L
 
Alles Van Tmm
Alles Van TmmAlles Van Tmm
Alles Van Tmmlucasnet
 
Taggerfm Artist 091116
Taggerfm Artist 091116Taggerfm Artist 091116
Taggerfm Artist 091116Tim Rootsaert
 
My Logo Portfolio
My Logo PortfolioMy Logo Portfolio
My Logo Portfoliobeth7865
 
OpenRural's Guide to Digital Public Records in N.C.
OpenRural's Guide to Digital Public Records in N.C.OpenRural's Guide to Digital Public Records in N.C.
OpenRural's Guide to Digital Public Records in N.C.Ryan Thornburg
 
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...Andres Agostini, Future Knowledgist
 

En vedette (20)

Exercise 6
Exercise 6Exercise 6
Exercise 6
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
Oracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guideOracle database 12c 2 day + performance tuning guide
Oracle database 12c 2 day + performance tuning guide
 
pl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledgepl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledge
 
Adbms lab manual
Adbms lab manualAdbms lab manual
Adbms lab manual
 
PL/SQL Code for Sample Projects
PL/SQL Code for Sample ProjectsPL/SQL Code for Sample Projects
PL/SQL Code for Sample Projects
 
Advanced Database Lecture Notes
Advanced Database Lecture NotesAdvanced Database Lecture Notes
Advanced Database Lecture Notes
 
Digital Public Records
Digital Public RecordsDigital Public Records
Digital Public Records
 
Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027Muziekdigitaal Taggerfm Pitch 091027
Muziekdigitaal Taggerfm Pitch 091027
 
Preparing Students
Preparing StudentsPreparing Students
Preparing Students
 
AVB201.1 Microsoft Access VBA Module 1
AVB201.1 Microsoft Access VBA Module 1AVB201.1 Microsoft Access VBA Module 1
AVB201.1 Microsoft Access VBA Module 1
 
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
 
The Gap Between Online Journalism Education and Practice
The Gap Between Online Journalism Education and PracticeThe Gap Between Online Journalism Education and Practice
The Gap Between Online Journalism Education and Practice
 
KaDouce AutoBio
KaDouce AutoBioKaDouce AutoBio
KaDouce AutoBio
 
Alles Van Tmm
Alles Van TmmAlles Van Tmm
Alles Van Tmm
 
Taggerfm Artist 091116
Taggerfm Artist 091116Taggerfm Artist 091116
Taggerfm Artist 091116
 
My Logo Portfolio
My Logo PortfolioMy Logo Portfolio
My Logo Portfolio
 
¿Somos animales?
¿Somos animales?¿Somos animales?
¿Somos animales?
 
OpenRural's Guide to Digital Public Records in N.C.
OpenRural's Guide to Digital Public Records in N.C.OpenRural's Guide to Digital Public Records in N.C.
OpenRural's Guide to Digital Public Records in N.C.
 
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
 

Similaire à SQL302 Intermediate SQL

SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualDan D'Urso
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualDan D'Urso
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualDan D'Urso
 
SQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL QueriesSQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL QueriesDan D'Urso
 
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3Dan D'Urso
 
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...IDERA Software
 
Dynamic sql for efficient searching
Dynamic sql for efficient searchingDynamic sql for efficient searching
Dynamic sql for efficient searchingdamienjoyce
 
SQL Azure Intro and what’s New
SQL Azure Intro and what’s NewSQL Azure Intro and what’s New
SQL Azure Intro and what’s Newandythiru
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)Michael Rys
 
SQL in Version Control using SQL Server Database Projects
SQL in Version Control using SQL Server Database ProjectsSQL in Version Control using SQL Server Database Projects
SQL in Version Control using SQL Server Database Projectsfloydhilton
 
SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1Dan D'Urso
 
Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...
Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...
Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...Trivadis
 
JupyterCon 2020 - Supercharging SQL Users with Jupyter Notebooks
JupyterCon 2020 - Supercharging SQL Users with Jupyter NotebooksJupyterCon 2020 - Supercharging SQL Users with Jupyter Notebooks
JupyterCon 2020 - Supercharging SQL Users with Jupyter NotebooksMichelle Ufford
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First TimeSQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First TimeDean Richards
 
Developing on SQL Azure
Developing on SQL AzureDeveloping on SQL Azure
Developing on SQL AzureIke Ellis
 
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentRapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentEmbarcadero Technologies
 
Analyzing SQL Server wait stats, hands-on!
Analyzing SQL Server wait stats, hands-on!Analyzing SQL Server wait stats, hands-on!
Analyzing SQL Server wait stats, hands-on!Red Gate Software
 
DP-300 Administering Microsoft Azure SQL Solutions Updated Dumps
DP-300 Administering Microsoft Azure SQL Solutions Updated DumpsDP-300 Administering Microsoft Azure SQL Solutions Updated Dumps
DP-300 Administering Microsoft Azure SQL Solutions Updated DumpsVictoriaMeisel
 
Azure Synapse Analytics Overview (r2)
Azure Synapse Analytics Overview (r2)Azure Synapse Analytics Overview (r2)
Azure Synapse Analytics Overview (r2)James Serra
 

Similaire à SQL302 Intermediate SQL (20)

SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL Manual
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL Manual
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
 
SQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL QueriesSQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL Queries
 
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3
 
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
Geek Sync | Locating and Resolving Common Database Performance Issues in Micr...
 
Dynamic sql for efficient searching
Dynamic sql for efficient searchingDynamic sql for efficient searching
Dynamic sql for efficient searching
 
SQL Azure Intro and what’s New
SQL Azure Intro and what’s NewSQL Azure Intro and what’s New
SQL Azure Intro and what’s New
 
U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)U-SQL Intro (SQLBits 2016)
U-SQL Intro (SQLBits 2016)
 
SQL in Version Control using SQL Server Database Projects
SQL in Version Control using SQL Server Database ProjectsSQL in Version Control using SQL Server Database Projects
SQL in Version Control using SQL Server Database Projects
 
SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1
 
Oracle sql demo
Oracle sql demoOracle sql demo
Oracle sql demo
 
Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...
Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...
Trivadis TechEvent 2017 Oracle to My SQL Migration - Challenges by Robert Bia...
 
JupyterCon 2020 - Supercharging SQL Users with Jupyter Notebooks
JupyterCon 2020 - Supercharging SQL Users with Jupyter NotebooksJupyterCon 2020 - Supercharging SQL Users with Jupyter Notebooks
JupyterCon 2020 - Supercharging SQL Users with Jupyter Notebooks
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First TimeSQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
 
Developing on SQL Azure
Developing on SQL AzureDeveloping on SQL Azure
Developing on SQL Azure
 
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL DevelopmentRapid SQL Datasheet - The Intelligent IDE for SQL Development
Rapid SQL Datasheet - The Intelligent IDE for SQL Development
 
Analyzing SQL Server wait stats, hands-on!
Analyzing SQL Server wait stats, hands-on!Analyzing SQL Server wait stats, hands-on!
Analyzing SQL Server wait stats, hands-on!
 
DP-300 Administering Microsoft Azure SQL Solutions Updated Dumps
DP-300 Administering Microsoft Azure SQL Solutions Updated DumpsDP-300 Administering Microsoft Azure SQL Solutions Updated Dumps
DP-300 Administering Microsoft Azure SQL Solutions Updated Dumps
 
Azure Synapse Analytics Overview (r2)
Azure Synapse Analytics Overview (r2)Azure Synapse Analytics Overview (r2)
Azure Synapse Analytics Overview (r2)
 

Plus de Dan D'Urso

LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartDan D'Urso
 
Database Normalization
Database NormalizationDatabase Normalization
Database NormalizationDan D'Urso
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingDan D'Urso
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedDan D'Urso
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingDan D'Urso
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using PythonDan D'Urso
 
Stem conference
Stem conferenceStem conference
Stem conferenceDan D'Urso
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joinsDan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL MedianDan D'Urso
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3Dan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2Dan D'Urso
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1Dan D'Urso
 
AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queriesDan D'Urso
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesDan D'Urso
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1Dan D'Urso
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosDan D'Urso
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 

Plus de Dan D'Urso (19)

LCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with LucidchartLCD201d Database Diagramming with Lucidchart
LCD201d Database Diagramming with Lucidchart
 
Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 
VIS201d Visio Database Diagramming
VIS201d Visio Database DiagrammingVIS201d Visio Database Diagramming
VIS201d Visio Database Diagramming
 
PRJ101a Project 2013 Accelerated
PRJ101a Project 2013 AcceleratedPRJ101a Project 2013 Accelerated
PRJ101a Project 2013 Accelerated
 
PRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic TrainingPRJ101xl Project Libre Basic Training
PRJ101xl Project Libre Basic Training
 
Introduction to coding using Python
Introduction to coding using PythonIntroduction to coding using Python
Introduction to coding using Python
 
Stem conference
Stem conferenceStem conference
Stem conference
 
Microsoft access self joins
Microsoft access self joinsMicrosoft access self joins
Microsoft access self joins
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 
AIN100
AIN100AIN100
AIN100
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL Median
 
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
 
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
SQL202.1 Accelerated Introduction to SQL Using SQL Server Module 1
 
AIN102S Access string function sample queries
AIN102S Access string function sample queriesAIN102S Access string function sample queries
AIN102S Access string function sample queries
 
AIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access QueriesAIN102.2 Microsoft Access Queries
AIN102.2 Microsoft Access Queries
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 

Dernier

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

SQL302 Intermediate SQL

  • 1. 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-9855 Accelerated Computer Training for Working Professionals Bookstore Case
  • 2. 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.com Bookstore 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 certificate Bookstore SQL302 2 1
  • 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 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.com Bookstore SQL302 Module 1 4 2
  • 4. About Us 5 Intermediate SQL Curriculum SQL322W SQL302 SQL312 MySQL** Transact-SQL Oracle** •*= first day only •**=under SQL3xxS* development Bookstore SQL302 6 3
  • 5. 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 functions Bookstore SQL302 8 4
  • 6. Intermediate SQL SQL Covered (Day 2: AM Only): • Data Updates – Select into – Update from, using subqueries – Delete from • Data structures – Alter – Synonyms – Views Bookstore SQL302 9 Intermediate SQL Course Format: • 3 Sessions • Lecture • Demo • Student “hands-on” • Many exercises are cumulative – later examples build on queries created earlier Bookstore SQL302 10 5
  • 7. Intermediate SQL Course Schedule (“1/2” day sessions): • Session 1 – Intermediate SQL • Session 2 – Multi-table Retrieval • Session 3 – Modifying data and data structures Bookstore SQL302 11 Notes Bookstore SQL302 12 6
  • 8. 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 Expressions Bookstore 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
  • 9. 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 Orderlines Bookstore2 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
  • 10. 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.com Bookstore 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 databases Bookstore SQL302 Module 1 6 3
  • 11. 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 scripting Bookstore 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 Oracle Bookstore SQL302 Module 1 8 4
  • 12. Relational Database Basics • Storage • Indexes • Databases • Views • Tables • Cursors • Rows • Application interfaces • Columns Bookstore SQL302 Module 1 9 Relational Database Table Bookstore SQL302 Module 1 10 5
  • 13. Constraints • Database • Other Business Rule – Domain – Triggers – Uniqueness – Stored Procedures – Relationship Cardinality • 1 to 1 • 1 to N Bookstore SQL302 Module 1 11 Relational Database with constraints Bookstore SQL302 Module 1 12 6
  • 14. Database Management Systems Positioning Chart Cost VLDB Enterprise Workgroup Single user Spreadsheet # Users Bookstore SQL302 Module 1 13 System Architecture File Server Architecture Access MDB Access Bookstore SQL302 Module 1 14 7
  • 15. System Architecture Client/Server Architecture Oracle SQL DB Visual Access Basic App Bookstore SQL302 Module 1 15 System Architecture Web Architecture Web Oracle Server DB SQL Browser Bookstore SQL302 Module 1 16 8
  • 16. Approaching SQL • Relatively simple • Two main environments – Interactive (This course) – Embedded • Static (Compiled) • Dynamic Bookstore SQL302 Module 1 17 SQL Standardization ANSI standardization – First standard in 1986 – SQL 89 – SQL 92 – SQL 99 • Various vendor extensions – Microsoft/Sybase: T-SQL – Oracle: PL/SQL Bookstore SQL302 Module 1 18 9
  • 17. SQL Conformance • Entry • Intermediate • Advanced • Most are at least entry level Bookstore 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 Language Bookstore SQL302 Module 1 20 10
  • 18. 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 administration Bookstore SQL302 Module 1 21 SQL DCL • Data Control Language (DDL) – Grant – Revoke – Deny – Constraints Bookstore SQL302 Module 1 22 11
  • 19. SQL DQL • Data Manipulation Language (DML) – Select Bookstore SQL302 Module 1 23 SQL DML • Data Manipulation Language (DML) – Insert – Update – Delete Bookstore SQL302 Module 1 24 12
  • 20. SQL Statement Processing Parse Validate Optimize Access Plan Execute Bookstore 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
  • 21. 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’ Oracle Bookstore SQL302 Module 1 28 14
  • 22. 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 statement Bookstore SQL302 Module 1 30 15
  • 23. On Your Own • Find books written by Mark Twain • Show title, publisher, year Bookstore 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
  • 24. Select with Complex Where Bookstore SQL302 Module 1 33 Complex Where Result Bookstore SQL302 Module 1 34 17
  • 25. 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 NULL Bookstore 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
  • 26. 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 1 Bookstore 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 m Bookstore SQL302 Module 1 38 19
  • 27. Case • Used to return a choice from two or more alternatives • Two forms – Searched case – Unsearched case Bookstore 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> End Bookstore SQL302 Module 1 40 20
  • 28. Unsearched (Simple Case) • Example: expand the order filled status columns in the orders table Bookstore 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> End Bookstore SQL302 Module 1 42 21
  • 29. Searched CASE • Example: list names of referring customers, self in no referrer Bookstore 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
  • 30. CAST • Example: combine author name and publication year into one column Bookstore SQL302 Module 1 45 CAST results Bookstore SQL302 Module 1 46 23
  • 31. 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 column Bookstore SQL302 Module 1 48 24
  • 32. Convert results Bookstore 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 row Bookstore SQL302 Module 2 50 25
  • 33. Uncorrelated Subquery • In list (covered in sql202 basic class) • Single valued Bookstore 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
  • 34. 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 clause Bookstore 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
  • 35. 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 integrity Bookstore 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
  • 36. Derived Tables • Sort of a named subquery • Allows you to access columns inside the subquery from the containing outer query • Syntax <select statement> as derivedtablename Bookstore 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
  • 37. 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’s Bookstore SQL302 Module 2 60 30
  • 38. Technique 1 – w/out CTE select isbn, cost_each, (select AVG(cost_each)from orderlines) from orderlines where cost_each > (select AVG(cost_each) from orderlines) order by isbn; Bookstore SQL302 Module 2 61 Technique 2 – using a CTE with average_cost_cte(average_cost) as (select AVG(cost_each) from orderlines) select isbn, cost_each, average_cost from orderlines, average_cost_cte where cost_each > average_cost order by isbn; Bookstore SQL302 Module 2 62 31
  • 39. 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 Notes Bookstore SQL302 Module 1 64 32
  • 40. 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 Functions Bookstore 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
  • 41. 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 Orderlines Bookstore 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
  • 42. 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.com Bookstore SQL302 Module 2 5 Relational Database with constraints (from text) Bookstore SQL302 Module 2 6 3
  • 43. Sample Employees Database Bookstore2 & SQL204 Module 1 7 Employees 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
  • 44. SQL302 SQL Programming Part 1 – Joins: Natural, Self and Outer Bookstore 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 class Bookstore SQL302 Module 2 10 5
  • 45. 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 Server Bookstore 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
  • 46. Self Joins • Implements a recursive relationship • Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation names Bookstore 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
  • 47. 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 set Bookstore SQL302 Module 2 16 8
  • 48. Rollup • Example: calculate average salaries by job_title_code and manager Bookstore SQL302 Module 2 17 Rollup results Bookstore SQL302 Module 2 18 9
  • 49. cube • Similar to rollup but computes summary rows in all dimensions Bookstore SQL302 Module 2 19 Cube results • Add a new set of rows which total by year Bookstore SQL302 Module 2 20 10
  • 50. 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 tables Bookstore SQL302 Module 2 22 11
  • 51. 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 well Bookstore SQL302 Module 2 24 12
  • 52. 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_numb Bookstore SQL302 Module 2 25 Left Join with Results Bookstore SQL302 Module 2 26 13
  • 53. Negative Left Join • List all the customers who have not placed any orders • This is an example of a query which finds unmatched records Bookstore 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
  • 54. 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 printout Bookstore SQL302 Module 2 30 15
  • 55. 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 1999 Bookstore SQL302 Module 2 32 16
  • 56. 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 matchings Bookstore 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 field Bookstore SQL302 Module 2 34 17
  • 57. Theta join results • Can be further processed with a union query to consolidate names into a single list Bookstore SQL302 Module 2 35 SQL302 SQL Programming Part 3– Set Operations Bookstore SQL302 Module 2 36 18
  • 58. Set Operations • More on unions • Intersect • Except Bookstore SQL302 Module 2 37 Unions • Combines two or more tables • Tables must be union compatible Bookstore SQL302 Module 2 38 19
  • 59. 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 column Bookstore SQL302 Module 2 40 20
  • 60. Union consolidation result • Customers in same city Bookstore 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
  • 61. unions • Example: add an element to a pick list Bookstore 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
  • 62. 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 2 Bookstore 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
  • 63. 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 2 Bookstore 47 SQL302 SQL Programming Part 4 – Window Functions Bookstore SQL302 Module 2 48 24
  • 64. Aggregate Functions • Count • Sum • Min • Max • Avg • Often used in conjunction with grouping and window functions Bookstore 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
  • 65. 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
  • 66. 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 lines Bookstore SQL302 Module 2 53 Notes Bookstore SQL302 Module 2 54 27
  • 67. Notes Bookstore SQL302 Module 2 55 Notes Bookstore SQL302 Module 2 56 28
  • 68. 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 Database SQL 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
  • 69. 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 Orderlines SQL 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
  • 70. 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.com SQL Server/Employees SQL302 Module 3 5 SQL302 Module 3 • Part 1 – Modifying Data • Part 2 – Managing Database Structures SQL Server/Employees SQL302 Module 3 6 3
  • 71. SQL302 SQL Programming Part 1 – Modifying Data SQL Server/Employees SQL302 Module 3 7 Relational Database with constraints (from text) SQL Server/Employees SQL302 Module 3 8 4
  • 72. Sample Employees Database Bookstore2 & SQL204 Module 1 9 Employees 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 consistent SQL Server/Employees POS/410 Workshop 3 10 5
  • 73. SQL Server Transactions Syntax begin transaction Statements … … if @@error = 0 Commit transaction else Rollback error SQL 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 user SQL Server/Employees SQL302 Module 3 12 6
  • 74. Data Modification Statements • This course (SQL302) – Select Into – Table Valued Constructors (TVCs) – Update – Delete • Basic DML already covered in SQL202 SQL 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
  • 75. 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 class SQL Server/Employees SQL302 Module 3 16 8
  • 76. Insert with TVC SQL 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
  • 77. 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 codes SQL Server/Employees SQL302 Module 3 20 10
  • 78. UPDATE Results SQL 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
  • 79. Update from • Example: increase managerial salaries SQL Server/Employees SQL302 Module 3 23 UPDATE From Results SQL Server/Employees SQL302 Module 3 24 12
  • 80. Update w/ subquery in set clause • Update employee temp table – set salaries to the average for that code SQL 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
  • 81. Delete from • Example: Delete unused job titles SQL Server/Employees SQL302 Module 3 27 DELETE FROM Results SQL Server/Employees SQL302 Module 3 28 14
  • 82. 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 class SQL Server/Employees SQL302 Module 3 29 SQL302 SQL Programming Part 2– Managing Database Structures SQL Server/Employees SQL302 Module 3 30 15
  • 83. Managing Database Structures • Create • Alter • Synonyms • Views SQL 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 constraints SQL Server/Employees SQL302 Module 3 32 16
  • 84. Creating Tables • Use create statement • Specify: – Columns with data types and column constraints – Table constraints • Foreign key references • Primary key designation SQL 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
  • 85. 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
  • 86. Modifying a Table Design • Applies to tables • Use ALTER statement – Add columns – Delete columns – Rename columns – Add column constraints – Add table constraints SQL 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
  • 87. 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
  • 88. New column results SQL Server/Employees SQL302 Module 3 41 Column Constraints • Primary key • Not NULL • CHECK clause • Default • Unique SQL Server/Employees SQL302 Module 3 42 21
  • 89. 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_date SQL Server/Employees SQL302 Module 3 44 22
  • 90. Add a table constraint Example: add a foreign key constraint with cascade options SQL Server/Employees SQL302 Module 3 45 Constraints on Summary Table SQL Server/Employees SQL302 Module 3 46 23
  • 91. 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
  • 92. 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 updateable SQL 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 list SQL Server/Employees SQL302 Module 3 50 25
  • 93. Creating a View SQL 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_view SQL Server/Employees SQL302 Module 3 52 26
  • 94. Inserting into a view • Must insert into all required columns in underlying table • Sample code: SQL Server/Employees SQL302 Module 3 53 Using a View SQL Server/Employees SQL302 Module 3 54 27
  • 95. SQL302 [end of course] SQL Server/Employees SQL302 Module 3 55 Notes SQL Server/Employees SQL302 Module 3 56 28
  • 96. 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.com Accelerated Computer Training for Working Professionals