Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

SQL201S Accelerated Introduction to MySQL Queries

119 views

Published on

1 day course introducing MySQL queries. Covers functions, select, joins, subqueries, grouping.

Published in: Software
  • Be the first to comment

  • Be the first to like this

SQL201S Accelerated Introduction to MySQL Queries

  1. 1. Bookstore SQL201S 1 An accelerated introduction to SQL for non- programmers P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.ocdatabases.com Welcome to SQL201S – Accelerated Introduction to SQL Queries Using MySQL
  2. 2. Bookstore SQL201S 2 Accelerated Introduction to SQL • Introduction (s) • Facilities • Course Packet (contents may vary) – Student questionnaire (may be onleine) – Collaterals (Maps, Catalogs, Etc.) – PowerPoint handouts for all sessions – Evaluation form (may be online) – Training certificate
  3. 3. Bookstore SQL201S 3 SQL Curriculum SQL200* SQL200S* SQL212 Oracle SQL202 Transact-SQL SQL201W MySQL * = included in above courses
  4. 4. Bookstore SQL201S 4 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 Workbench • SQL201S is first two modules of SQL201, otherwise identical.
  5. 5. Bookstore SQL201S 5 Accelerated Introduction to SQL • Select – Basic – Filters – Special Operators – Multi-table retrieval • Joins • Subqueries • Unions – Calculations and Aggregates SQL CoveredSQL Covered::
  6. 6. Bookstore SQL201S 6 Accelerated Introduction to SQL • 2 Sessions • Lecture • Demo • Student “hands-on” • Many exercises are cumulative – later examples build on queries created earlier Course Format:Course Format:
  7. 7. Bookstore SQL201S 7 Accelerated Introduction to SQL • Session 1 – Basic SQL • Session 2 – Multi-table Retrieval Course Schedule (“1/2” day sessions):Course Schedule (“1/2” day sessions):
  8. 8. Notes Bookstore SQL201S 8
  9. 9. Bookstore SQL201 Module 1 9 SQL201 MySQL Programming Based on SQL Clearly Explained by Jan Harrington Module 1 – Relational Database Background, Basic Single Table Retrieval Operations
  10. 10. Note on SQL201 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 slides out into their own slide sets. Bookstore SQL201 Module 1 10
  11. 11. Bookstore SQL201 Module 1 11 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
  12. 12. Bookstore SQL201 Module 1 12 SQL201 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2001-2015. All rights reserved.
  13. 13. SQL201 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? support@ocdatabases.com Bookstore SQL201 Module 1 13
  14. 14. Bookstore SQL201 Module 1 14 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
  15. 15. Bookstore SQL201 Module 1 15 SQL Programming • A basic knowledge of query systems, perhaps via MS Access, or some programming knowledge, is desirable • We will use GUI tools such as MySQL workbench in this class. But we will be typing up the scripts directly in SQL code.
  16. 16. Bookstore SQL201 Module 1 16 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
  17. 17. Bookstore SQL201 Module 1 17 Relational Database Basics • Storage • Databases • Tables • Rows • Columns • Indexes • Views • Cursors • Application interfaces
  18. 18. Bookstore SQL201 Module 1 18 Relational Database Table
  19. 19. Bookstore SQL201 Module 1 19 Constraints • Database – Domain – Uniqueness – Relationship Cardinality • 1 to 1 • 1 to N • Other Business Rule – Triggers – Stored Procedures
  20. 20. Bookstore SQL201 Module 1 20 Relational Database with constraints
  21. 21. Bookstore SQL201 Module 1 21 Database Management Systems Positioning Chart VLDB Enterprise Workgroup Single user Spreadsheet # Users Cost
  22. 22. Bookstore SQL201 Module 1 22 System Architecture Access MDB File Server Architecture Access
  23. 23. Bookstore SQL201 Module 1 23 System Architecture Oracle DB Visual Basic App Client/Server Architecture Access SQL
  24. 24. Bookstore SQL201 Module 1 24 System Architecture Oracle DB Browser Web Architecture Web Server SQL
  25. 25. Bookstore SQL201 Module 1 25 Approaching SQL • Relatively simple • Two main environments – Interactive (This course) – Embedded • Static (Compiled) • Dynamic
  26. 26. Bookstore SQL201 Module 1 26 SQL Standardization ANSI standardization – First standard in 1986 – SQL 89 – SQL 92 – SQL 99 • Various vendor extensions – Microsoft/Sybase: T-SQL – Oracle: PL/SQL
  27. 27. Bookstore SQL201 Module 1 27 SQL Conformance • Entry • Intermediate • Advanced • Most are at least entry level
  28. 28. Bookstore SQL201 Module 1 28 SQL Statements • Data Manipulation Language (DML) • Data Control Language (DCL) • Data Definition Language (DDL) • Note: SQL 99 changes these to seven types
  29. 29. Bookstore SQL201 Module 1 29 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
  30. 30. Bookstore SQL201 Module 1 30 SQL DCL • Data Control Language (DDL) – Grant – Revoke – Deny – Constraints
  31. 31. Bookstore SQL201 Module 1 31 SQL DML • Data Manipulation Language (DML) – Select – Insert – Update – Delete
  32. 32. Bookstore SQL201 Module 1 32 SQL Statement Processing Parse Validate Optimize Access Plan Execute
  33. 33. Bookstore SQL201 Module 1 33 Bookstore Sample Database • Before we continue (note: instructor may have already done this)… • Load the sample database if you haven’t already – Run the supplied SQL script
  34. 34. Bookstore SQL201 Module 1 34 Text Conventions • In an enterprise database such as Oracle or MySQL enclose text strings in single quotes – ‘Jones’
  35. 35. Bookstore SQL201 Module 1 35 Date Conventions • In an enterprise database enclose dates in single quotes – ‘2004-12-23’ MySQL – ’12-23-2004’ SQL Server – ’23-DEC-04’ Oracle
  36. 36. Select statement clauses SELECT columns FROM tables WHERE condition GROUP BY columns HAVING condition ORDER BY columns Bookstore SQL201 Module 1 36
  37. 37. Bookstore SQL201 Module 1 37 SELECT Basic Syntax (Projection): Select <column-list> or <*> From <table-list>
  38. 38. Bookstore SQL201 Module 1 38 SELECT Basic Example (Projection): select customer_last_name, customer_street from customers
  39. 39. Bookstore SQL201 Module 1 39 MySQL Query
  40. 40. Bookstore SQL201 Module 1 40 SELECT with Where Clause Example (Restriction plus Projection): Select <column-list> or * From <table-list> Where <selection-criteria>;
  41. 41. Bookstore SQL201 Module 1 41 Comparison Operators • < less than • > greater than • <= less than or equal to • >= greater than or equal to • = equal to • <> or != two forms for not equal
  42. 42. Bookstore SQL201 Module 1 42 SELECT with Where Basic Example (Restriction plus Projection): select customer_last_name, customer_first_name, customer_street from customers where customer_last_name = ‘Jones’
  43. 43. Bookstore SQL201 Module 1 43 Select with Where
  44. 44. Bookstore SQL201 Module 1 44 On Your Own • Find books written by Mark Twain • Show title, publisher, year
  45. 45. Bookstore SQL201 Module 1 45 Complex Predicates Follow normal boolean logic Select customer_last_name, customer_first_name, customer_street, customer_state From customers Where (customer_last_name = ‘Jones’ or customer_last_name = ‘Smith’)and customer_state=‘NY’
  46. 46. Bookstore SQL201 Module 1 46 Select with Complex Where
  47. 47. Bookstore SQL201 Module 1 47 Complex Where Result
  48. 48. Bookstore SQL201 Module 1 48 Special Operators • Can be used in where clause • LIKE • IN • BETWEEN • IS NULL • EXISTS
  49. 49. Bookstore SQL201 Module 1 49 Like (“Wild Card Matches”) • Use ANSI wildcard characters: % _ • Where customer_last_name like ‘Jo%’ like ‘Jo_’ There are also additional regular expression search patterns
  50. 50. Bookstore SQL201 Module 1 50 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.
  51. 51. Bookstore SQL201 Module 1 51 SQL Where Clause with IN
  52. 52. Bookstore SQL201 Module 1 52 SQL Where Clause with IN
  53. 53. Bookstore SQL201 Module 1 53 IS NULL SQL uses three valued logic. A null is NOT the same as blank or empty. It means missing or unknown.
  54. 54. Bookstore SQL201 Module 1 54 IS NULL Select * From customers Where customer_street IS NULL; Must use IS NULL to test for NULL values. Cannot even use = NULL.
  55. 55. Bookstore SQL201 Module 1 55 On Your Own • Find all customers with an address not equal to 4592 Maple Lane • Was Peter Johnson selected? • Why or why not?
  56. 56. Bookstore SQL201 Module 1 56 BETWEEN List all orders placed in 1999. select * from orders where order_date BETWEEN ‘1999-01-01’ and ‘1999-12- 31’; Note: date formats vary from product to product; recent versions tend to be pretty flexible.
  57. 57. Bookstore SQL201 Module 1 57 Where with Between
  58. 58. Bookstore SQL201 Module 1 58 Removing Duplicates Select DISTINCT customer_city From customers; List once each city in which there are customers Removes duplicate rows from result set
  59. 59. Bookstore SQL201 Module 1 59 Removing Duplicates
  60. 60. Bookstore SQL201 Module 1 60 Sorting – ORDER BY DESC will sort in descending order Basic syntax: Select <column list> or * From <table list> Where <selection criteria> Order by <column list> [DESC]
  61. 61. Bookstore SQL201 Module 1 61 Sorting – ORDER BY select * from orderlines order by cost_line desc, isbn; List all orderlines sorted by cost descending
  62. 62. Bookstore SQL201 Module 1 62 Sorting Results with Order By
  63. 63. Bookstore SQL201 Module 1 63 Limiting Record Selection Select order_numb, isbn, cost_line From orderlines Order by cost_line desc, isbn limit 5; List largest 5 orderlines…
  64. 64. Select…limit 5 Bookstore SQL201 Module 1 64
  65. 65. Bookstore SQL201 Module 1 65 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 character position 2 of the credit card #; sort by order date descending [end module]
  66. 66. Notes Bookstore SQL201 Module 1 66
  67. 67. Notes Bookstore SQL201 Module 1 67
  68. 68. Notes Bookstore SQL201 Module 1 68
  69. 69. Bookstore SQL201 Module 2 69 SQL201 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping Based on SQL Clearly Explained by Jan Harrington
  70. 70. Note on SQL201 Slides Bookstore SQL201 Module 2 70 • These slides were originally designed to support the single SQL201 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 slides out into their own slide sets.
  71. 71. Bookstore SQL201 Module 2 71 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
  72. 72. Bookstore SQL201 Module 2 72 SQL201 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com slides.1@dhdursoassociates.com Copyright 2018 All rights reserved.
  73. 73. SQL201 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? support@ocdatabases.com Bookstore SQL201 Module 2 73
  74. 74. Bookstore SQL201 Module 2 74 SQL201 SQL Programming Part 1 – Joins
  75. 75. Bookstore SQL201 Module 2 75 Relational Database with constraints (from text)
  76. 76. Bookstore SQL201 Module 2 76 Joins • Inner • Outer – Left – Right – Full • Cross • Self • Theta • We will cover the most important; others as time and interest permit
  77. 77. Bookstore SQL201 Module 2 77
  78. 78. Bookstore SQL201 Module 2 78 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
  79. 79. Bookstore SQL201 Module 2 79 Inner Join Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly used
  80. 80. Bookstore SQL201 Module 2 80 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
  81. 81. Bookstore SQL201 Module 2 81 Inner Join with Result
  82. 82. Bookstore SQL201 Module 2 82 Inner Join (New Syntax) Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition>
  83. 83. Bookstore SQL201 Module 2 83 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
  84. 84. Bookstore SQL201 Module 2 84 Inner Join with Result
  85. 85. Bookstore SQL201 Module 2 85 Inner Join over Multiple columns • Note that that the join condition can apply to multiple columns if desired • Used with composite keys
  86. 86. Bookstore SQL201 Module 2 86 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?
  87. 87. Bookstore SQL201 Module 2 87 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! • There are uses for these which we will save for an advanced class
  88. 88. Bookstore SQL201 Module 2 88 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”)
  89. 89. Bookstore SQL201 Module 2 89 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
  90. 90. Bookstore SQL201 Module 2 90 Correlation Names (Table Aliases) Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date from customers as c inner join orders as o on c.customer_numb = o.customer_numb alias
  91. 91. Bookstore SQL201 Module 2 91 Multi-table Join with Results
  92. 92. On Your Own • Add the book title to the previous query results • Hint: add another join to books table Bookstore 92SQL201 Module 2
  93. 93. Bookstore SQL201 Module 2 93 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
  94. 94. Bookstore SQL201 Module 2 94 Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left [outer] join <table2> On <join condition>
  95. 95. Bookstore SQL201 Module 2 95 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
  96. 96. Bookstore SQL201 Module 2 96 Left Join with Results
  97. 97. Negative query • Add where clause to outer join • Restrict to nulls on a column from the child table that cannot be null in the actual table – This implies there is no child record • This is a classic “forensics” query. It finds unmatched or missing information. Bookstore SQL201 Module 2 97
  98. 98. Negative Join Example • Find customers that have not placed any orders Bookstore SQL201 Module 2 98
  99. 99. Bookstore SQL201 Module 2 99 Self Joins • Implements a recursive relationship • Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation names
  100. 100. Bookstore SQL201 Module 2 100 Self Joins SELECT e.name, m.name as manager FROM employees AS e left join employees AS m on e.mgr_soc_sec_no = m.soc_sec_no;
  101. 101. Self Join Example Bookstore SQL201 Module 2 101
  102. 102. Bookstore SQL201 Module 2 102 SQL201 SQL Programming Part 2– Subqueries, Unions
  103. 103. Bookstore SQL201 Module 2 103 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
  104. 104. Bookstore SQL201 Module 2 104 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’);
  105. 105. Bookstore SQL201 Module 2 105 Uncorrelated Subquery with Results
  106. 106. Bookstore SQL201 Module 2 106 Negative Subquery • A type of subquery that matches “not found” conditions
  107. 107. Bookstore SQL201 Module 2 107 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’);
  108. 108. Bookstore SQL201 Module 2 108 Negative Subquery with Results
  109. 109. Bookstore SQL201 Module 2 109 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 This type of query covered in intermediate SQL class
  110. 110. Bookstore SQL201 Module 2 110 Unions • Combines two or more tables • Tables must be union compatible
  111. 111. Bookstore SQL201 Module 2 111 Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>
  112. 112. Bookstore SQL201 Module 2 112 Unions Mailing List Script select <sources table columns> from sources union select <customers table columns> from customers
  113. 113. Bookstore SQL201 Module 2 113 Unions Mailing List Result
  114. 114. Bookstore SQL201 Module 2 114 SQL201 SQL Programming Part 3 – Calculations, Aggregates
  115. 115. Bookstore SQL201 Module 2 115 Calculated Fields • Can add a column calculated from others SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlines
  116. 116. Bookstore SQL201 Module 2 116 Calculated field in the Result
  117. 117. Bookstore SQL201 Module 2 117 String Manipulation • Concatenation • Trim • Substring • Upper, Lower • Etc. (various vendor extensions)
  118. 118. Bookstore SQL201 Module 2 118 Concatenation • Used for concatenated keys • Useful to format reports Basic syntax: (Access) Field1 & Field2 (Oracle, std) Field1 || Field2 (Sql Server) Field1 + Field2
  119. 119. Bookstore SQL201 Module 2 119 Concatenation select concat (rtrim(customer_first_name) , ‘ ‘ , trim(customer_last_name)) as FullName from customers
  120. 120. Bookstore SQL201 Module 2 120 Concatenation
  121. 121. Bookstore SQL201 Module 2 121 Date Functions • Numerous date functions • Often vendor specific • Often used: – year – month – Date_Add(…), DateDiff(…) – Current_date(), Date_Format • Ex: where year(order_date) = 1999
  122. 122. Date Format Bookstore SQL201 Module 2 122
  123. 123. Bookstore SQL201 Module 2 123 Aggregate Functions • Count • Sum • Min • Max • Avg • Often used in conjunction with grouping
  124. 124. Bookstore SQL201 Module 2 124 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
  125. 125. Bookstore SQL201 Module 2 125 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;
  126. 126. Bookstore SQL201 Module 2 126 Aggregate Functions
  127. 127. Bookstore SQL201 Module 2 127 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
  128. 128. Bookstore SQL201 Module 2 128 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
  129. 129. Bookstore SQL201 Module 2 129 Exercise Result [end module]
  130. 130. Notes Bookstore SQL201 Module 2 130
  131. 131. Notes Bookstore SQL201 Module 2 131
  132. 132. Notes Bookstore SQL201 Module 2 132

×