SQL212 Oracle SQL Manual

566 views

Published on

SQL212 Accelerated Introduction to SQL Using oracle. Covers create, alter, drop, insert, update, delete. Includes joins, inner and outer, subqueries, calculations and grouping.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

SQL212 Oracle SQL Manual

  1. 1. Orange Coast Database Associates Course (800)355-9855 or http://ocdatabases.itgo.com SQL212 Introduction to SQL Using Oracle Orange Coast Database Associates Specializing in Microsoft Office, Access, SQL, and related technologies Classes custom designed for Working Professionals http://www.dhdursoassociates.com San Juan Capistrano, CA (800)355-9855Accelerated Computer Training for Working Professionals Factory 2010 Case
  2. 2. Welcome to SQL212 – Accelerated Introduction to SQL with Oracle An accelerated introduction to SQL for non- programmers P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.comBookstore SQL212 1 Accelerated Introduction to Oracle SQL• Introduction (s)• Facilities• Course Packet (content may vary by class) – Student questionnaire – Collaterals (Price List, Flyers, etc.) – PowerPoint handouts for all sessions (instructor slides may have some changes) – Evaluation form – Training certificate• Website (Terms, Practice Tests, etc.)Bookstore SQL212 2 1
  3. 3. SQL Curriculum SQL201W SQL202 SQL212 MySQL SQL Server Oracle SQL200* * = included in above courses SQL200S*Bookstore SQL212 3 Accelerated Introduction to SQL• Assumes no prior knowledge of SQL or Oracle products• Quick pace for experienced computer users• End-user, not programmer, oriented• SQL212 is an extension to SQL/200 – Uses Oracle in class but is otherwise identical.• SQL200s is first two modules of SQL200 - a “read only” version.Bookstore SQL212 4 2
  4. 4. Accelerated Introduction to Oracle SQL SQL Covered (Day 1) 9:00AM – 4:00PM: • Select – Basic – Filters – Joins – Subqueries – Unions – Grouping and SummarizationBookstore SQL212 5 Accelerated Introduction to Oracle SQL SQL Covered (Day 2, 9:00AM – 12:00PM): • Data Updates – Insert – Update – Delete • Data structures – Create – Drop – Alter – Views – IndexesBookstore SQL212 6 3
  5. 5. Accelerated Introduction to SQL• Focus is on SQL language• We will use Oracle SQL Developer in this class• Enterprise manager outside scope of this classBookstore SQL212 7 Accelerated Introduction to SQL Course Format: • 3 Sessions • Lecture • Demo • Student “hands-on” • Many exercises are cumulative – later examples build on queries created earlierBookstore SQL212 8 4
  6. 6. Accelerated Introduction to SQL Course Schedule (“1/2” day sessions): • Session 1 – Basic SQL • Session 2 – Multi-table Retrieval • Session 3 – Modifying DataBookstore SQL212 9 NotesBookstore SQL212 10 5
  7. 7. NotesBookstore SQL212 11 NotesBookstore SQL212 12 6
  8. 8. 11/25/2011 SQL200 Based on SQL Clearly Explained by Jan Harrington SQL Programming Module 1 – Relational Database Background, Basic Single Table Retrieval OperationsBookstore SQL200 Module 1 1 SQL Programming• Course focus is SQL language• Widely used for: – Database administration – Enterprise application development – Data driven web sites• A foundation skill for eBusiness and almost all major business applications that use relational databasesBookstore SQL200 Module 1 2 1
  9. 9. 11/25/2011 SQL Programming• A basic knowledge of query systems, perhaps via MS Access, or some programming knowledge, is desirable• We will use “SQL View” almost exclusivelyBookstore SQL200 Module 1 3 Relational Database Evolution• Based on Codd‟s paper• Early commercial efforts focused on Unix• First mainframe implementation by IBM - precursor to today‟s DB2• First PC implementation in early 80‟s by OracleBookstore SQL200 Module 1 4 2
  10. 10. 11/25/2011 Relational Database Basics• Storage • Indexes• Databases • Views• Tables • Cursors• Rows • Application interfaces• ColumnsBookstore SQL200 Module 1 5 Relational Database TableBookstore SQL200 Module 1 6 3
  11. 11. 11/25/2011 Constraints• Database • Other Business Rule – Domain – Triggers – Uniqueness – Stored Procedures – Relationship Cardinality • 1 to 1 • 1 to NBookstore SQL200 Module 1 7 Relational Database with constraintsBookstore SQL200 Module 1 8 4
  12. 12. 11/25/2011 Database Management Systems Positioning Chart Cost VLDB Enterprise Workgroup Single user Spreadsheet # UsersBookstore SQL200 Module 1 9 System Architecture File Server Architecture Access MDB AccessBookstore SQL200 Module 1 10 5
  13. 13. 11/25/2011 System Architecture Client/Server Architecture Oracle SQL DB Visual Access Basic AppBookstore SQL200 Module 1 11 System Architecture Web Architecture Web Oracle Server DB SQL BrowserBookstore SQL200 Module 1 12 6
  14. 14. 11/25/2011 Approaching SQL• Relatively simple• Two main environments – Interactive (This course) – Embedded • Static (Compiled) • DynamicBookstore SQL200 Module 1 13 SQL StandardizationANSI standardization – First standard in 1986 – SQL 89 – SQL 92 – SQL 99• Various vendor extensions – Microsoft/Sybase: T-SQL – Oracle: PL/SQLBookstore SQL200 Module 1 14 7
  15. 15. 11/25/2011 SQL Conformance• Entry• Intermediate• Advanced• Most are at least entry levelBookstore SQL200 Module 1 15 SQL Statements• Data Manipulation Language (DML)• Data Control Language (DCL)• Data Definition Language (DDL)• Note: SQL 99 changes these to seven typesBookstore SQL200 Module 1 16 8
  16. 16. 11/25/2011 SQL DDL• Data definition language (DDL) – Create, alter, drop, etc. – Frequently implemented via various CASE tools: Visio, Embarcadero, ERWin, etc. – But very useful for database administrationBookstore SQL200 Module 1 17 SQL DCL• Data Control Language (DDL) – Grant – Revoke – ConstraintsBookstore SQL200 Module 1 18 9
  17. 17. 11/25/2011 SQL DML• Data Manipulation Language (DML) – Select – Insert – Update – DeleteBookstore SQL200 Module 1 19 SQL Statement Processing Parse Validate Optimize Access Plan ExecuteBookstore SQL200 Module 1 20 10
  18. 18. 11/25/2011 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 wizardBookstore SQL200 Module 1 21 Conventions• In Access character strings are normally surrounded by double quotes – “Jones”• In an enterprise database such as Oracle or SQL Sever, then single quotes – „Jones‟• Be sensitive to the environment of your class in copying scripts from the PowerPoint slides!Bookstore SQL200 Module 1 22 11
  19. 19. 11/25/2011 SELECT Basic Syntax (Projection): Select <column-list> or <*> From <table-list>Bookstore SQL200 Module 1 23 SELECT Basic Example (Projection): select customer_last_name, customer_street from customersBookstore SQL200 Module 1 24 12
  20. 20. 11/25/2011 MS Access SQL QueryBookstore SQL200 Module 1 25Bookstore SQL200 Module 1 26 13
  21. 21. 11/25/2011 SQL Server QueryBookstore SQL200 Module 1 27 SELECT with Where Clause Example (Restriction plus Projection): Select <column-list> From <table-list> Where <selection-criteria>;Bookstore SQL200 Module 1 28 14
  22. 22. 11/25/2011 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 29 Select with WhereBookstore SQL200 Module 1 30 15
  23. 23. 11/25/2011 On Your Own• Find books written by Mark Twain• Show title, publisher, yearBookstore SQL200 Module 1 31 Complex Predicates Follow normal boolean logic Select customer_last_name, customer_street From customers Where (customer_last_name = ‘Jones’ or customer_last_name = ‘Smith’)and customer_state=‘NY’Bookstore SQL200 Module 1 32 16
  24. 24. 11/25/2011 Select with Complex WhereBookstore SQL200 Module 1 33 Complex Where ResultBookstore SQL200 Module 1 34 17
  25. 25. 11/25/2011 Special Operators• Can be used in where clause• LIKE• IN• BETWEEN• IS NULLBookstore SQL200 Module 1 35 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 36 18
  26. 26. 11/25/2011 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 37 SQL Where Clause with INBookstore SQL200 Module 1 38 19
  27. 27. 11/25/2011 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 NULLBookstore SQL200 Module 1 39 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 40 20
  28. 28. 11/25/2011 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 41 Where with BetweenBookstore SQL200 Module 1 42 21
  29. 29. 11/25/2011 Removing Duplicates List once each city in which there are customers Select DISTINCT customer_city From customers Removes duplicate rows from result setBookstore SQL200 Module 1 43 Removing DuplicatesBookstore SQL200 Module 1 44 22
  30. 30. 11/25/2011 Sorting – ORDER BY Basic syntax: Select <column list> From <table list> Where <selection criteria> Order by <column list> [DESC] DESC will sort in descending orderBookstore SQL200 Module 1 45 Sorting – ORDER BY Example: List all records sorted by state, city Select * From customers Order by customer_state, customer_cityBookstore SQL200 Module 1 46 23
  31. 31. 11/25/2011 Sorting Results with Order ByBookstore SQL200 Module 1 47 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 descendingBookstore SQL200 Module 1 [end module] 48 24
  32. 32. SQL212 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and GroupingBookstore2 SQL212 Module 2 1 SQL212 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2009. All rights reserved.Bookstore2 SQL212 Module 2 2 1
  33. 33. SQL212 SQL Programming Part 1 – Joins, SubqueriesBookstore2 SQL212 Module 2 3 Relational Database with constraints (from text)Bookstore2 SQL212 Module 2 4 2
  34. 34. Warning!• Some slides may show queries using a table called… Order_filled• The current database uses a better name… Orders Construct your queries with this latter table nameBookstore2 SQL212 Module 2 5 Joins• Inner• Outer – Left – Right – Full• Cross• Self• Theta• We will cover the most important; others as time and interest permitBookstore2 SQL212 Module 2 6 3
  35. 35. 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 joinBookstore2 SQL212 Module 2 7 Inner Join Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly usedBookstore2 SQL212 Module 2 8 4
  36. 36. Inner Join Examples• Show customers and their orders• Join the customers table to the orders table where the customer number in each table matchesBookstore2 SQL212 Module 2 9 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_numbBookstore2 SQL212 Module 2 10 5
  37. 37. Inner Join with ResultBookstore2 SQL212 Module 2 11 Inner Join (New Syntax) Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition>Bookstore2 SQL212 Module 2 12 6
  38. 38. 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_numbBookstore2 SQL212 Module 2 13 Inner Join with ResultBookstore2 SQL212 Module 2 14 7
  39. 39. Inner Join over Multiple columns• Note that that the join condition can apply to multiple columns if desired• Used with composite keysBookstore2 SQL212 Module 2 15 Inner Join Result in MS AccessBookstore2 SQL212 Module 2 16 8
  40. 40. 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 SQL212 Module 2 17 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 SQL212 Module 2 18 9
  41. 41. Dual• Sometimes we want to generate an expression without actually referring to a real table.• A trivial example would show the date.• Oracle has a 1 row, 1 column built in table called Dual to handle this.• Ex: select sysdate from dual;Bookstore2 SQL212 Module 2 19 Cross Join Result Set in MS AccessBookstore2 SQL212 Module 2 20 10
  42. 42. Additional SQL92 Syntax• Table1 natural join table2 – automatically uses columns with same name• Table1 natural join table2 using(<column- list>)• Not yet widely available in commercial implementationsBookstore2 SQL212 Module 2 21 Natural JoinBookstore2 SQL212 Module 2 22 11
  43. 43. 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 SQL212 Module 2 23 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_numbBookstore2 SQL212 Module 2 24 12
  44. 44. Multi-table Join with ResultsBookstore2 SQL212 Module 2 25 MS Access Multi-table Join Result SetBookstore2 SQL212 Module 2 26 13
  45. 45. Own Your Own• Add the book title to the previous queryBookstore2 SQL212 Module 2 27 Sample Database• Before we continue (Access classes only)…• Create a new employees tableBookstore2 SQL212 Module 2 28 14
  46. 46. 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 SQL212 Module 2 29 Self Joins• Implements a recursive relationship• Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation namesBookstore2 SQL212 Module 2 30 15
  47. 47. Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;Bookstore2 SQL212 Module 2 31Bookstore2 SQL212 Module 2 32 16
  48. 48. 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 tablesBookstore2 SQL212 Module 2 33 Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left [outer] join <table2> On <join condition>Bookstore2 SQL212 Module 2 34 17
  49. 49. Outer Join Example• Show all customers and their orders.• Include customers with no orders as well.Bookstore2 SQL212 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_numbBookstore2 SQL212 Module 2 36 18
  50. 50. Bookstore2 SQL212 Module 2 37 Left Join with ResultsBookstore2 SQL212 Module 2 38 19
  51. 51. SQL200 SQL Programming Part 2– Subqueries, UnionsBookstore2 SQL212 Module 2 39 Subqueries• One select statement embedded in another.• Can be paced in select list, from clause or where clause. – We will study the latter in this class• Can be nested multiple levels deep• Two types: – Uncorrelated – executes inner query then outer – Correlated – executes inner query once for each outer query rowBookstore2 SQL212 Module 2 40 20
  52. 52. Subquery Example• Show all the orderline information for orders places in 1999• Note that orderlines table does not have order date. Thus must filter on a different table (orders).Bookstore2 SQL212 Module 2 41 Uncorrelated Subquery select isbn, quantity from orderlines ol where ol.order_numb in (select o.order_numb from orders o where order_date between „1-JAN-99‟ and ‟31- DEC-99‟)Bookstore2 SQL212 Module 2 42 21
  53. 53. Uncorrelated Subquery with ResultsBookstore2 SQL212 Module 2 43 Negative Subquery• A type of subquery that matches “not found” conditionsBookstore2 SQL212 Module 2 44 22
  54. 54. Negative Subquery select isbn, quantity from orderlines ol where ol.order_numb not in (select o.order_numb from orders o where order_date between „1-JAN-99‟ and 31- DEC-99‟)Bookstore2 SQL212 Module 2 45 Negative Subquery with ResultsBookstore2 SQL212 Module 2 46 23
  55. 55. 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 integrityBookstore2 SQL212 Module 2 47 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-JAN- 99‟ and „31-DEC-99‟); This type of query covered in intermediate SQL classBookstore2 SQL212 Module 2 48 24
  56. 56. Unions• Combines two tables• Tables must be union compatible• Uses: – Combine current tables with history – Combine information from tables with no common join columnBookstore2 SQL212 Module 2 49 Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>Bookstore2 SQL212 Module 2 50 25
  57. 57. Union Example• Create a mailing list of customers and sources• Use a union of the two tables, making sure the columns matchBookstore2 SQL212 Module 2 51 UnionsBookstore2 SQL212 Module 2 52 26
  58. 58. Union ResultsBookstore2 SQL212 Module 2 53 SQL200 SQL Programming Part 3 – Calculations, AggregatesBookstore2 SQL212 Module 2 54 27
  59. 59. Calculated Fields• Can add a column calculated from others SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlinesBookstore2 SQL212 Module 2 55 Calculated field in the ResultBookstore2 SQL212 Module 2 56 28
  60. 60. Bookstore2 SQL212 Module 2 57 String Manipulation• Concatenation• Trim• Substring• Upper, Lower• Etc. (various vendor extensions)Bookstore2 SQL212 Module 2 58 29
  61. 61. Concatenation• Used for concatenated keys• Useful to format reports Basic syntax: (Oracle, std) Field1 || Field2Bookstore2 SQL212 Module 2 59 Concatenation select customer_first_name || „ „ || trim(customer_last_name) as Name from customersBookstore2 SQL212 Module 2 60 30
  62. 62. Bookstore2 SQL212 Module 2 61 Date Functions• Numerous date functions• Often vendor specific• Often used: – Take the year of a date – Take the month of a date – Add a month (not 30 days) – Etc.Bookstore2 SQL212 Module 2 62 31
  63. 63. Aggregate Functions• Count• Sum• Min• Max• Avg• Often used in conjunction with groupingBookstore2 SQL212 Module 2 63 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 aggregateBookstore2 SQL212 Module 2 64 32
  64. 64. Aggregate Functions SELECT orderlines.order_numb, Count(*) AS “Number of Order Lines” , Sum(orderlines.quantity) AS SumOfquantity, Sum(quantity * cost_each) AS extension FROM orderlines GROUP BY orderlines.order_numb having count(*) > 1Bookstore2 SQL212 Module 2 65Bookstore2 SQL212 Module 2 66 33
  65. 65. 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 formedBookstore2 SQL212 Module 2 67 Exercise• List all customers and their orders – Name nicely formatted – With orders in the year of 1999 – Show total order quantities and amounts – Only include orders with more than three order linesBookstore2 SQL212 Module 2 68 34
  66. 66. Exercise Result [end module]Bookstore2 SQL212 Module 2 69 NotesBookstore2 SQL212 Module 2 70 35
  67. 67. NotesBookstore2 SQL212 Module 2 71 NotesBookstore2 SQL212 Module 2 72 36
  68. 68. SQL/212 SQL Programming Workshop 3 – Modifying Data, Managing the DatabaseBookstore SQL212 Module 3 1 SQL212 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com htt // d2 i t slides.1@dhdursoassociates.com Copyright 2001-2009. All rights reserved.Bookstore SQL212 Module 3 2 1
  69. 69. SQL212 Module 3• Part 1 – Modifying Data• Part 2 – Managing Database Structures• Part 3 – Creating Views and Indexes• Part 4 -- SecurityBookstore SQL212 Module 3 3 SQL/212 SQL Programming Part 1 – Modifying DataBookstore SQL212 Module 3 4 2
  70. 70. Relational Database with constraints (from text)Bookstore SQL212 Module 3 5 Data Modification Statements • Insert • Update • D l t DeleteBookstore SQL212 Module 3 6 3
  71. 71. Data Modification Statements • End-user rarely sees these End user statements • Application developer prepares these statements “behind the scenes” based on forms filled out by b userBookstore SQL212 Module 3 7 Insert• Adds new rows to an existing table• Two forms: – Single Row – Multi-RowBookstore SQL212 Module 3 8 4
  72. 72. Single Row Insert Basic Syntax: Insert [into] <table-name> Values (<value-list>)Bookstore SQL212 Module 3 9 Single Row Insert Basic Example: insert into sources(source_numb, source_name, source_street) values(22,Specialty Books, Canal Street)Bookstore SQL212 Module 3 10 5
  73. 73. Insert StatementBookstore SQL212 Module 3 11 Sources table after InsertBookstore SQL212 Module 3 12 6
  74. 74. Multi-row Insert Basic Syntax: Insert [into] <table-name> Select <select-statement> We will do this after creating a new table later in this moduleBookstore SQL212 Module 3 13 Update• Updates fields in an existing row Basic Syntax: Update <table-name> Set <field1> = new value, <field2> = new value value,… Where <selection-criteria>Bookstore SQL212 Module 3 14 7
  75. 75. Update• Increase Ingram prices by 10% Example: Update books Set retail_price = retail price retail price retail_price *1.10 Where source_numb = 1Bookstore SQL212 Module 3 15 Ingram Book Prices before UpdateBookstore SQL212 Module 3 16 8
  76. 76. Ingram Book Prices after UpdateBookstore SQL212 Module 3 17 Delete• Deletes one or more rows Basic Syntax: Delete from <table-name> Where <selection-criteria>Bookstore SQL212 Module 3 18 9
  77. 77. Delete Example: delete the source we added Delete from sources Where source_numb = 22 h bBookstore SQL212 Module 3 19 DeleteBookstore SQL212 Module 3 20 10
  78. 78. Sources table after DeleteBookstore SQL212 Module 3 21 Delete and Referential Integrity• Can affect referential integrity when deleting a “parent” row parent• 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 classBookstore SQL212 Module 3 22 11
  79. 79. SQL/212 SQL Programming Part 2– Managing Database StructuresBookstore SQL212 Module 3 23 Schemas• Logical view of a database; sort of a “sub- database” – we will not cover these in this module… – Catalogs – Clusters – Domains (somewhat like a user defined datatype)• These topics are highly dependent upon the vendor DBMS and installation practices – In Oracle you are logged in to your schemaBookstore SQL212 Module 3 24 12
  80. 80. Tables • Two types – Base tables – Temporary tables • Local (or module scope) • Global (session scope) • We will create base tables in this classBookstore SQL212 Module 3 25 Creating Tables• Use create statement• Specify: – Columns with data types and column constraints – Table constraints • Foreign key references • Primary key designationBookstore SQL212 Module 3 26 13
  81. 81. 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 varchar2(35)• Money – money field• Date/Datetime – date and time• And many others – see documentation or HelpBookstore SQL212 Module 3 27 Create Table Basic syntax: Create table <table-name> <column1> <datatype> <constraints> ,.. <column1> <datatype> <constraints> … <table constraints> Note: often preceded by a dropBookstore SQL212 Module 3 28 14
  82. 82. Temporary Tables Basic syntax: 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. Access doesn’t have true temporary tables.Bookstore SQL212 Module 3 29 Column Constraints• Primary key• Not NULL• CHECK clause• Default• Unique qBookstore SQL212 Module 3 30 15
  83. 83. Table Constraints• Primary Key• Foreign Key• Compare fields against each other. I.e. ship_date >= order_dateBookstore SQL212 Module 3 31 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 SQL212 Module 3 32 16
  84. 84. Create Table Example 1: Create a summary table Create table summary( isbn varchar2(20) primary key, How_many int check (how_many >= 0), Constraint isbn_fk Foreign key (isbn) references books(isbn) )Bookstore SQL212 Module 3 33 Create Summary TableBookstore SQL212 Module 3 34 17
  85. 85. Constraints on Summary TableBookstore SQL212 Module 3 35 Multi-row Insert Basic Syntax: Insert [into] <table-name> Select <select-statement>Bookstore SQL212 Module 3 36 18
  86. 86. Multi-row Insert Basic Example: (store # times each book ordered) Insert into summary(isbn, how_many) Select isbn, count(*) S l t i b t(*) From orderlines Group by isbn;Bookstore SQL212 Module 3 37 Multi-row InsertBookstore SQL212 Module 3 38 19
  87. 87. After multi-row insert in MS AccessBookstore SQL212 Module 3 39 SQL/212 SQL Programming Part 3 – Creating Views and Indexes, Modifying StructuresBookstore SQL212 Module 3 40 20
  88. 88. 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 updateableBookstore SQL212 Module 3 41 Views Basic syntax: Create view <view-name> (<column-list>) As <select statement>Bookstore SQL212 Module 3 42 21
  89. 89. Creating a View• Example: show inventory for each bookBookstore SQL212 Module 3 43 Using Views• Can be used like a table subject to various limitations – Cannot insert into grouped queries, etc. – Etc.• Sample syntax: select column-list l l l from employee_viewBookstore SQL212 Module 3 44 22
  90. 90. Using a ViewBookstore SQL212 Module 3 45 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 databasesBookstore SQL212 Module 3 46 23
  91. 91. Indexes Basic syntax: y Create [unique] index <index-name> On <table-name> (field-name> [desc]) Note: can place index on a composite key; ex: state and cityBookstore SQL212 Module 3 47 Indexes• Add an index on state to speed searches and reporting Basic example: create i d t index state_inx t t i on customers(customer_state)Bookstore SQL212 Module 3 48 24
  92. 92. After indexing on customer_stateBookstore SQL212 Module 3 49 State_inx in OracleBookstore SQL212 Module 3 50 25
  93. 93. Modifying a Table Design• Applies to tables• Use ALTER statement – Add columns – Delete columns – Rename columns – Add column constraints – Add table constraintsBookstore SQL212 Module 3 51 Modifying a Table Design Basic syntax: y Alter <table-name> Add <field-name>, Add <table-constraint>, Modify fi ld M dif <field-name> Etc.Bookstore SQL212 Module 3 52 26
  94. 94. Modify a Table Design Example: add a phone number field l dd h b fi ld alter table publishers add phone char(12);Bookstore SQL212 Module 3 53After alter publishers tableBookstore SQL212 Module 3 54 27
  95. 95. SQL/212 SQL Programming Part 4 – SecurityBookstore SQL212 Module 3 55 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 similarBookstore SQL212 Module 3 56 28
  96. 96. Security• Specifics can vary by product• Access: workgroup administrator• SQL Server: users, roles• Oracle: users, rolesBookstore SQL212 Module 3 57 SQL Security Statements • Grant • Revoke • DenyBookstore SQL212 Module 3 58 29
  97. 97. 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 SQL212 Module 3 59 Access Rights• Select• Update• Insert• Delete• References• All privilegesBookstore SQL212 Module 3 60 30
  98. 98. Grant Example: Give user ddurso the permission to update the employees table. Grant update On employees to ddursoBookstore SQL212 Module 3 61 Revoke• Revokes the rights• Syntax similar to grant [end module]Bookstore SQL212 Module 3 62 31
  99. 99. NotesBookstore SQL212 Module 3 63 NotesBookstore SQL212 Module 3 64 32
  100. 100. 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 A-15 San Juan Capistrano, CA (800)355-9855 (Toll Free) | (949)489-1472 (Direct) | (949)485-6284 (Fax) http://www.dhdursoassociates.com | sales@dhdursoassociates.comAccelerated Computer Training for Working Professionals

×