1 / 29

Lecture 7 – SQL

Lecture 7 – SQL. Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join. INNER JOINS. INNER JOIN – the regular join operation SELECT fields FROM Table1 INNER JOIN Table2 ON Table1.field1=Table2.field1

hestia
Download Presentation

Lecture 7 – SQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 7 – SQL Joins – assemble new views from existing tables • INNER JOIN’s • The Cartesian Product • Theta Joins and Equi-joins • Self Joins • Natural Join

  2. INNER JOINS INNER JOIN – the regular join operation SELECT fields FROM Table1 INNER JOIN Table2 ON Table1.field1=Table2.field1 Example: SELECT * FROM COURSE c INNER JOIN Prereq p ON c.course_number = p.course_number This query could be written without the table alias.

  3. WHERE Clause and the Cartesian Product A second way of joining tables – instead of using the INNER JOIN command: SELECT * FROM Course c, Prereq p WHERE c.course_number = p.course_number Cartesian product – a binary operation in which two objects are combined. It is usually not wanted. Why? How to prevent? SELECT * FROM Course c, Prereq p;

  4. Theta Joins and Equi-joins Join with comparison operators (=,>,>=, <=. and <>) on the WHERE or ON clauses are called theta joins. Join with an = operator are called equi-joins. Join with an operator other than an = sign are called nonequi-joins. SELECT * FROM Course c INNER JOIN Prereq p ON c.course_number = p.course_number;

  5. SELF Joins On rare situations, you will need to join a table with itself – called self join. Scenario – trying to find all students who are more senior than other students: SELECT x.sname + ‘ is more senior than ‘ + y.sname FROM Student AS x, Student AS y WHERE y.class = 3 AND x.class > y.class This produces the 70 rows of output.

  6. Natural Joins Natural Join – a equi-join without the duplicate column and with the obvious join condition. Example: SELECT c.course_name, c.course_number, c.credit_hours, C.offering_dept, p.prereq FROM Course c INNER JOIN Prereq p ON c.course_number = p.course_number The implied join condition is the equality of course_number in the tables, so it is displayed only once in the result set.

  7. Using ORDER BY with a join The ORDER BY clause can be used in joins to order the output. To order the output by course_number: SELECT c.course_name, c.course_number, c.credit_hours, C.offering_dept, p.prereq FROM Course c INNER JOIN Prereq p ON c.course_number = p.course_number ORDER BY c.course_number; Or change the last line to – ORDER BY 2;

  8. Joining More than two tables • Using a nested INNER JOIN • Using a WHERE clause SELECT fields FROM table1 INNER JOIN (table2 INNER JOIN table3 ON table3.field3 = table2.field2) ON table1.field1=table2.field2; For example, if we want to see the courses that have prerequisites and the departments offering those courses, we have to first join the Course table with the prereq table, and then join that result to the Department_to_major table.

  9. Joining Multiple tables with WHERE Clause SELECT c.course_name, c.course_number, d.dname FROM Course c, Prereq p, Department_to_major d WHERE c.course_number = p.course_number AND c.offering_dept = d.dcode; Joining order depends on the database engine – thought result would be same, performance might be different. In Access, the order of joins is most easily controlled using the INNER JOIN syntax.

  10. Outer JOINs If you want to include unmatched records in an equi-join, you will need to use OUTER JOINs. • LEFT JOIN • RIGHT JOIN • FULL OUTER JOIN – union of the LEFT and RIGHT OUTER JOINs

  11. The LEFT JOIN SELECT fields FROM table1 LEFT JOIN table2 ON table1.field1 = table2.field1; LEFT OUTER JOINS includes all the records from the first (left) of the two tables, even if there are no matching values for the records in the second (right) table.

  12. The RIGHT JOIN RIGHT OUTER JOINs includes all the records from the second (right) of the two tables, even if there are no matching values for the records in the first (left) table. Access SQL does not explicitly support the FULL OUTER JOIN. Word “OUTER” is optional in Access.

  13. Functions • Aggregate Functions – COUNT, SUM, AVG, MIN, MAX, FIRST and LAST • Row-level Functions – Adding a number to a field, ROUND, NZ functions, etc. • Other Functions – TOP, BOTTOM, etc. • String • Date

  14. Aggregate Functions • Numeric aggregate functions that are used in calculations on a group of numbers, such as SUM, AVG. • The second type of aggregate functions can be used for other manipulations of multiple rows, for example, TOP or DISTINCT, in which we try to obtain a smaller set from multiple rows.

  15. The COUNT Function COUNT is a function that will generate a value of how many of something there are. SELECT COUNT(*) FROM table-name(s) Example: SELECT COUNT(grade) AS [Count of Grade] FROM Grade_report SELECT COUNT(*) AS Count FROM Student, Section, Grade_Report; Result - 321024

  16. SUM, AVG, MIN and Max Function SELECT SUM(Hours) AS [Total hours] FROM Employee; SELECT AVG(hours) AS [Average hours] FROM Employee; SELECT MIN(wage) As [Minimum Wage] FROM Employee; First and Last Functions will return corresponding row attributes.

  17. Row-Level Functions Row functions operate on single rows at a time. (1) Adding a Number to a Field SELECT wage, (wage +5) AS [wage+5] (2) The ROUND Function SELECT name, wage, ROUND))wage/3), 2) AS [wage/3] (3) The NZ Function – returns a value if a table value (or attribute is null. NZ(expression, ValueIfNull) Example: SELECT name, NZ(wage, 0)*NZ(hours,0) AS [wage*hours] (4) Other row-level functions – ABS, SIN, COS, TAN, LOG, ETC.

  18. Other Functions The TOP Function SELECT TOP 2 name, wage FROM Employee ORDER BY wage ASC; If you do not include the order by clause, the query will return rows based on the order in which they appear in the table. To get bottom rows: … ORDER BY Wage DESC; TOP can be used with PRECENT: SELECT TOP 10 PERCENT sname …

  19. The DISTINCT Function The distinct function omits records that contain duplicate data in the selected fields. SELECT DISTINCT grade FROM Grade_report; To count the number of distinct grades, two steps are required. First, create a temporary table that has the distinct grades, and then count the distinct grades from it. SELECT DISTINCT grade INTO temp1 FROM Grade_report; SELECT COUNT(grade) AS [Count of distinct grade]

  20. The DISTINCTROW Function The DISTINCTROW function omits rows based on entire duplicate records, not just duplicate fields. SELECT DISTINCTROW prereq, course_number FROM Prereq DISTINCTROW has an effect only when you select fields from some, but not all, of the tables used in the query.

  21. String Functions String functions are all row-level functions. • String Concatenation SELECT name& ‘, Esq. ‘ AS [Employee Names] FROM Employee; SELECT (‘…..’ +name) AS [Employee Names] FROM Employee; (2) String Extractors MID, INSTR, LEFT/RIGHT, LTRIM/RTRIM, UCASE/LCASE, and LEN

  22. MID, INSTR and LEFT/RIGHT MID(Stringexpression, start, length) Start tells Access where in the string expression to start retrieving from, and length tells Access how many characters to extract. INSTR(start, source_string, search_string) INSTR finds the occurrence of some search-string pattern in the string listed in the second argument. SELECT name, INSTR(1, name, ‘ ‘) AS [position of blank in name] FROM Employee; LEFT(stringexpression, n) RIGHT(stringexpression,n)

  23. LTRIM/RTRIM and UCLASE/LCASE Function LTRIM removes blanks from the beginning (left) of as string. RTRIM removes blanks from the end of a string. SELECT LTRIM(‘ Ranu’) AS name; UCASE converts a string to uppercase, while LCASE will do the opposite. SELECT UCASE(name) AS [NAMES IN CAPS] FROM Employee;

  24. The LEN/LIKE Function The LEN function returns the length of a desired string. SELECT name, LEN(name) AS [Length of Name] FROM Employee; Matching Substring Using LIKE. Using LIKE as an “existence” match entails finding whether a character string exists in an attribute – if the string existed, the row is selected for inclusion in the result set. WHERE sname LIKE ‘*Smith’;

  25. DATE Functions • The Year(number) function will extract the year from a date. SELECT YEAR(k5date) AS [Kindergarten Year], name • The MONTH function will extract the month from a date. • The DAY function extracts the day of the month from a date. • The WEEKDAY function extracts the day of the week from a date. Sunday is regarded as day 1 • The Function DATE() gives the current date.

  26. Query Development and Derived Structures • Query Development • Parentheses in SQL Expressions • Derived Structure • Query Development with Derived Structures

  27. Query Development • Experimentation • Modifying previous stored queries Best way to understand how query building process works is to look at an example. Suppose we want to find the names of all students in the standard student.mdb database who major in computer science (COSC) and have earned a grade of B in some course.

  28. Derived Structures • Derived structures help us to build queries on top of other queries. • Views • Temporary tables A view (virtual table, a saved query.): • Save space • Permission control

  29. Using Views • View can be used just like a table • A view has no data of its own • Views depend on the underlying tables • If a record were added or deleted from the view, the same change would also appear in the original table • If data is changed in the original table, the same data in all the views related to that table also gets changed.

More Related