SlideShare ist ein Scribd-Unternehmen logo
1 von 102
Downloaden Sie, um offline zu lesen
Orange Coast Database Associates Course                                        (800)355-9855 or http://ocdatabases.itgo.com



                           SQL202 Accelerated Introduction to
                           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://ocdatabases.itgo.com
                                                  San Juan Capistrano, CA
                                                      (800)355-9855




Accelerated Computer Training for Working Professionals                                                     Bookstore Case
Welcome to SQL202 –
     Accelerated Introduction to
     SQL Using MS SQL Server
    An accelerated introduction to SQL for non-
    programmers



     P.O. Box 6142
     Laguna Niguel, CA 92607
     949-489-1472
     http://www.d2associates.com

Bookstore                             SQL202       1




    Accelerated Introduction to
               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                            SQL202        2




                                                       1
SQL Curriculum

     SQL201W       SQL202            SQL212
      MySQL      Transact-SQL         Oracle




                  SQL200*       * = included in
                                above courses
                SQL200S*



Bookstore              SQL202                     3




 Accelerated Introduction to SQL
•   Assumes no prior knowledge of SQL
•   Quick pace for experienced computer users
•   End-user, not programmer, oriented
•   Focus is on SQL, not Management Studio
•   SQL200s is first two modules of SQL200,
    otherwise identical.


Bookstore              SQL202                     4




                                                      2
Accelerated Introduction to
              SQL
  SQL Covered (Day 1: All Day):
                • Select
                  –   Basic
                  –   Filters
                  –   Special Operators
                  –   Multi-table retrieval
                       • Joins
                       • Subqueries
                       • Unions
                  – Calculations and
                    Aggregates

Bookstore                    SQL202           5




   Accelerated Introduction to
              SQL
  SQL Covered (Day 2: AM Only):
            • Data Updates
              – Insert
              – Update
              – Delete

            • Data structures
              – Create
              – Drop
              – Alter

Bookstore                    SQL202           6




                                                  3
Accelerated Introduction to
                SQL
    Course Format:

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

Bookstore                  SQL202             7




   Accelerated Introduction to
              SQL
   Course Schedule (“1/2” day sessions):

            • Session 1 – Basic SQL
            • Session 2 – Multi-table
              Retrieval
            • Session 3 – Modifying Data



Bookstore                  SQL202             8




                                                  4
SQL200
               Based on SQL Clearly Explained by Jan Harrington




                       SQL Programming

            Module 1 – Relational Database Background,
              Basic Single Table Retrieval Operations
Bookstore                        SQL200 Module 1                  1




              Note on SQL200 Slides
    • These slides were originally designed to support the
      single SQL200 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 slides
      and the MS Access slides out into their own slide
      sets. The SQL200 slides will cover MySQL and
      SQL Server which are virtually identical for
      purposes of this course.

Bookstore2                      SQL200 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                             SQL200 Module 2         3




     SQL200 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.


Bookstore2                             SQL200 Module 2         4




                                                                   2
SQL200 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              SQL212 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              SQL200 Module 1          6




                                                    3
SQL Programming
• A basic knowledge of query systems,
  perhaps via MS Access, or some
  programming knowledge, is desirable
• We will use GUI tools or SQL Plus almost
  exclusively




Bookstore        SQL200 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        SQL200 Module 1             8




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




Bookstore                SQL200 Module 1                       9




      Relational Database Table




Bookstore                SQL200 Module 1                   10




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




Bookstore                 SQL200 Module 1                     11




        Relational Database with constraints




Bookstore                 SQL200 Module 1                     12




                                                                   6
Database Management Systems

                    Positioning Chart


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




             System Architecture

 File Server
 Architecture
                                               Access
                                               MDB



                      Access



Bookstore                SQL200 Module 1                14




                                                             7
System Architecture

 Client/Server
 Architecture
                                              Oracle
            SQL                             DB



             Visual                        Access
             Basic App


Bookstore                SQL200 Module 1               15




            System Architecture

 Web
 Architecture
                         Web                  Oracle
                         Server               DB


                                           SQL
            Browser



Bookstore                SQL200 Module 1               16




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




Bookstore                    SQL200 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                    SQL200 Module 1   18




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




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




Bookstore            SQL200 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                  SQL200 Module 1            21




                          SQL DCL
• Data Control Language (DDL)

      –     Grant
      –     Revoke
      –     Deny
      –     Constraints



Bookstore                  SQL200 Module 1            22




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




Bookstore             SQL200 Module 1   23




            SQL Statement Processing

                         Parse

                       Validate

                       Optimize

                      Access Plan

                       Execute

Bookstore             SQL200 Module 1   24




                                             12
Bookstore Sample Database



• Before we continue (note: instructor may have
  already done this)…
• Load the sample database if you haven’t already
      – Use Access import table feature, or
      – Run SQL script, or
      – Use Access upsizing wizard

Bookstore                 SQL200 Module 1           25




                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                 SQL200 Module 1           26




                                                         13
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               SQL200 Module 1         27




                      SELECT

            Basic Syntax (Projection):
            Select <column-list> or <*>
            From <table-list>




Bookstore               SQL200 Module 1         28




                                                     14
SELECT

            Basic Example (Projection):
            select
                customer_last_name,
                customer_street
            from customers


Bookstore                SQL200 Module 1   29




              MS Access SQL Query




Bookstore                SQL200 Module 1   30




                                                15
Bookstore        SQL200 Module 1   31




            SQL Server Query




Bookstore        SQL200 Module 1   32




                                        16
SELECT with Where Clause

    Example (Restriction plus Projection):
    Select <column-list>
    From <table-list>
    Where <selection-criteria>;


Bookstore           SQL200 Module 1          33




            Comparison Operators
•   < less than
•   > greater than
•   <= less than or equal to
•   >= greater than or equal to
•   <> or != two forms for not equal



Bookstore           SQL200 Module 1          34




                                                  17
SELECT with Where
  Basic Example (Restriction plus
  Projection):
  select customer_last_name,
      customer_street
  from customers
  where customer_last_name =
  ‘Jones’
Bookstore         SQL200 Module 1   35




             Select with Where




Bookstore         SQL200 Module 1   36




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




Bookstore         SQL200 Module 1    37




            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         SQL200 Module 1    38




                                          19
Select with Complex Where




Bookstore          SQL200 Module 1   39




            Complex Where Result




Bookstore          SQL200 Module 1   40




                                          20
Special Operators
•   Can be used in where clause
•   LIKE
•   IN
•   BETWEEN
•   IS NULL



Bookstore          SQL200 Module 1                 41




       Like (“Wild Card Matches”)
• ANSI                      • Access
• Where                     • Where
  customer_last_name          customer_last_name
  like ‘Jo%’                  like “Jo*”
• Like ‘Jo_’                • Like “Jo?”




Bookstore          SQL200 Module 1                 42




                                                        21
IN


  Select *
  From customers
  Where customer_last_name in
  (‘Rizzo’, ‘Jones’, ‘Garcia’)

      The list in parentheses can be replaced by a
      subquery. We will study this later.
Bookstore                  SQL200 Module 1           43




        SQL Where Clause with IN




Bookstore                  SQL200 Module 1           44




                                                          22
IS NULL
   SQL uses three valued logic. Must use IS NULL
   to test for unknowns. A null is NOT the same as
   blank or empty.

  Select *
  From customers
  Where customer_street IS NULL


Bookstore             SQL200 Module 1                45




               On Your Own
• Find all customers with an address not equal to
  4592 Maple Lane
• Was Peter Johnson selected?
• Why or why not?




Bookstore             SQL200 Module 1                46




                                                          23
BETWEEN
  Select *
  From orders
  Where order_date BETWEEN ‘1-
  Jan-99’ and ’31-Dec-99’

     Note: date formats vary from product to product.




Bookstore                 SQL200 Module 1               47




            Where with Between




Bookstore                 SQL200 Module 1               48




                                                             24
Removing Duplicates
       List once each city in which there are
       customers

            Select DISTINCT
            customer_city
            From customers
        Removes duplicate rows from result set
Bookstore                  SQL200 Module 1       49




             Removing Duplicates




Bookstore                  SQL200 Module 1       50




                                                      25
Sorting – ORDER BY
    Basic syntax:

             Select <column list>
             From <table list>
             Where <selection criteria>
             Order by <column list> [DESC]

      DESC will sort in descending order

Bookstore               SQL200 Module 1         51




             Sorting – ORDER BY
       Example:
       List all records sorted by state, city

            Select *
            From customers
            Order by customer_state,
            customer_city


Bookstore               SQL200 Module 1         52




                                                     26
Sorting Results with Order By




Bookstore              SQL200 Module 1      53




            Selecting Top Records
       List largest 5 zips or top 25 % of
       them…
  Select Top 5 (or top 25
  percent) Customer_last_name
      , contact_zip
  From customers
  Order by customer_zip desc;

Bookstore              SQL200 Module 1      54




                                                 27
SQL Exercises
  • List all books whose publisher name begins
    with “H” or “T”; sort by title [hint: use LIKE]
  • List all customers whose last name ends with
    “S”; sort by state, city, last name
  • Find the order numbers of orders with order
    dates in 1999; sort by order #. [Hint: use
    BETWEEN]
  • Find the order numbers and order dates of all
    orders with a “2” in column 2 of the credit card
    #; sort by order date descending
Bookstore             SQL200 Module 1   [end module]   55




                      Notes




Bookstore             SQL200 Module 1                  56




                                                            28
SQL200

                    SQL Programming

             Workshop 2 – Joins, Subqueries, Unions,
                  Calculations and Grouping
Bookstore2                  SQL200 Module 2                  1




             Note on SQL200 Slides
    • These slides were originally designed to support the
      single SQL200 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 slides
      and the MS Access slides out into their own slide
      sets. The SQL200 slides will cover MySQL and
      SQL Server which are virtually identical for
      purposes of this course.

Bookstore2                 SQL200 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                            SQL200 Module 2          3




     SQL200 Contact Information



             P.O. Box 6142
             Laguna Niguel, CA 92607
             949-489-1472
             http://www.d2associates.com
             slides.1@dhdursoassociates.com
             Copyright 2001-20011 All rights reserved.


Bookstore2                            SQL200 Module 2          4




                                                                   2
SQL200 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              SQL212 Module 1        5




                     SQL200

                 SQL Programming

                     Part 1 – Joins


Bookstore2              SQL200 Module 2       6




                                                  3
Relational Database with constraints (from text)




Bookstore2               SQL200 Module 2                  7




               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.


Bookstore2               SQL200 Module 2                  8




                                                              4
Joins
• Inner
• Outer
      – Left
      – Right
      – Full
•   Cross
•   Self
•   Theta
•   We will cover the most important; others as time
    and interest permit
Bookstore2            SQL200 Module 2                   9




Bookstore2            SQL200 Module 2                  10




                                                            5
Inner Join
• Pairs each row from first table with
  corresponding row from second table over
  the “join column”
• The result set only contains rows where
  there is a match over the join column in
  both tables
• Equi-join is the common inner join

Bookstore2                  SQL200 Module 2   11




                         Inner Join

             Older Syntax:
              Select <column-list>
              From <tablelist>
              Where <predicate>
             Still very commonly used


Bookstore2                  SQL200 Module 2   12




                                                   6
Inner Join

             Example using older syntax:
             SELECT customer_first_name,
             customer_street, order_numb,
             order_date
             from customers, orders
             Where customers.customer_numb =
             orders.customer_numb



Bookstore2               SQL200 Module 2       13




               Inner Join with Result




Bookstore2               SQL200 Module 2       14




                                                    7
Inner Join (New Syntax)

             Basic SQL 92 Syntax:
             Select <column-list>
             From <table1>
             Inner join <table2>
             On <join condition>

Bookstore2                SQL200 Module 2   15




                        Inner Join

             Basic Example:
             SELECT customer_first_name,
             customer_street, order_numb,
             order_date
             from customers
             inner join orders
             on customers.customer_numb =
             orders.customer_numb

Bookstore2                SQL200 Module 2   16




                                                 8
Inner Join with Result




Bookstore2           SQL200 Module 2            17




 Inner Join over Multiple columns

• Note that that the join condition can apply
  to multiple columns if desired
• Used with composite keys




Bookstore2           SQL200 Module 2            18




                                                     9
Inner Join Result in MS Access




Bookstore2              SQL200 Module 2                19




                     Inner Join

• In the last example…
      – What was the cardinality of the relationship
        between customers and orders?
      – Which table was the parent?
      – What was it’s primary key?
      – In which table did we employ a foreign key
        and what was it?


Bookstore2              SQL200 Module 2                20




                                                            10
Cross Join
• What happens when you omit a join
  expression?
• Get the cartesian product of the tables – all
  possible combinations of the two tables
• For large tables this will run a long time!



Bookstore2                  SQL200 Module 2       21




             Cross Join Result Set in MS Access




Bookstore2                  SQL200 Module 2       22




                                                       11
Additional SQL92 Syntax
• Table1 natural join table3 – automatically
  uses columns with same name
• Table 1 natural join table2 using(<column-
  list>
• Not yet widely available in commercial
  implementations


Bookstore2           SQL200 Module 2           23




    Joining More than Two Tables
• Can join several tables in one select
• Try to limit to three or four
• Join order can be important for
  performance (although optimizers will
  usually handle this for you)
• Use parentheses to force order of
  evaluation (also vendor extensions, often
  called “hints”)

Bookstore2           SQL200 Module 2           24




                                                    12
Joining More than Two Tables
• Add orderlines detail to previous queries
  SELECT customer_first_name, customer_street,
  orders.order_numb, orders.order_date,
  orderlines.isbn, orderlines.quantity
  FROM customers
  INNER JOIN orders ON
  customers.customer_numb=orders.customer_numb
  INNER JOIN orderlines
  on orders.order_numb = orderlines.order_numb

Bookstore2           SQL200 Module 2             25




      Multi-table Join with Results




Bookstore2           SQL200 Module 2             26




                                                      13
MS Access Multi-table Join Result Set




Bookstore2              SQL200 Module 2              27




                 On Your Own
• Add the book title to the previous query
  results
• Hint: add another join to books table




                                                          14
Sample Database

• Before we continue (Access classes
  only)…
• Create a new employees table




Bookstore2              SQL200 Module 2   29




  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;



Bookstore2              SQL200 Module 2   30




                                               15
Self Joins
• Implements a recursive relationship
• Important in various applications
      –   Parts lists/assemblies
      –   HR
      –   Etc.
      –   Table joined to itself using correlation names



Bookstore2                SQL200 Module 2                  31




                       Self Joins

             SELECT e.*, m.name
             FROM employees AS e, employees
             AS m
             WHERE e.managerid =
             m.employeeid;




Bookstore2                SQL200 Module 2                  32




                                                                16
Bookstore2                SQL200 Module 2                 33




                     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


Bookstore2                SQL200 Module 2                 34




                                                               17
Left Outer Join

             Basic SQL 92 Syntax:
             Select <column-list>
             From <table1>
             Left join <table2>
             On <join condition>

Bookstore2                SQL200 Module 2   35




                        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

Bookstore2                SQL200 Module 2   36




                                                 18
Bookstore2           SQL200 Module 2   37




             Left Join with Results




Bookstore2           SQL200 Module 2   38




                                            19
SQL200

                 SQL Programming

                Part 2– Subqueries, Unions


Bookstore2              SQL200 Module 2                  39




                    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

Bookstore2              SQL200 Module 2              40




                                                              20
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’);
Bookstore2          SQL200 Module 2   41




 Uncorrelated Subquery with Results




Bookstore2          SQL200 Module 2   42




                                           21
Negative Subquery
• A type of subquery that matches “not
  found” conditions




Bookstore2          SQL200 Module 2      43




             Negative Subquery

         select isbn, quantity
         from orderlines
         where order_numb not in
         (select order_numb from
         orders where order_date
         between ‘1/1/99’ and
         ‘12/31/99’);
Bookstore2          SQL200 Module 2      44




                                              22
Negative Subquery with Results




Bookstore2          SQL200 Module 2                  45




 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




Bookstore2          SQL200 Module 2                  46




                                                          23
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’);

    This type of query covered in intermediate SQL class
Bookstore2                  SQL200 Module 2                47




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




Bookstore2                  SQL200 Module 2                48




                                                                24
Unions

      Select <column-list> from
      <table1>
      Union [ALL]
      Select <same-columns> from
      <table2>



Bookstore2              SQL200 Module 2   49




                    Unions

             select *
             from employees
             union all
             select *
             from employees_copy


Bookstore2              SQL200 Module 2   50




                                               25
Results of Union query




Bookstore2                SQL200 Module 2         51




                       SQL200

                   SQL Programming

              Part 3 – Calculations, Aggregates


Bookstore2                 SQL200 Module 2        52




                                                       26
Calculated Fields
• Can add a column calculated from others


             SELECT order_numb, quantity,
             cost_each,
             quantity*cost_each as
             extension
             FROM orderlines

Bookstore2             SQL200 Module 2      53




      Calculated field in the Result




Bookstore2             SQL200 Module 2      54




                                                 27
Bookstore2          SQL200 Module 2    55




             String Manipulation
•   Concatenation
•   Trim
•   Substring
•   Upper, Lower
•   Etc. (various vendor extensions)



Bookstore2          SQL200 Module 2    56




                                            28
Concatenation
• Used for concatenated keys
• Useful to format reports

             Basic syntax:

              (Access) Field1 & Field2
              (Oracle, std) Field1 || Field2
              (Sql Server) Field1 + Field2

Bookstore2                SQL200 Module 2      57




                   Concatenation

  select customer_first_name
  + ‘ ‘ +
  trim(customer_last_name)
  as Name
  from customers


Bookstore2                SQL200 Module 2      58




                                                    29
Bookstore2               SQL200 Module 2   59




                  Date Functions
• Numerous date functions
• Often vendor specific
• Often used:
      –   year
      –   month
      –   DateAdd, DateDiff, DatePart
      –   getdate()
• Ex: where year(order_date) = 1999
Bookstore2               SQL200 Module 2   60




                                                30
Aggregate Functions
•   Count
•   Sum
•   Min
•   Max
•   Avg
•   Often used in conjunction with grouping

Bookstore2                   SQL200 Module 2          61




               Aggregate Functions

             Basic syntax:

             Select <function>(<column>)
             From <table>
             Group by <column-list>
             Having <predicate>

             Group by all columns to left of one(s)
             you want to aggregate
Bookstore2                   SQL200 Module 2          62




                                                           31
Aggregate Functions
     SELECT order_numb, Count(*) AS
     [Number of Order Lines] ,
     Sum(quantity) AS [Total Quantity],
     Sum(quantity * cost_each) AS [Total
     Amount]
     FROM order_lines
     GROUP BY order_numb
     having count(*)    > 1;



Bookstore2         SQL200 Module 2         63




Bookstore2         SQL200 Module 2         64




                                                32
Having vs. Where
• Having and Where clauses are similar but
  not the same
• Having removes groups after they are
  formed
• Where removes rows before groups are
  formed


Bookstore2              SQL200 Module 2               65




                      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


Bookstore2              SQL200 Module 2               66




                                                           33
Exercise Result




                                   [end module]
Bookstore2       SQL200 Module 2                  67




                 Notes




Bookstore2       SQL200 Module 2                  68




                                                       34
SQL/200

                     SQL Programming

            Workshop 3 – Modifying Data, Managing the
                           Database
Bookstore                   SQL200 Module 3                  1




             Note on SQL200 Slides
    • These slides were originally designed to support the
      single SQL200 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 slides
      and the MS Access slides out into their own slide
      sets. These SQL200 slides (used in SQL202 as well
      as SQL200) will focus on Microsoft SQL Server.


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


Bookstore2                              SQL200 Module 2         3




      SQL200 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.


Bookstore                               SQL200 Module 3         4




                                                                    2
Note on SQL200 Slides
    • These slides were originally designed to support the
      single SQL200 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 slides
      and the MS Access slides out into their own slide
      sets. The SQL200 slides will cover MySQL and
      SQL Server which are virtually identical for
      purposes of this course.

Bookstore2                SQL200 Module 2                    5




              SQL200 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                 SQL212 Module 1                    6




                                                                 3
SQL200 Module 3
•   Part 1 – Modifying Data
•   Part 2 – Managing Database Structures
•   Part 3 – Creating Views and Indexes
•   Part 4 -- Security




Bookstore            SQL200 Module 3        7




                 SQL/200

              SQL Programming

              Part 1 – Modifying Data


Bookstore            SQL200 Module 3        8




                                                4
Relational Database with constraints (from text)




Bookstore                  SQL200 Module 3                  9




     Data Modification Statements

                 • Insert

                 • Update

                 • Delete


Bookstore                  SQL200 Module 3                 10




                                                                5
Data Modification Statements

            • End-user rarely sees these
              statements

            • Application developer prepares
              these statements “behind the
              scenes” based on forms filled out
              by user



Bookstore                 SQL200 Module 3         11




                          Insert
• Adds new rows to an existing table
• Two forms:
      – Single Row
      – Multi-Row




Bookstore                 SQL200 Module 3         12




                                                       6
Single Row Insert


             Basic Syntax:
             Insert [into] <table-name>
             Values (<value-list>)




Bookstore                 SQL200 Module 3      13




                 Single Row Insert

            Basic Example:
            insert into sources(source_numb,
            source_name, source_street)
            values(22,'Specialty Books',
            'Canal Street')




Bookstore                 SQL200 Module 3      14




                                                    7
Insert Statement




Bookstore            SQL200 Module 3     15




            Sources table after Insert




Bookstore            SQL200 Module 3     16




                                              8
Multi-row Insert
            Basic Syntax:


            Insert [into] <table-name>
            Select <select-statement>


            We will do this after creating a new
            table later in this module
Bookstore                 SQL200 Module 3          17




                         Update
• Updates fields in an existing row

   Basic Syntax:
   Update <table-name>
   Set <field1> = new value, <field2> = new
   value,…
   Where <selection-criteria>
Bookstore                 SQL200 Module 3          18




                                                        9
Update
• Increase Ingram prices by 10%

   Example:
   Update books
   Set retail_price = retail_price
   *1.10
   Where source_numb = 1
Bookstore         SQL200 Module 3    19




  Ingram Book Prices before Update




Bookstore         SQL200 Module 3    20




                                          10
Ingram Book Prices after Update




Bookstore                SQL200 Module 3   21




       After update in MS Access




Bookstore                SQL200 Module 3   22




                                                11
Delete
• Deletes one or more rows

            Basic Syntax:


            Delete from <table-name>
            Where <selection-criteria>


Bookstore                   SQL200 Module 3   23




                            Delete

            Example:


            Delete from sources
            Where source_numb = 22


Bookstore                   SQL200 Module 3   24




                                                   12
Delete




Bookstore             SQL200 Module 3    25




            Sources table after Delete




Bookstore             SQL200 Module 3    26




                                              13
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

Bookstore                      SQL200 Module 3            27




                           SQL/200

                       SQL Programming

               Part 2– Managing Database Structures


Bookstore                      SQL200 Module 3            28




                                                               14
DDL
• Create
• Alter
• Drop




Bookstore                 SQL200 Module 3                 29




                       Schemas
• Logical view of a database; sort of a “sub-
  database” – we will not cover these in this
  module or…
      – Catalogs
      – Clusters
      – Domains (somewhat like a user defined datatype)
• These topics are highly dependent upon the
  vendor DBMS and installation practices


Bookstore                 SQL200 Module 3                 30




                                                               15
Tables

            • Base tables
            • Temporary tables
                – Local (or module scope)
                – Global (session scope)




Bookstore                   SQL200 Module 3   31




                    Creating Tables
• Use create statement
• Specify:
      – Columns with data types and column
        constraints
      – Table constraints
            • Foreign key references
            • Primary key designation


Bookstore                   SQL200 Module 3   32




                                                   16
Data Types
• Int – integers or whole numbers
      – Ex: how_many int
• Char – fixed length fields
      – Ex: state char(2)
• Varchar/Varchar2 – variable length fields
      – Ex: address varchar(35)
• Money – money field; same as MS Access
  currency
• Date/Datetime – date and time
• And many others – see documentation or Help
Bookstore                   SQL200 Module 3     33




                     Create Table
     Basic syntax:
     Create table <table-name>
     <column1> <datatype> <constraints>
     ,.. <column1> <datatype> <constraints>
     …
     <table constraints>
     Note: often preceded by a drop
Bookstore                   SQL200 Module 3     34




                                                     17
Temporary Tables

    Basic syntax (SQL standard):
    Create [global] temporary table <table-name>
    <rest of statement as for normal create>


    Note: SQL Server uses a different syntax. Just put
    a #in front of the table name as in #mytable.

Bookstore               SQL200 Module 3                  35




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



Bookstore               SQL200 Module 3                  36




                                                              18
Table Constraints
• Primary Key
• Foreign Key
• Compare fields against each other. I.e.
  ship_date >= order_date




Bookstore                SQL200 Module 3    37




    But first – the Drop Statement
• Deletes a database “object”
      –     Drop table <table-name>
      –     Drop view <view-name>
      –     Drop index <index-name>
      –     Drop domain <domain-name>




Bookstore                SQL200 Module 3    38




                                                 19
Create Table
       Example 1: Create a summary table
       Create table summary(
       isbn varchar(20) primary key,
       How_many int check (how_many >= 0),
       Constraint isbn_fk
       Foreign key (isbn) references
       books(isbn)
       )
Bookstore             SQL200 Module 3        39




            Create Summary Table




Bookstore             SQL200 Module 3        40




                                                  20
Constraints on Summary Table




Bookstore                SQL200 Module 3   41




                Multi-row Insert


            Basic Syntax:


            Insert [into] <table-name>
            [(<column list>)]
            Select <select-statement>


Bookstore                SQL200 Module 3   42




                                                21
Multi-row Insert
            Basic Example: (store # times each
            book ordered)


            Insert into summary
            Select isbn, count(*)
            From orderlines
            Group by isbn;

Bookstore                   SQL200 Module 3      43




                  Multi-row Insert




Bookstore                   SQL200 Module 3      44




                                                      22
After multi-row insert in MS Access




Bookstore                 SQL200 Module 3                45




                      SQL/200

                   SQL Programming

        Part 3 – Creating Views and Indexes, Modifying
                           Structures
Bookstore                  SQL200 Module 3               46




                                                              23
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




Bookstore               SQL200 Module 3      47




                        Views

   Basic syntax:
   Create view <view-name> (<column-list>)
   As
   <select statement>




Bookstore               SQL200 Module 3      48




                                                  24
Creating a View




Bookstore                SQL200 Module 3           49




                     Using Views
• Can be used like a table subject to various
  limitations
      – Cannot insert into grouped queries, etc.
      – Etc.
• Sample syntax:
            select column-list
            from employee_view

Bookstore                SQL200 Module 3           50




                                                        25
Using a View




Bookstore              SQL200 Module 3      51




                      Indexes
• Used to speed searches, joins, etc.
• Placed on:
      – primary and foreign keys
      – Secondary keys
• In commercial practice often managed by
  DBA’s for large databases


Bookstore              SQL200 Module 3      52




                                                 26
Indexes
    Basic syntax:


    Create [unique] index <index-name>
    On <table-name> (field-name> [desc])


    Note: can place index on a composite key; ex: state and
    city

Bookstore                 SQL200 Module 3                     53




                        Indexes

      Basic example:


      create index state_inx
      on customers(customer_state)




Bookstore                 SQL200 Module 3                     54




                                                                   27
Customers table with index




Bookstore             SQL200 Module 3         55




             Dropping an index
Basic Syntax:
      – Drop index <table-name.index-name>;




Bookstore             SQL200 Module 3         56




                                                   28
Modifying a Table Design
• Applies to tables
• Use ALTER statement
      –     Add columns
      –     Delete columns
      –     Rename columns
      –     Add column constraints
      –     Add table constraints

Bookstore                  SQL200 Module 3   57




            Modifying a Table Design
      Basic syntax:
      Alter <table-name>
      Add <field-name>,
      Add <table-constraint>,
      Modify <field-name>
      Etc.

Bookstore                  SQL200 Module 3   58




                                                  29
Modify a Table Design

        Example: add a phone number field


        alter table publishers
        add phone char(12);




Bookstore               SQL200 Module 3     59




After alter publishers table




Bookstore               SQL200 Module 3     60




                                                 30
SQL/200

                 SQL Programming

                    Part 4 – Security


Bookstore               SQL200 Module 3           61




                      Security
• Important DBA function
      – Beyond scope of this course
      – Typically controlled through Enterprise
        Manager or Studio GUI’s
• In commercial practice application security
  frequently controlled via own login and a
  “users” table or similar

Bookstore               SQL200 Module 3           62




                                                       31
Security
•   Specifics can vary by product
•   Access: workgroup administrator
•   SQL Server: users, roles
•   Oracle: users, roles




Bookstore            SQL200 Module 3   63




            SQL Security Statements


              • Grant
              • Revoke
              • Deny




Bookstore            SQL200 Module 3   64




                                            32
Grant
    Syntax:


    Grant <access-right> [with grant option]
    On <object> to <user>

    Note: by default only tables owners and admins can access
    a table. Others must be granted the relevant rights.
Bookstore                  SQL200 Module 3                      65




                   Access Rights
•    Select
•    Update
•    Insert
•    Delete
•    References
•    All privileges

Bookstore                  SQL200 Module 3                      66




                                                                     33
Grant

     Example:


     Grant update
     On employees to ddurso



Bookstore           SQL200 Module 3                  67




                 Revoke
• Revokes the rights
• Syntax similar to grant




                                      [end module]
Bookstore           SQL200 Module 3                  68




                                                          34
Orange Coast Database Associates Course                                               (800)355-9855 or http://ocdatabases.itgo.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 B-4A
                                                     San Juan Capistrano, CA
                             (800)355-9855 (Toll Free) | (949)489-1472 (Direct) | (949)485-6284 (Fax)
                                      http://ocdatabases.itgo.com | info@ocdatabases.itgo.com




Accelerated Computer Training for Working Professionals

Weitere ähnliche Inhalte

Was ist angesagt?

Purna_gorre SQLDBA (1)
Purna_gorre SQLDBA (1)Purna_gorre SQLDBA (1)
Purna_gorre SQLDBA (1)
Gorre Mamatha
 
SQL Sevrer 2008 R2 Overview
SQL Sevrer 2008 R2 OverviewSQL Sevrer 2008 R2 Overview
SQL Sevrer 2008 R2 Overview
Mark Kromer
 
Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1
guestd54e35
 
Resume_Tushar_Kanti_DBA
Resume_Tushar_Kanti_DBAResume_Tushar_Kanti_DBA
Resume_Tushar_Kanti_DBA
Tushar Kanti
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
Kaing Menglieng
 
What's New in MySQL 5.6
What's New in MySQL 5.6What's New in MySQL 5.6
What's New in MySQL 5.6
Santo Leto
 
KoprowskiT - SQLBITS X - 2am a disaster just began
KoprowskiT - SQLBITS X - 2am a disaster just beganKoprowskiT - SQLBITS X - 2am a disaster just began
KoprowskiT - SQLBITS X - 2am a disaster just began
Tobias Koprowski
 
Newsletter December09
Newsletter December09Newsletter December09
Newsletter December09
guest50e0c5
 

Was ist angesagt? (20)

Purna_gorre SQLDBA (1)
Purna_gorre SQLDBA (1)Purna_gorre SQLDBA (1)
Purna_gorre SQLDBA (1)
 
KoprowskiT_SQLRelay2014#9_London_FromPlanToBackupToCloud
KoprowskiT_SQLRelay2014#9_London_FromPlanToBackupToCloudKoprowskiT_SQLRelay2014#9_London_FromPlanToBackupToCloud
KoprowskiT_SQLRelay2014#9_London_FromPlanToBackupToCloud
 
MySQL Features & Implementation
MySQL Features & ImplementationMySQL Features & Implementation
MySQL Features & Implementation
 
An overview of microsoft data mining technology
An overview of microsoft data mining technologyAn overview of microsoft data mining technology
An overview of microsoft data mining technology
 
SQL Sevrer 2008 R2 Overview
SQL Sevrer 2008 R2 OverviewSQL Sevrer 2008 R2 Overview
SQL Sevrer 2008 R2 Overview
 
VinayKumar_Sirikonda
VinayKumar_SirikondaVinayKumar_Sirikonda
VinayKumar_Sirikonda
 
An overview of Microsoft data mining technology
An overview of Microsoft data mining technologyAn overview of Microsoft data mining technology
An overview of Microsoft data mining technology
 
Sql server 2012 roadshow masd overview 003
Sql server 2012 roadshow masd overview 003Sql server 2012 roadshow masd overview 003
Sql server 2012 roadshow masd overview 003
 
Mohamed cv
Mohamed cvMohamed cv
Mohamed cv
 
KoprowskiT_SQLRelay2014#1_Reading_FromPlanToBackupToCloud
KoprowskiT_SQLRelay2014#1_Reading_FromPlanToBackupToCloudKoprowskiT_SQLRelay2014#1_Reading_FromPlanToBackupToCloud
KoprowskiT_SQLRelay2014#1_Reading_FromPlanToBackupToCloud
 
Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1
 
KoprowskiT_Session2_SDNEvent_SourceControlForDBA
KoprowskiT_Session2_SDNEvent_SourceControlForDBAKoprowskiT_Session2_SDNEvent_SourceControlForDBA
KoprowskiT_Session2_SDNEvent_SourceControlForDBA
 
Resume_Tushar_Kanti_DBA
Resume_Tushar_Kanti_DBAResume_Tushar_Kanti_DBA
Resume_Tushar_Kanti_DBA
 
State of the art of MySQL replication and clustering
State of the art of MySQL replication and clusteringState of the art of MySQL replication and clustering
State of the art of MySQL replication and clustering
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
What's New in MySQL 5.6
What's New in MySQL 5.6What's New in MySQL 5.6
What's New in MySQL 5.6
 
Nadzor sql a
Nadzor sql aNadzor sql a
Nadzor sql a
 
KoprowskiT - SQLBITS X - 2am a disaster just began
KoprowskiT - SQLBITS X - 2am a disaster just beganKoprowskiT - SQLBITS X - 2am a disaster just began
KoprowskiT - SQLBITS X - 2am a disaster just began
 
MySQL 开发
MySQL 开发MySQL 开发
MySQL 开发
 
Newsletter December09
Newsletter December09Newsletter December09
Newsletter December09
 

Andere mochten auch

Social enter strategic planning
Social enter strategic planningSocial enter strategic planning
Social enter strategic planning
Tarek Fahim
 
Neon Something Different
Neon   Something DifferentNeon   Something Different
Neon Something Different
fondas vakalis
 
081223-“明星制造”百脑汇高校才艺大赛
081223-“明星制造”百脑汇高校才艺大赛081223-“明星制造”百脑汇高校才艺大赛
081223-“明星制造”百脑汇高校才艺大赛
buynow
 
Social networking and internet security
Social networking and internet securitySocial networking and internet security
Social networking and internet security
Frank Brunke
 
Buenas Fotos Mal Fondo
Buenas Fotos Mal FondoBuenas Fotos Mal Fondo
Buenas Fotos Mal Fondo
fondas vakalis
 
From Neo to Trinity: The Matrix Reinvented
From Neo to Trinity: The Matrix ReinventedFrom Neo to Trinity: The Matrix Reinvented
From Neo to Trinity: The Matrix Reinvented
The Difference Engine
 
Marketing Overview 1
Marketing Overview 1Marketing Overview 1
Marketing Overview 1
Alison Murray
 

Andere mochten auch (20)

Rockets
RocketsRockets
Rockets
 
Volcano Powerpt
Volcano PowerptVolcano Powerpt
Volcano Powerpt
 
Cloud Computing Sun Microsystems
Cloud Computing Sun MicrosystemsCloud Computing Sun Microsystems
Cloud Computing Sun Microsystems
 
Samantha Resume
Samantha ResumeSamantha Resume
Samantha Resume
 
Social enter strategic planning
Social enter strategic planningSocial enter strategic planning
Social enter strategic planning
 
Neon Something Different
Neon   Something DifferentNeon   Something Different
Neon Something Different
 
Nice Travel
Nice TravelNice Travel
Nice Travel
 
081223-“明星制造”百脑汇高校才艺大赛
081223-“明星制造”百脑汇高校才艺大赛081223-“明星制造”百脑汇高校才艺大赛
081223-“明星制造”百脑汇高校才艺大赛
 
Lips & Mouth
Lips & MouthLips & Mouth
Lips & Mouth
 
How to find new Music
How to find new MusicHow to find new Music
How to find new Music
 
Social networking and internet security
Social networking and internet securitySocial networking and internet security
Social networking and internet security
 
How to Do Lean Planning (and what does that mean anyway)
How to Do Lean Planning (and what does that mean anyway)How to Do Lean Planning (and what does that mean anyway)
How to Do Lean Planning (and what does that mean anyway)
 
Tamkeen capital investment model 2013
Tamkeen capital investment model 2013Tamkeen capital investment model 2013
Tamkeen capital investment model 2013
 
AIA101.4.Automating Access
AIA101.4.Automating AccessAIA101.4.Automating Access
AIA101.4.Automating Access
 
Buenas Fotos Mal Fondo
Buenas Fotos Mal FondoBuenas Fotos Mal Fondo
Buenas Fotos Mal Fondo
 
Hurricanes &amp; Tornados
Hurricanes &amp; TornadosHurricanes &amp; Tornados
Hurricanes &amp; Tornados
 
Laila
LailaLaila
Laila
 
SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3SQL212.3 Introduction to SQL using Oracle Module 3
SQL212.3 Introduction to SQL using Oracle Module 3
 
From Neo to Trinity: The Matrix Reinvented
From Neo to Trinity: The Matrix ReinventedFrom Neo to Trinity: The Matrix Reinvented
From Neo to Trinity: The Matrix Reinvented
 
Marketing Overview 1
Marketing Overview 1Marketing Overview 1
Marketing Overview 1
 

Ähnlich wie SQL202 SQL Server SQL Manual

6232 b 01
6232 b 016232 b 01
6232 b 01
stamal
 
Kb 40 kevin_klineukug_reading20070717[1]
Kb 40 kevin_klineukug_reading20070717[1]Kb 40 kevin_klineukug_reading20070717[1]
Kb 40 kevin_klineukug_reading20070717[1]
shuwutong
 
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
andythiru
 
Dynamic sql for efficient searching
Dynamic sql for efficient searchingDynamic sql for efficient searching
Dynamic sql for efficient searching
damienjoyce
 
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
Andrew Brust
 
Bb performance-engineering-toad
Bb performance-engineering-toadBb performance-engineering-toad
Bb performance-engineering-toad
Steve Feldman
 

Ähnlich wie SQL202 SQL Server SQL Manual (20)

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 1
SQL302 Intermediate SQL Workshop 1SQL302 Intermediate SQL Workshop 1
SQL302 Intermediate SQL Workshop 1
 
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...
 
Oracle sql demo
Oracle sql demoOracle sql demo
Oracle sql demo
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL Design
 
FatDB Intro
FatDB IntroFatDB Intro
FatDB Intro
 
6232 b 01
6232 b 016232 b 01
6232 b 01
 
Ora 4 the_sqldba
Ora 4 the_sqldbaOra 4 the_sqldba
Ora 4 the_sqldba
 
Sql data base
Sql data baseSql data base
Sql data base
 
Manageability Enhancements of SQL Server 2012
Manageability Enhancements of SQL Server 2012Manageability Enhancements of SQL Server 2012
Manageability Enhancements of SQL Server 2012
 
Kb 40 kevin_klineukug_reading20070717[1]
Kb 40 kevin_klineukug_reading20070717[1]Kb 40 kevin_klineukug_reading20070717[1]
Kb 40 kevin_klineukug_reading20070717[1]
 
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
 
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
 
Dynamic sql for efficient searching
Dynamic sql for efficient searchingDynamic sql for efficient searching
Dynamic sql for efficient searching
 
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012SQL Server Workshop for Developers - Visual Studio Live! NY 2012
SQL Server Workshop for Developers - Visual Studio Live! NY 2012
 
MySQL 8: Ready for Prime Time
MySQL 8: Ready for Prime TimeMySQL 8: Ready for Prime Time
MySQL 8: Ready for Prime Time
 
Topic1
Topic1Topic1
Topic1
 
Performance Eye for the SQL Guy
Performance Eye for the SQL GuyPerformance Eye for the SQL Guy
Performance Eye for the SQL Guy
 
Bb performance-engineering-toad
Bb performance-engineering-toadBb performance-engineering-toad
Bb performance-engineering-toad
 
Database as a Service on the Oracle Database Appliance Platform
Database as a Service on the Oracle Database Appliance PlatformDatabase as a Service on the Oracle Database Appliance Platform
Database as a Service on the Oracle Database Appliance Platform
 

Mehr von Dan D'Urso

Course Catalog
Course CatalogCourse Catalog
Course Catalog
Dan D'Urso
 

Mehr von Dan D'Urso (20)

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
 
AIN106 Access Reporting and Analysis
AIN106 Access Reporting and AnalysisAIN106 Access Reporting and Analysis
AIN106 Access Reporting and Analysis
 
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 3
 
SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL Workshop 2SQL302 Intermediate SQL Workshop 2
SQL302 Intermediate SQL Workshop 2
 
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
 
AIN102 Microsoft Access Queries
AIN102 Microsoft Access QueriesAIN102 Microsoft Access Queries
AIN102 Microsoft Access Queries
 
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
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

SQL202 SQL Server SQL Manual

  • 1. Orange Coast Database Associates Course (800)355-9855 or http://ocdatabases.itgo.com SQL202 Accelerated Introduction to 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://ocdatabases.itgo.com San Juan Capistrano, CA (800)355-9855 Accelerated Computer Training for Working Professionals Bookstore Case
  • 2. Welcome to SQL202 – Accelerated Introduction to SQL Using MS SQL Server An accelerated introduction to SQL for non- programmers P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com Bookstore SQL202 1 Accelerated Introduction to 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 SQL202 2 1
  • 3. SQL Curriculum SQL201W SQL202 SQL212 MySQL Transact-SQL Oracle SQL200* * = included in above courses SQL200S* Bookstore SQL202 3 Accelerated Introduction to SQL • Assumes no prior knowledge of SQL • Quick pace for experienced computer users • End-user, not programmer, oriented • Focus is on SQL, not Management Studio • SQL200s is first two modules of SQL200, otherwise identical. Bookstore SQL202 4 2
  • 4. Accelerated Introduction to SQL SQL Covered (Day 1: All Day): • Select – Basic – Filters – Special Operators – Multi-table retrieval • Joins • Subqueries • Unions – Calculations and Aggregates Bookstore SQL202 5 Accelerated Introduction to SQL SQL Covered (Day 2: AM Only): • Data Updates – Insert – Update – Delete • Data structures – Create – Drop – Alter Bookstore SQL202 6 3
  • 5. Accelerated Introduction to SQL Course Format: • 3 Sessions • Lecture • Demo • Student “hands-on” • Many exercises are cumulative – later examples build on queries created earlier Bookstore SQL202 7 Accelerated Introduction to SQL Course Schedule (“1/2” day sessions): • Session 1 – Basic SQL • Session 2 – Multi-table Retrieval • Session 3 – Modifying Data Bookstore SQL202 8 4
  • 6. SQL200 Based on SQL Clearly Explained by Jan Harrington SQL Programming Module 1 – Relational Database Background, Basic Single Table Retrieval Operations Bookstore SQL200 Module 1 1 Note on SQL200 Slides • These slides were originally designed to support the single SQL200 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 slides and the MS Access slides out into their own slide sets. The SQL200 slides will cover MySQL and SQL Server which are virtually identical for purposes of this course. Bookstore2 SQL200 Module 2 2 1
  • 7. 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 SQL200 Module 2 3 SQL200 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. Bookstore2 SQL200 Module 2 4 2
  • 8. SQL200 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 SQL212 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 SQL200 Module 1 6 3
  • 9. SQL Programming • A basic knowledge of query systems, perhaps via MS Access, or some programming knowledge, is desirable • We will use GUI tools or SQL Plus almost exclusively Bookstore SQL200 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 SQL200 Module 1 8 4
  • 10. Relational Database Basics • Storage • Indexes • Databases • Views • Tables • Cursors • Rows • Application interfaces • Columns Bookstore SQL200 Module 1 9 Relational Database Table Bookstore SQL200 Module 1 10 5
  • 11. Constraints • Database • Other Business Rule – Domain – Triggers – Uniqueness – Stored Procedures – Relationship Cardinality • 1 to 1 • 1 to N Bookstore SQL200 Module 1 11 Relational Database with constraints Bookstore SQL200 Module 1 12 6
  • 12. Database Management Systems Positioning Chart Cost VLDB Enterprise Workgroup Single user Spreadsheet # Users Bookstore SQL200 Module 1 13 System Architecture File Server Architecture Access MDB Access Bookstore SQL200 Module 1 14 7
  • 13. System Architecture Client/Server Architecture Oracle SQL DB Visual Access Basic App Bookstore SQL200 Module 1 15 System Architecture Web Architecture Web Oracle Server DB SQL Browser Bookstore SQL200 Module 1 16 8
  • 14. Approaching SQL • Relatively simple • Two main environments – Interactive (This course) – Embedded • Static (Compiled) • Dynamic Bookstore SQL200 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 SQL200 Module 1 18 9
  • 15. SQL Conformance • Entry • Intermediate • Advanced • Most are at least entry level Bookstore SQL200 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 Bookstore SQL200 Module 1 20 10
  • 16. 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 SQL200 Module 1 21 SQL DCL • Data Control Language (DDL) – Grant – Revoke – Deny – Constraints Bookstore SQL200 Module 1 22 11
  • 17. SQL DML • Data Manipulation Language (DML) – Select – Insert – Update – Delete Bookstore SQL200 Module 1 23 SQL Statement Processing Parse Validate Optimize Access Plan Execute Bookstore SQL200 Module 1 24 12
  • 18. Bookstore Sample Database • Before we continue (note: instructor may have already done this)… • Load the sample database if you haven’t already – Use Access import table feature, or – Run SQL script, or – Use Access upsizing wizard Bookstore SQL200 Module 1 25 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 SQL200 Module 1 26 13
  • 19. 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 SQL200 Module 1 27 SELECT Basic Syntax (Projection): Select <column-list> or <*> From <table-list> Bookstore SQL200 Module 1 28 14
  • 20. SELECT Basic Example (Projection): select customer_last_name, customer_street from customers Bookstore SQL200 Module 1 29 MS Access SQL Query Bookstore SQL200 Module 1 30 15
  • 21. Bookstore SQL200 Module 1 31 SQL Server Query Bookstore SQL200 Module 1 32 16
  • 22. SELECT with Where Clause Example (Restriction plus Projection): Select <column-list> From <table-list> Where <selection-criteria>; Bookstore SQL200 Module 1 33 Comparison Operators • < less than • > greater than • <= less than or equal to • >= greater than or equal to • <> or != two forms for not equal Bookstore SQL200 Module 1 34 17
  • 23. SELECT with Where Basic Example (Restriction plus Projection): select customer_last_name, customer_street from customers where customer_last_name = ‘Jones’ Bookstore SQL200 Module 1 35 Select with Where Bookstore SQL200 Module 1 36 18
  • 24. On Your Own • Find books written by Mark Twain • Show title, publisher, year Bookstore SQL200 Module 1 37 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 SQL200 Module 1 38 19
  • 25. Select with Complex Where Bookstore SQL200 Module 1 39 Complex Where Result Bookstore SQL200 Module 1 40 20
  • 26. Special Operators • Can be used in where clause • LIKE • IN • BETWEEN • IS NULL Bookstore SQL200 Module 1 41 Like (“Wild Card Matches”) • ANSI • Access • Where • Where customer_last_name customer_last_name like ‘Jo%’ like “Jo*” • Like ‘Jo_’ • Like “Jo?” Bookstore SQL200 Module 1 42 21
  • 27. IN Select * From customers Where customer_last_name in (‘Rizzo’, ‘Jones’, ‘Garcia’) The list in parentheses can be replaced by a subquery. We will study this later. Bookstore SQL200 Module 1 43 SQL Where Clause with IN Bookstore SQL200 Module 1 44 22
  • 28. IS NULL SQL uses three valued logic. Must use IS NULL to test for unknowns. A null is NOT the same as blank or empty. Select * From customers Where customer_street IS NULL Bookstore SQL200 Module 1 45 On Your Own • Find all customers with an address not equal to 4592 Maple Lane • Was Peter Johnson selected? • Why or why not? Bookstore SQL200 Module 1 46 23
  • 29. BETWEEN Select * From orders Where order_date BETWEEN ‘1- Jan-99’ and ’31-Dec-99’ Note: date formats vary from product to product. Bookstore SQL200 Module 1 47 Where with Between Bookstore SQL200 Module 1 48 24
  • 30. Removing Duplicates List once each city in which there are customers Select DISTINCT customer_city From customers Removes duplicate rows from result set Bookstore SQL200 Module 1 49 Removing Duplicates Bookstore SQL200 Module 1 50 25
  • 31. Sorting – ORDER BY Basic syntax: Select <column list> From <table list> Where <selection criteria> Order by <column list> [DESC] DESC will sort in descending order Bookstore SQL200 Module 1 51 Sorting – ORDER BY Example: List all records sorted by state, city Select * From customers Order by customer_state, customer_city Bookstore SQL200 Module 1 52 26
  • 32. Sorting Results with Order By Bookstore SQL200 Module 1 53 Selecting Top Records List largest 5 zips or top 25 % of them… Select Top 5 (or top 25 percent) Customer_last_name , contact_zip From customers Order by customer_zip desc; Bookstore SQL200 Module 1 54 27
  • 33. SQL Exercises • List all books whose publisher name begins with “H” or “T”; sort by title [hint: use LIKE] • List all customers whose last name ends with “S”; sort by state, city, last name • Find the order numbers of orders with order dates in 1999; sort by order #. [Hint: use BETWEEN] • Find the order numbers and order dates of all orders with a “2” in column 2 of the credit card #; sort by order date descending Bookstore SQL200 Module 1 [end module] 55 Notes Bookstore SQL200 Module 1 56 28
  • 34. SQL200 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping Bookstore2 SQL200 Module 2 1 Note on SQL200 Slides • These slides were originally designed to support the single SQL200 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 slides and the MS Access slides out into their own slide sets. The SQL200 slides will cover MySQL and SQL Server which are virtually identical for purposes of this course. Bookstore2 SQL200 Module 2 2 1
  • 35. 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 SQL200 Module 2 3 SQL200 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-20011 All rights reserved. Bookstore2 SQL200 Module 2 4 2
  • 36. SQL200 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 SQL212 Module 1 5 SQL200 SQL Programming Part 1 – Joins Bookstore2 SQL200 Module 2 6 3
  • 37. Relational Database with constraints (from text) Bookstore2 SQL200 Module 2 7 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. Bookstore2 SQL200 Module 2 8 4
  • 38. Joins • Inner • Outer – Left – Right – Full • Cross • Self • Theta • We will cover the most important; others as time and interest permit Bookstore2 SQL200 Module 2 9 Bookstore2 SQL200 Module 2 10 5
  • 39. Inner Join • Pairs each row from first table with corresponding row from second table over the “join column” • The result set only contains rows where there is a match over the join column in both tables • Equi-join is the common inner join Bookstore2 SQL200 Module 2 11 Inner Join Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly used Bookstore2 SQL200 Module 2 12 6
  • 40. Inner Join Example using older syntax: SELECT customer_first_name, customer_street, order_numb, order_date from customers, orders Where customers.customer_numb = orders.customer_numb Bookstore2 SQL200 Module 2 13 Inner Join with Result Bookstore2 SQL200 Module 2 14 7
  • 41. Inner Join (New Syntax) Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition> Bookstore2 SQL200 Module 2 15 Inner Join Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date from customers inner join orders on customers.customer_numb = orders.customer_numb Bookstore2 SQL200 Module 2 16 8
  • 42. Inner Join with Result Bookstore2 SQL200 Module 2 17 Inner Join over Multiple columns • Note that that the join condition can apply to multiple columns if desired • Used with composite keys Bookstore2 SQL200 Module 2 18 9
  • 43. Inner Join Result in MS Access Bookstore2 SQL200 Module 2 19 Inner Join • In the last example… – What was the cardinality of the relationship between customers and orders? – Which table was the parent? – What was it’s primary key? – In which table did we employ a foreign key and what was it? Bookstore2 SQL200 Module 2 20 10
  • 44. Cross Join • What happens when you omit a join expression? • Get the cartesian product of the tables – all possible combinations of the two tables • For large tables this will run a long time! Bookstore2 SQL200 Module 2 21 Cross Join Result Set in MS Access Bookstore2 SQL200 Module 2 22 11
  • 45. Additional SQL92 Syntax • Table1 natural join table3 – automatically uses columns with same name • Table 1 natural join table2 using(<column- list> • Not yet widely available in commercial implementations Bookstore2 SQL200 Module 2 23 Joining More than Two Tables • Can join several tables in one select • Try to limit to three or four • Join order can be important for performance (although optimizers will usually handle this for you) • Use parentheses to force order of evaluation (also vendor extensions, often called “hints”) Bookstore2 SQL200 Module 2 24 12
  • 46. Joining More than Two Tables • Add orderlines detail to previous queries SELECT customer_first_name, customer_street, orders.order_numb, orders.order_date, orderlines.isbn, orderlines.quantity FROM customers INNER JOIN orders ON customers.customer_numb=orders.customer_numb INNER JOIN orderlines on orders.order_numb = orderlines.order_numb Bookstore2 SQL200 Module 2 25 Multi-table Join with Results Bookstore2 SQL200 Module 2 26 13
  • 47. MS Access Multi-table Join Result Set Bookstore2 SQL200 Module 2 27 On Your Own • Add the book title to the previous query results • Hint: add another join to books table 14
  • 48. Sample Database • Before we continue (Access classes only)… • Create a new employees table Bookstore2 SQL200 Module 2 29 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; Bookstore2 SQL200 Module 2 30 15
  • 49. Self Joins • Implements a recursive relationship • Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation names Bookstore2 SQL200 Module 2 31 Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid; Bookstore2 SQL200 Module 2 32 16
  • 50. Bookstore2 SQL200 Module 2 33 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 Bookstore2 SQL200 Module 2 34 17
  • 51. Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition> Bookstore2 SQL200 Module 2 35 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 Bookstore2 SQL200 Module 2 36 18
  • 52. Bookstore2 SQL200 Module 2 37 Left Join with Results Bookstore2 SQL200 Module 2 38 19
  • 53. SQL200 SQL Programming Part 2– Subqueries, Unions Bookstore2 SQL200 Module 2 39 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 Bookstore2 SQL200 Module 2 40 20
  • 54. 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’); Bookstore2 SQL200 Module 2 41 Uncorrelated Subquery with Results Bookstore2 SQL200 Module 2 42 21
  • 55. Negative Subquery • A type of subquery that matches “not found” conditions Bookstore2 SQL200 Module 2 43 Negative Subquery select isbn, quantity from orderlines where order_numb not in (select order_numb from orders where order_date between ‘1/1/99’ and ‘12/31/99’); Bookstore2 SQL200 Module 2 44 22
  • 56. Negative Subquery with Results Bookstore2 SQL200 Module 2 45 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 Bookstore2 SQL200 Module 2 46 23
  • 57. 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’); This type of query covered in intermediate SQL class Bookstore2 SQL200 Module 2 47 Unions • Combines two or more tables • Tables must be union compatible Bookstore2 SQL200 Module 2 48 24
  • 58. Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2> Bookstore2 SQL200 Module 2 49 Unions select * from employees union all select * from employees_copy Bookstore2 SQL200 Module 2 50 25
  • 59. Results of Union query Bookstore2 SQL200 Module 2 51 SQL200 SQL Programming Part 3 – Calculations, Aggregates Bookstore2 SQL200 Module 2 52 26
  • 60. Calculated Fields • Can add a column calculated from others SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlines Bookstore2 SQL200 Module 2 53 Calculated field in the Result Bookstore2 SQL200 Module 2 54 27
  • 61. Bookstore2 SQL200 Module 2 55 String Manipulation • Concatenation • Trim • Substring • Upper, Lower • Etc. (various vendor extensions) Bookstore2 SQL200 Module 2 56 28
  • 62. Concatenation • Used for concatenated keys • Useful to format reports Basic syntax: (Access) Field1 & Field2 (Oracle, std) Field1 || Field2 (Sql Server) Field1 + Field2 Bookstore2 SQL200 Module 2 57 Concatenation select customer_first_name + ‘ ‘ + trim(customer_last_name) as Name from customers Bookstore2 SQL200 Module 2 58 29
  • 63. Bookstore2 SQL200 Module 2 59 Date Functions • Numerous date functions • Often vendor specific • Often used: – year – month – DateAdd, DateDiff, DatePart – getdate() • Ex: where year(order_date) = 1999 Bookstore2 SQL200 Module 2 60 30
  • 64. Aggregate Functions • Count • Sum • Min • Max • Avg • Often used in conjunction with grouping Bookstore2 SQL200 Module 2 61 Aggregate Functions Basic syntax: Select <function>(<column>) From <table> Group by <column-list> Having <predicate> Group by all columns to left of one(s) you want to aggregate Bookstore2 SQL200 Module 2 62 31
  • 65. Aggregate Functions SELECT order_numb, Count(*) AS [Number of Order Lines] , Sum(quantity) AS [Total Quantity], Sum(quantity * cost_each) AS [Total Amount] FROM order_lines GROUP BY order_numb having count(*) > 1; Bookstore2 SQL200 Module 2 63 Bookstore2 SQL200 Module 2 64 32
  • 66. Having vs. Where • Having and Where clauses are similar but not the same • Having removes groups after they are formed • Where removes rows before groups are formed Bookstore2 SQL200 Module 2 65 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 Bookstore2 SQL200 Module 2 66 33
  • 67. Exercise Result [end module] Bookstore2 SQL200 Module 2 67 Notes Bookstore2 SQL200 Module 2 68 34
  • 68. SQL/200 SQL Programming Workshop 3 – Modifying Data, Managing the Database Bookstore SQL200 Module 3 1 Note on SQL200 Slides • These slides were originally designed to support the single SQL200 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 slides and the MS Access slides out into their own slide sets. These SQL200 slides (used in SQL202 as well as SQL200) will focus on Microsoft SQL Server. Bookstore SQL200 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 Bookstore2 SQL200 Module 2 3 SQL200 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. Bookstore SQL200 Module 3 4 2
  • 70. Note on SQL200 Slides • These slides were originally designed to support the single SQL200 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 slides and the MS Access slides out into their own slide sets. The SQL200 slides will cover MySQL and SQL Server which are virtually identical for purposes of this course. Bookstore2 SQL200 Module 2 5 SQL200 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 SQL212 Module 1 6 3
  • 71. SQL200 Module 3 • Part 1 – Modifying Data • Part 2 – Managing Database Structures • Part 3 – Creating Views and Indexes • Part 4 -- Security Bookstore SQL200 Module 3 7 SQL/200 SQL Programming Part 1 – Modifying Data Bookstore SQL200 Module 3 8 4
  • 72. Relational Database with constraints (from text) Bookstore SQL200 Module 3 9 Data Modification Statements • Insert • Update • Delete Bookstore SQL200 Module 3 10 5
  • 73. Data Modification Statements • End-user rarely sees these statements • Application developer prepares these statements “behind the scenes” based on forms filled out by user Bookstore SQL200 Module 3 11 Insert • Adds new rows to an existing table • Two forms: – Single Row – Multi-Row Bookstore SQL200 Module 3 12 6
  • 74. Single Row Insert Basic Syntax: Insert [into] <table-name> Values (<value-list>) Bookstore SQL200 Module 3 13 Single Row Insert Basic Example: insert into sources(source_numb, source_name, source_street) values(22,'Specialty Books', 'Canal Street') Bookstore SQL200 Module 3 14 7
  • 75. Insert Statement Bookstore SQL200 Module 3 15 Sources table after Insert Bookstore SQL200 Module 3 16 8
  • 76. Multi-row Insert Basic Syntax: Insert [into] <table-name> Select <select-statement> We will do this after creating a new table later in this module Bookstore SQL200 Module 3 17 Update • Updates fields in an existing row Basic Syntax: Update <table-name> Set <field1> = new value, <field2> = new value,… Where <selection-criteria> Bookstore SQL200 Module 3 18 9
  • 77. Update • Increase Ingram prices by 10% Example: Update books Set retail_price = retail_price *1.10 Where source_numb = 1 Bookstore SQL200 Module 3 19 Ingram Book Prices before Update Bookstore SQL200 Module 3 20 10
  • 78. Ingram Book Prices after Update Bookstore SQL200 Module 3 21 After update in MS Access Bookstore SQL200 Module 3 22 11
  • 79. Delete • Deletes one or more rows Basic Syntax: Delete from <table-name> Where <selection-criteria> Bookstore SQL200 Module 3 23 Delete Example: Delete from sources Where source_numb = 22 Bookstore SQL200 Module 3 24 12
  • 80. Delete Bookstore SQL200 Module 3 25 Sources table after Delete Bookstore SQL200 Module 3 26 13
  • 81. 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 Bookstore SQL200 Module 3 27 SQL/200 SQL Programming Part 2– Managing Database Structures Bookstore SQL200 Module 3 28 14
  • 82. DDL • Create • Alter • Drop Bookstore SQL200 Module 3 29 Schemas • Logical view of a database; sort of a “sub- database” – we will not cover these in this module or… – Catalogs – Clusters – Domains (somewhat like a user defined datatype) • These topics are highly dependent upon the vendor DBMS and installation practices Bookstore SQL200 Module 3 30 15
  • 83. Tables • Base tables • Temporary tables – Local (or module scope) – Global (session scope) Bookstore SQL200 Module 3 31 Creating Tables • Use create statement • Specify: – Columns with data types and column constraints – Table constraints • Foreign key references • Primary key designation Bookstore SQL200 Module 3 32 16
  • 84. Data Types • Int – integers or whole numbers – Ex: how_many int • Char – fixed length fields – Ex: state char(2) • Varchar/Varchar2 – variable length fields – Ex: address varchar(35) • Money – money field; same as MS Access currency • Date/Datetime – date and time • And many others – see documentation or Help Bookstore SQL200 Module 3 33 Create Table Basic syntax: Create table <table-name> <column1> <datatype> <constraints> ,.. <column1> <datatype> <constraints> … <table constraints> Note: often preceded by a drop Bookstore SQL200 Module 3 34 17
  • 85. Temporary Tables Basic syntax (SQL standard): Create [global] temporary table <table-name> <rest of statement as for normal create> Note: SQL Server uses a different syntax. Just put a #in front of the table name as in #mytable. Bookstore SQL200 Module 3 35 Column Constraints • Primary key • Not NULL • CHECK clause • Default • Unique Bookstore SQL200 Module 3 36 18
  • 86. Table Constraints • Primary Key • Foreign Key • Compare fields against each other. I.e. ship_date >= order_date Bookstore SQL200 Module 3 37 But first – the Drop Statement • Deletes a database “object” – Drop table <table-name> – Drop view <view-name> – Drop index <index-name> – Drop domain <domain-name> Bookstore SQL200 Module 3 38 19
  • 87. Create Table Example 1: Create a summary table Create table summary( isbn varchar(20) primary key, How_many int check (how_many >= 0), Constraint isbn_fk Foreign key (isbn) references books(isbn) ) Bookstore SQL200 Module 3 39 Create Summary Table Bookstore SQL200 Module 3 40 20
  • 88. Constraints on Summary Table Bookstore SQL200 Module 3 41 Multi-row Insert Basic Syntax: Insert [into] <table-name> [(<column list>)] Select <select-statement> Bookstore SQL200 Module 3 42 21
  • 89. Multi-row Insert Basic Example: (store # times each book ordered) Insert into summary Select isbn, count(*) From orderlines Group by isbn; Bookstore SQL200 Module 3 43 Multi-row Insert Bookstore SQL200 Module 3 44 22
  • 90. After multi-row insert in MS Access Bookstore SQL200 Module 3 45 SQL/200 SQL Programming Part 3 – Creating Views and Indexes, Modifying Structures Bookstore SQL200 Module 3 46 23
  • 91. 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 Bookstore SQL200 Module 3 47 Views Basic syntax: Create view <view-name> (<column-list>) As <select statement> Bookstore SQL200 Module 3 48 24
  • 92. Creating a View Bookstore SQL200 Module 3 49 Using Views • Can be used like a table subject to various limitations – Cannot insert into grouped queries, etc. – Etc. • Sample syntax: select column-list from employee_view Bookstore SQL200 Module 3 50 25
  • 93. Using a View Bookstore SQL200 Module 3 51 Indexes • Used to speed searches, joins, etc. • Placed on: – primary and foreign keys – Secondary keys • In commercial practice often managed by DBA’s for large databases Bookstore SQL200 Module 3 52 26
  • 94. Indexes Basic syntax: Create [unique] index <index-name> On <table-name> (field-name> [desc]) Note: can place index on a composite key; ex: state and city Bookstore SQL200 Module 3 53 Indexes Basic example: create index state_inx on customers(customer_state) Bookstore SQL200 Module 3 54 27
  • 95. Customers table with index Bookstore SQL200 Module 3 55 Dropping an index Basic Syntax: – Drop index <table-name.index-name>; Bookstore SQL200 Module 3 56 28
  • 96. Modifying a Table Design • Applies to tables • Use ALTER statement – Add columns – Delete columns – Rename columns – Add column constraints – Add table constraints Bookstore SQL200 Module 3 57 Modifying a Table Design Basic syntax: Alter <table-name> Add <field-name>, Add <table-constraint>, Modify <field-name> Etc. Bookstore SQL200 Module 3 58 29
  • 97. Modify a Table Design Example: add a phone number field alter table publishers add phone char(12); Bookstore SQL200 Module 3 59 After alter publishers table Bookstore SQL200 Module 3 60 30
  • 98. SQL/200 SQL Programming Part 4 – Security Bookstore SQL200 Module 3 61 Security • Important DBA function – Beyond scope of this course – Typically controlled through Enterprise Manager or Studio GUI’s • In commercial practice application security frequently controlled via own login and a “users” table or similar Bookstore SQL200 Module 3 62 31
  • 99. Security • Specifics can vary by product • Access: workgroup administrator • SQL Server: users, roles • Oracle: users, roles Bookstore SQL200 Module 3 63 SQL Security Statements • Grant • Revoke • Deny Bookstore SQL200 Module 3 64 32
  • 100. Grant Syntax: Grant <access-right> [with grant option] On <object> to <user> Note: by default only tables owners and admins can access a table. Others must be granted the relevant rights. Bookstore SQL200 Module 3 65 Access Rights • Select • Update • Insert • Delete • References • All privileges Bookstore SQL200 Module 3 66 33
  • 101. Grant Example: Grant update On employees to ddurso Bookstore SQL200 Module 3 67 Revoke • Revokes the rights • Syntax similar to grant [end module] Bookstore SQL200 Module 3 68 34
  • 102. Orange Coast Database Associates Course (800)355-9855 or http://ocdatabases.itgo.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 B-4A San Juan Capistrano, CA (800)355-9855 (Toll Free) | (949)489-1472 (Direct) | (949)485-6284 (Fax) http://ocdatabases.itgo.com | info@ocdatabases.itgo.com Accelerated Computer Training for Working Professionals