SlideShare a Scribd company logo
1 of 56
SQL302




            Intermediate SQL Programming
   Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T-
   SQL Fundamentals by Itzki Ben-gan

         Workshop 3 – Modifying Data, Managing the
                        Database
SQL Server/Employees               SQL302 Module 3                                1
Note on SQL302 Slides
    • These slides were originally designed to support the
      single SQL302 course which was used for any of
      MS Access, Oracle and SQL Server.
    • As such you may see here slides developed in any
      one of the above products.
    • We are in the process of migrating the Oracle
      MySQL, and MS Access slides out into their own
      slide sets. These SQL302 slides will focus on
      Microsoft SQL Server.


SQL Server/Employees      SQL302 Module 3                    2
Warning!
• Below are some table name changes to be
  aware of in doing queries. We have created
  synonyms so either name should work.

        New Name               Old Name
        Orders                 Order_filled
        Order_Lines            Orderlines


SQL Server/Employees    SQL302 Module 3        3
SQL302 Contact Information



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


SQL Server/Employees                    SQL302 Module 3   4
SQL302 Resources
• Bookstore database scripts found on
  box.net at
      http://tinyurl.com/SQLScripts
• Slides can be viewed on SlideShare…
      http://www.slideshare.net/OCDatabases
• Follow up questions?
      sql.support@dhdursoassociates.com

SQL Server/Employees    SQL302 Module 3       5
SQL302 Module 3
• Part 1 – Modifying Data
• Part 2 – Managing Database Structures




SQL Server/Employees    SQL302 Module 3   6
SQL302

                       SQL Programming

                       Part 1 – Modifying Data


SQL Server/Employees          SQL302 Module 3    7
Relational Database with constraints (from text)




SQL Server/Employees     SQL302 Module 3                  8
Sample Employees Database




Bookstore2 &          SQL204 Module 1      9
Employees
Transactions
  • Statements can be grouped
    into transactions
  • All must succeed
  • If so they are all
    committed
  • If not they are all rolled
    back
  • Helps guarantee data is
    consistent

SQL Server/Employees     POS/410 Workshop 3   10
SQL Server Transactions Syntax
                   begin transaction
                       Statements
                       …
                       …
                   if @@error = 0
                       Commit transaction
                   else
                       Rollback error

SQL Server/Employees         POS/410 Workshop 3   11
Data Modification Statements

           • End-user rarely sees these
             statements

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



SQL Server/Employees     SQL302 Module 3      12
Data Modification Statements
           • This course (SQL302)
                –      Select Into
                –      Table Valued Constructors (TVCs)
                –      Update
                –      Delete
           • Basic DML already covered in
             SQL202

SQL Server/Employees            SQL302 Module 3           13
Select into
• Select….into will copy a table
• Uses a regular SQL statement with into
  clause before the from not after
• Syntax:
    Select <select list>
    Into <tablename>
    From <tablename>

SQL Server/Employees     SQL302 Module 3   14
Select into
• Example:
      – Copy a subset of the employees table to a
        temporary working table
• Code:




SQL Server/Employees     SQL302 Module 3            15
Insert with TVC
• Newer form of insert statement long
  available in MySQL
• Can shorten your code
• Each element in the insert list can actually
  be an expression but we will use literals in
  this class


SQL Server/Employees       SQL302 Module 3       16
Insert with TVC




SQL Server/Employees       SQL302 Module 3   17
Update and Delete
           • Updates and deletes can use
             subqueries

           • SQL Server allows update and
             delete statements to be based on
             joins, too

           • We will review this in the next few
             slides.
SQL Server/Employees        SQL302 Module 3        18
Update
• You can use subqueries in an update.
      – In where predicate
      – To set the field value

     UPDATE table
     SET columnname = value from subquery
     [WHERE condition with subquery]


SQL Server/Employees     SQL302 Module 3    19
UPDATE w/ Subquery in where
• Example: Increase range minimums for unused
  job codes




SQL Server/Employees   SQL302 Module 3          20
UPDATE Results




SQL Server/Employees       SQL302 Module 3   21
UPDATE FROM Statement
   SQL Server allows updates from a table, including joined
   tables. As an example one could update quantity on hand
   in an inventory table from a transaction table.


                   UPDATE table
                   SET columnname = value…
                   [FROM tablelist]
                   [WHERE condition]

SQL Server/Employees      SQL302 Module 3                     22
Update from
• Example: increase managerial salaries




SQL Server/Employees      SQL302 Module 3   23
UPDATE From Results




SQL Server/Employees   SQL302 Module 3   24
Update w/ subquery in set clause
• Update employee temp table – set salaries to the
  average for that code




SQL Server/Employees   SQL302 Module 3               25
DELETE FROM Statement
   SQL Server allows deletes from a table based on a
   subquery or a join condition.

   Basic syntax:

                       DELETE [from] table
                       FROM tablelist
                       [WHERE condition]


SQL Server/Employees         SQL302 Module 3           26
Delete from
• Example: Delete unused job titles




SQL Server/Employees     SQL302 Module 3   27
DELETE FROM Results




SQL Server/Employees   SQL302 Module 3   28
Delete and Referential Integrity
• Can affect referential integrity when deleting a
  “parent” row
• Can do following with child…
      –   Cascade: delete the child row
      –   Set null: set the child’s foreign key null
      –   Set default: as above but to default value
      –   No action: don’t allow delete of parent row
• Referential integrity can be established when
  creating or modifying table structures which we
  will look at later in the class

SQL Server/Employees        SQL302 Module 3             29
SQL302

                       SQL Programming

              Part 2– Managing Database Structures


SQL Server/Employees        SQL302 Module 3          30
Managing Database Structures
•   Create
•   Alter
•   Synonyms
•   Views




SQL Server/Employees   SQL302 Module 3   31
Managing Database Structures
• We will first create a table and then use the
  alter command to
      – Add columns
      – Modify columns
      – Add constraints




SQL Server/Employees   SQL302 Module 3        32
Creating Tables
• Use create statement
• Specify:
      – Columns with data types and column
        constraints
      – Table constraints
           • Foreign key references
           • Primary key designation


SQL Server/Employees       SQL302 Module 3   33
Create Table
     Basic syntax:
     Create table <table-name>
     (
     <column1> <datatype> <constraints>
     ,.. <column1> <datatype> <constraints>
     …
     <table constraints>
     );
SQL Server/Employees       SQL302 Module 3    34
Create Table
      Example 1: SQL202 Create summary table
      (we will do this step by step using the alter
      statement in succeeding slides)
      Create table summary(
      isbn varchar(20) primary key,
      How_many int check (how_many >= 0),
      Constraint isbn_fk
      Foreign key (isbn) references books(isbn)
      )

SQL Server/Employees      SQL302 Module 3             35
Create Table
      Example 2: Create summary table
      Create table #summary(
      isbn varchar(20) primary key);




SQL Server/Employees      SQL302 Module 3   36
Modifying a Table Design
• Applies to tables
• Use ALTER statement
      –   Add columns
      –   Delete columns
      –   Rename columns
      –   Add column constraints
      –   Add table constraints

SQL Server/Employees     SQL302 Module 3   37
Modifying a Table Design
      Basic syntax:
      Alter <table-name>
      Add <field-name>,
      Add <table-constraint>,
      Alter <field-name>
      Etc.

SQL Server/Employees   SQL302 Module 3   38
Add a column

         Example: add a column to hold how
         many times a book has been sold
         alter table #summary
         Add how_many
         numeric(5,2);



SQL Server/Employees      SQL302 Module 3    39
Modify a column
• Example
      – Change the how many column to an integer
• Code
  alter table #summary
  alter column how_many int;



SQL Server/Employees        SQL302 Module 3        40
New column results




SQL Server/Employees    SQL302 Module 3   41
Column Constraints
•   Primary key
•   Not NULL
•   CHECK clause
•   Default
•   Unique



SQL Server/Employees    SQL302 Module 3   42
Add a column constraint

        Example: modify the how many column
        so there is a check constraint on
        how_many


        alter table #summary
        add constraint check
        (how_many >=0);
SQL Server/Employees   SQL302 Module 3        43
Table Constraints
• Primary Key
• Foreign Key
• Compare fields against each other. I.e.
  ship_date >= order_date




SQL Server/Employees        SQL302 Module 3   44
Add a table constraint

       Example: add a foreign key constraint
       with cascade options




SQL Server/Employees   SQL302 Module 3         45
Constraints on Summary Table




SQL Server/Employees   SQL302 Module 3   46
Synonyms
• Can create another name for an object
      – Used to provide a shorthand way to refer a
        long, fully qualified table name
      – Used where we want scripts to use an old
        name as well as the newer name
• Syntax:
      – Create <synonym> for <objectname>


SQL Server/Employees    SQL302 Module 3              47
Synonyms
• Example:
      – create a synonym for the orderlines table
• Code
  create synonym orderlines for
  order_lines;



SQL Server/Employees    SQL302 Module 3             48
Views
• Think of a view as a named query wherein
  the definition is stored in the database
• Can be read like a table
• Some are updateable




SQL Server/Employees   SQL302 Module 3       49
Views

   Basic syntax:
   Create view <view-name> (<column-list>)
   As
   <select statement>
   Column list can be used to name the output columns
   instead of using the names in the select list

SQL Server/Employees     SQL302 Module 3                50
Creating a View




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

SQL Server/Employees      SQL302 Module 3          52
Inserting into a view
• Must insert into all required columns in
  underlying table
• Sample code:




SQL Server/Employees    SQL302 Module 3      53
Using a View




SQL Server/Employees      SQL302 Module 3   54
SQL302




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




SQL Server/Employees   SQL302 Module 3   56

More Related Content

What's hot

Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data RedactionAlex Zaballa
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data RedactionIvica Arsov
 
MS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutionsMS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutionsRSolutions
 
Oracle Data Redaction - UKOUG - TECH14
Oracle Data Redaction - UKOUG - TECH14Oracle Data Redaction - UKOUG - TECH14
Oracle Data Redaction - UKOUG - TECH14Alex Zaballa
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2Raj vardhan
 
Using MySQL Meta Data Effectively
Using MySQL Meta Data EffectivelyUsing MySQL Meta Data Effectively
Using MySQL Meta Data EffectivelyDossy Shiobara
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...Jürgen Ambrosi
 
SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1Dan D'Urso
 
Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015 Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015 Alex Zaballa
 

What's hot (13)

Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
MS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutionsMS SQL - Database Programming Concepts by RSolutions
MS SQL - Database Programming Concepts by RSolutions
 
Oracle Data Redaction - UKOUG - TECH14
Oracle Data Redaction - UKOUG - TECH14Oracle Data Redaction - UKOUG - TECH14
Oracle Data Redaction - UKOUG - TECH14
 
MYSQL.ppt
MYSQL.pptMYSQL.ppt
MYSQL.ppt
 
Sql queries
Sql queriesSql queries
Sql queries
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
 
Using MySQL Meta Data Effectively
Using MySQL Meta Data EffectivelyUsing MySQL Meta Data Effectively
Using MySQL Meta Data Effectively
 
Sql views
Sql viewsSql views
Sql views
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1SQL212.1 Introduction to SQL using Oracle Module 1
SQL212.1 Introduction to SQL using Oracle Module 1
 
Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015 Data Redaction - OTN TOUR LA 2015
Data Redaction - OTN TOUR LA 2015
 

Viewers also liked

Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2guest4a9aba
 
我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況RICK Lin
 
Course Catalog
Course CatalogCourse Catalog
Course CatalogDan D'Urso
 
Show Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataShow Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataRyan Thornburg
 
Comic Book
Comic BookComic Book
Comic BookThomasdl
 
Tagger.fm Muziek Digitaal 091028
Tagger.fm Muziek Digitaal 091028Tagger.fm Muziek Digitaal 091028
Tagger.fm Muziek Digitaal 091028Tim Rootsaert
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualDan D'Urso
 
Presentatie REC 250309
Presentatie REC 250309Presentatie REC 250309
Presentatie REC 250309Tim Rootsaert
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The NetherlandsBZK
 
Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009pulamajor
 
青年創業及圓夢網 創業稅務大小事【創業懶人包 】
青年創業及圓夢網 創業稅務大小事【創業懶人包 】青年創業及圓夢網 創業稅務大小事【創業懶人包 】
青年創業及圓夢網 創業稅務大小事【創業懶人包 】RICK Lin
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1guest38bf
 
AVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBAAVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBADan D'Urso
 
Displays
DisplaysDisplays
Displaysspecfab
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institutemoorebl
 

Viewers also liked (20)

Pharma Powerpoint 2
Pharma Powerpoint 2Pharma Powerpoint 2
Pharma Powerpoint 2
 
我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況我國數位產業學習發展與推動概況
我國數位產業學習發展與推動概況
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 
Show Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting DataShow Your Work: Cheap & Easy Tools for Presenting Data
Show Your Work: Cheap & Easy Tools for Presenting Data
 
Comic Book
Comic BookComic Book
Comic Book
 
Tagger.fm Muziek Digitaal 091028
Tagger.fm Muziek Digitaal 091028Tagger.fm Muziek Digitaal 091028
Tagger.fm Muziek Digitaal 091028
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
 
Presentatie REC 250309
Presentatie REC 250309Presentatie REC 250309
Presentatie REC 250309
 
eParticipation in The Netherlands
eParticipation in The NetherlandseParticipation in The Netherlands
eParticipation in The Netherlands
 
Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009Resume Portfolio Linkedin 01 2009
Resume Portfolio Linkedin 01 2009
 
青年創業及圓夢網 創業稅務大小事【創業懶人包 】
青年創業及圓夢網 創業稅務大小事【創業懶人包 】青年創業及圓夢網 創業稅務大小事【創業懶人包 】
青年創業及圓夢網 創業稅務大小事【創業懶人包 】
 
AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1AVB201.1 MS Access VBA Module 1
AVB201.1 MS Access VBA Module 1
 
London
LondonLondon
London
 
AIN100
AIN100AIN100
AIN100
 
Operació t4 i josef mengele
Operació t4 i josef mengeleOperació t4 i josef mengele
Operació t4 i josef mengele
 
AVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBAAVB202 Intermediate Microsoft Access VBA
AVB202 Intermediate Microsoft Access VBA
 
IntelliStick
IntelliStickIntelliStick
IntelliStick
 
K.l. reich
K.l. reichK.l. reich
K.l. reich
 
Displays
DisplaysDisplays
Displays
 
George Washington Teacher’s Institute
George Washington Teacher’s InstituteGeorge Washington Teacher’s Institute
George Washington Teacher’s Institute
 

Similar to SQL302 Intermediate SQL Workshop 3

SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxQuyVo27
 
SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxKashifManzoorMeo
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3Dan D'Urso
 
SQL302 Intermediate SQL
SQL302 Intermediate SQLSQL302 Intermediate SQL
SQL302 Intermediate SQLDan D'Urso
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignDan D'Urso
 
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 3Dan D'Urso
 
SQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL QueriesSQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL QueriesDan D'Urso
 
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2Dan D'Urso
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
Tungsten University: Load A Vertica Data Warehouse With MySQL Data
Tungsten University: Load A Vertica Data Warehouse With MySQL DataTungsten University: Load A Vertica Data Warehouse With MySQL Data
Tungsten University: Load A Vertica Data Warehouse With MySQL DataContinuent
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsmaxpane
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro projectARVIND SARDAR
 
Capture Change and Apply It!
Capture Change and Apply It!Capture Change and Apply It!
Capture Change and Apply It!Steve Wake
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 

Similar to SQL302 Intermediate SQL Workshop 3 (20)

SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptx
 
SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptx
 
SQL200.3 Module 3
SQL200.3 Module 3SQL200.3 Module 3
SQL200.3 Module 3
 
SQL302 Intermediate SQL
SQL302 Intermediate SQLSQL302 Intermediate SQL
SQL302 Intermediate SQL
 
SQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL DesignSQL200A Microsoft Access SQL Design
SQL200A Microsoft Access SQL Design
 
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
 
SQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL QueriesSQL201S Accelerated Introduction to MySQL Queries
SQL201S Accelerated Introduction to MySQL Queries
 
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
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
 
Sq lite module5
Sq lite module5Sq lite module5
Sq lite module5
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
Tungsten University: Load A Vertica Data Warehouse With MySQL Data
Tungsten University: Load A Vertica Data Warehouse With MySQL DataTungsten University: Load A Vertica Data Warehouse With MySQL Data
Tungsten University: Load A Vertica Data Warehouse With MySQL Data
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Dms 22319 micro project
Dms 22319 micro projectDms 22319 micro project
Dms 22319 micro project
 
Capture Change and Apply It!
Capture Change and Apply It!Capture Change and Apply It!
Capture Change and Apply It!
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
PL/SQL 3 DML
PL/SQL 3 DMLPL/SQL 3 DML
PL/SQL 3 DML
 

More from Dan D'Urso

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

More from 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
 
Course Catalog
Course CatalogCourse Catalog
Course Catalog
 
SQL201W MySQL SQL Manual
SQL201W MySQL SQL ManualSQL201W MySQL SQL Manual
SQL201W MySQL SQL Manual
 
SQL206 SQL Median
SQL206 SQL MedianSQL206 SQL Median
SQL206 SQL Median
 
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
 
SQL202 SQL Server SQL Manual
SQL202 SQL Server SQL ManualSQL202 SQL Server SQL Manual
SQL202 SQL Server SQL Manual
 
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
 
AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1AIN102.1 Microsoft Access Queries Module 1
AIN102.1 Microsoft Access Queries Module 1
 
AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2AIN100B Microsoft Access Level 2
AIN100B Microsoft Access Level 2
 
AMP110 Microsoft Access Macros
AMP110 Microsoft Access MacrosAMP110 Microsoft Access Macros
AMP110 Microsoft Access Macros
 

SQL302 Intermediate SQL Workshop 3

  • 1. SQL302 Intermediate SQL Programming Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T- SQL Fundamentals by Itzki Ben-gan Workshop 3 – Modifying Data, Managing the Database SQL Server/Employees SQL302 Module 3 1
  • 2. Note on SQL302 Slides • These slides were originally designed to support the single SQL302 course which was used for any of MS Access, Oracle and SQL Server. • As such you may see here slides developed in any one of the above products. • We are in the process of migrating the Oracle MySQL, and MS Access slides out into their own slide sets. These SQL302 slides will focus on Microsoft SQL Server. SQL Server/Employees SQL302 Module 3 2
  • 3. Warning! • Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. New Name Old Name Orders Order_filled Order_Lines Orderlines SQL Server/Employees SQL302 Module 3 3
  • 4. SQL302 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2011. All rights reserved. SQL Server/Employees SQL302 Module 3 4
  • 5. SQL302 Resources • Bookstore database scripts found on box.net at http://tinyurl.com/SQLScripts • Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases • Follow up questions? sql.support@dhdursoassociates.com SQL Server/Employees SQL302 Module 3 5
  • 6. SQL302 Module 3 • Part 1 – Modifying Data • Part 2 – Managing Database Structures SQL Server/Employees SQL302 Module 3 6
  • 7. SQL302 SQL Programming Part 1 – Modifying Data SQL Server/Employees SQL302 Module 3 7
  • 8. Relational Database with constraints (from text) SQL Server/Employees SQL302 Module 3 8
  • 9. Sample Employees Database Bookstore2 & SQL204 Module 1 9 Employees
  • 10. Transactions • Statements can be grouped into transactions • All must succeed • If so they are all committed • If not they are all rolled back • Helps guarantee data is consistent SQL Server/Employees POS/410 Workshop 3 10
  • 11. SQL Server Transactions Syntax begin transaction Statements … … if @@error = 0 Commit transaction else Rollback error SQL Server/Employees POS/410 Workshop 3 11
  • 12. Data Modification Statements • End-user rarely sees these statements • Application developer prepares these statements “behind the scenes” based on forms or web pages filled out by user SQL Server/Employees SQL302 Module 3 12
  • 13. Data Modification Statements • This course (SQL302) – Select Into – Table Valued Constructors (TVCs) – Update – Delete • Basic DML already covered in SQL202 SQL Server/Employees SQL302 Module 3 13
  • 14. Select into • Select….into will copy a table • Uses a regular SQL statement with into clause before the from not after • Syntax: Select <select list> Into <tablename> From <tablename> SQL Server/Employees SQL302 Module 3 14
  • 15. Select into • Example: – Copy a subset of the employees table to a temporary working table • Code: SQL Server/Employees SQL302 Module 3 15
  • 16. Insert with TVC • Newer form of insert statement long available in MySQL • Can shorten your code • Each element in the insert list can actually be an expression but we will use literals in this class SQL Server/Employees SQL302 Module 3 16
  • 17. Insert with TVC SQL Server/Employees SQL302 Module 3 17
  • 18. Update and Delete • Updates and deletes can use subqueries • SQL Server allows update and delete statements to be based on joins, too • We will review this in the next few slides. SQL Server/Employees SQL302 Module 3 18
  • 19. Update • You can use subqueries in an update. – In where predicate – To set the field value UPDATE table SET columnname = value from subquery [WHERE condition with subquery] SQL Server/Employees SQL302 Module 3 19
  • 20. UPDATE w/ Subquery in where • Example: Increase range minimums for unused job codes SQL Server/Employees SQL302 Module 3 20
  • 22. UPDATE FROM Statement SQL Server allows updates from a table, including joined tables. As an example one could update quantity on hand in an inventory table from a transaction table. UPDATE table SET columnname = value… [FROM tablelist] [WHERE condition] SQL Server/Employees SQL302 Module 3 22
  • 23. Update from • Example: increase managerial salaries SQL Server/Employees SQL302 Module 3 23
  • 24. UPDATE From Results SQL Server/Employees SQL302 Module 3 24
  • 25. Update w/ subquery in set clause • Update employee temp table – set salaries to the average for that code SQL Server/Employees SQL302 Module 3 25
  • 26. DELETE FROM Statement SQL Server allows deletes from a table based on a subquery or a join condition. Basic syntax: DELETE [from] table FROM tablelist [WHERE condition] SQL Server/Employees SQL302 Module 3 26
  • 27. Delete from • Example: Delete unused job titles SQL Server/Employees SQL302 Module 3 27
  • 28. DELETE FROM Results SQL Server/Employees SQL302 Module 3 28
  • 29. Delete and Referential Integrity • Can affect referential integrity when deleting a “parent” row • Can do following with child… – Cascade: delete the child row – Set null: set the child’s foreign key null – Set default: as above but to default value – No action: don’t allow delete of parent row • Referential integrity can be established when creating or modifying table structures which we will look at later in the class SQL Server/Employees SQL302 Module 3 29
  • 30. SQL302 SQL Programming Part 2– Managing Database Structures SQL Server/Employees SQL302 Module 3 30
  • 31. Managing Database Structures • Create • Alter • Synonyms • Views SQL Server/Employees SQL302 Module 3 31
  • 32. Managing Database Structures • We will first create a table and then use the alter command to – Add columns – Modify columns – Add constraints SQL Server/Employees SQL302 Module 3 32
  • 33. Creating Tables • Use create statement • Specify: – Columns with data types and column constraints – Table constraints • Foreign key references • Primary key designation SQL Server/Employees SQL302 Module 3 33
  • 34. Create Table Basic syntax: Create table <table-name> ( <column1> <datatype> <constraints> ,.. <column1> <datatype> <constraints> … <table constraints> ); SQL Server/Employees SQL302 Module 3 34
  • 35. Create Table Example 1: SQL202 Create summary table (we will do this step by step using the alter statement in succeeding slides) Create table summary( isbn varchar(20) primary key, How_many int check (how_many >= 0), Constraint isbn_fk Foreign key (isbn) references books(isbn) ) SQL Server/Employees SQL302 Module 3 35
  • 36. Create Table Example 2: Create summary table Create table #summary( isbn varchar(20) primary key); SQL Server/Employees SQL302 Module 3 36
  • 37. Modifying a Table Design • Applies to tables • Use ALTER statement – Add columns – Delete columns – Rename columns – Add column constraints – Add table constraints SQL Server/Employees SQL302 Module 3 37
  • 38. Modifying a Table Design Basic syntax: Alter <table-name> Add <field-name>, Add <table-constraint>, Alter <field-name> Etc. SQL Server/Employees SQL302 Module 3 38
  • 39. Add a column Example: add a column to hold how many times a book has been sold alter table #summary Add how_many numeric(5,2); SQL Server/Employees SQL302 Module 3 39
  • 40. Modify a column • Example – Change the how many column to an integer • Code alter table #summary alter column how_many int; SQL Server/Employees SQL302 Module 3 40
  • 41. New column results SQL Server/Employees SQL302 Module 3 41
  • 42. Column Constraints • Primary key • Not NULL • CHECK clause • Default • Unique SQL Server/Employees SQL302 Module 3 42
  • 43. Add a column constraint Example: modify the how many column so there is a check constraint on how_many alter table #summary add constraint check (how_many >=0); SQL Server/Employees SQL302 Module 3 43
  • 44. Table Constraints • Primary Key • Foreign Key • Compare fields against each other. I.e. ship_date >= order_date SQL Server/Employees SQL302 Module 3 44
  • 45. Add a table constraint Example: add a foreign key constraint with cascade options SQL Server/Employees SQL302 Module 3 45
  • 46. Constraints on Summary Table SQL Server/Employees SQL302 Module 3 46
  • 47. Synonyms • Can create another name for an object – Used to provide a shorthand way to refer a long, fully qualified table name – Used where we want scripts to use an old name as well as the newer name • Syntax: – Create <synonym> for <objectname> SQL Server/Employees SQL302 Module 3 47
  • 48. Synonyms • Example: – create a synonym for the orderlines table • Code create synonym orderlines for order_lines; SQL Server/Employees SQL302 Module 3 48
  • 49. Views • Think of a view as a named query wherein the definition is stored in the database • Can be read like a table • Some are updateable SQL Server/Employees SQL302 Module 3 49
  • 50. Views Basic syntax: Create view <view-name> (<column-list>) As <select statement> Column list can be used to name the output columns instead of using the names in the select list SQL Server/Employees SQL302 Module 3 50
  • 51. Creating a View SQL Server/Employees SQL302 Module 3 51
  • 52. Using Views • Can be used like a table subject to various limitations – Cannot insert into grouped queries, etc. – Etc. • Sample select from syntax: select column-list from employee_view SQL Server/Employees SQL302 Module 3 52
  • 53. Inserting into a view • Must insert into all required columns in underlying table • Sample code: SQL Server/Employees SQL302 Module 3 53
  • 54. Using a View SQL Server/Employees SQL302 Module 3 54
  • 55. SQL302 [end of course] SQL Server/Employees SQL302 Module 3 55
  • 56. Notes SQL Server/Employees SQL302 Module 3 56