Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2012 Pearson Education, Inc. All rights reserved.

Similar presentations


Presentation on theme: " 2012 Pearson Education, Inc. All rights reserved."— Presentation transcript:

1  2012 Pearson Education, Inc. All rights reserved.
Chapter 18 Introduction to SQL Part I Based on text [2]  2012 Pearson Education, Inc. All rights reserved. expanded by J. Goetz

2 It is a capital mistake to theorize before one has data.
Arthur Conan Doyle Now go, write it before them in a table, and note it in a book, that it may be for the time to come for ever and ever. Isaiah 30:8 Get your facts first, and then you can distort them as much as you please. Mark Twain I like two kinds of men: domestic and foreign. Mae West

3 Outline Introduction Relational Database Model Relational Database Overview: Books Database Structured Query Language (SQL) Basic SELECT Query WHERE Clause ORDER BY Clause Merging Data from Multiple Tables: INNER JOIN Joining Data from Tables Authors, AuthorISBN, Titles and Publishers INSERT Statement UPDATE Statement DELETE Statement

4 18.1 Introduction Database: Integrated collection of data
Database management system (DBMS) Provides mechanisms for storing and organizing data in a way that is consistent with database’s format Allows storage and access to database without knowledge of internal representation Relational Databases most popular Use Structured Query Language SQL to perform queries (search) and manipulate data Programming languages need an interface to interact with relational databases

5 18.2 Relational Database Model
Is logical representation of data that allows relationships among data to be considered without concern for physical structure of data Is composed of tables Rows called records Columns called fields Primary key: field that contains unique data Records normally are unique (by primary key) within a table Each record can be identified by at least one distinct value New sets made from queries called result sets

6 18.2 Relational Database Model
number name department salary location 23603 Jones 413 1100 New Jersey 24568 Kerwin 2100 34589 Larson 642 1800 Los Angeles 35761 Myers 611 1400 Orlando 47132 Neumann 9000 78321 Stephens 8500 record/row field/column primary key Fig Relational-database structure of an Employee table. The records ordered by primary key. department location 413 New Jersey 642 Los Angeles 611 Orlando Fig Result set formed by selecting Department and Location data from the Employee table.

7 18.2 Relational Database Model
Each column represents a different data attribute. Most users of a database use only subsets of the rows and columns. Programs use SQL to define queries that select subsets of the data from a table (Fig. 18.2). Fig | Distinct Department and Location data from the Employees table.

8 18.3 Relational Database Overview: Books Database
Rule of Entity Integrity: every record must have a unique value in its primary-key field Compound Primary key: when a record has a unique key based on a combination of two fields Foreign key: Field for which every entry has a unique value in another table and where the field in the other table is the primary key for that table Rule of Referential Integrity: every foreign-key field value must appear in another table’s primary-key field One to many relationship: A foreign key can appear many times in its own table, but only once as primary key in another table

9 18.3 Relational Database Overview: Books Database

10 18.3 Relational Database Overview: Books Database (Cont.)
The Titles table (described in Fig. 18.5) consists of four columns. Fig | Titles table of the Books database.

11 18.3 Relational Database Overview: Books Database (Cont.)
Figure 18.6 contains the data from the Titles table. Fig | Data from the Titles table of the Books database.

12 18.3 Relational Database Overview: Books Database (Cont.)
The AuthorISBN table (described in Fig. 18.7) matches the AuthorID and ISBN columns. These foreign keys form a composite primary key. Fig | AuthorISBN table of the Books database.

13 18.3 Relational Database Overview: Books Database (Cont.)
Figure 18.8 contains the data from the Author­ISBN table of the Books database. Fig | Data from the AuthorISBN table of Books.

14 18.3 Relational Database Overview: Books Database
Rule of Entity Integrity: every record must have a unique value in its primary-key field Compound Primary key: when a record has a unique key based on a combination of two fields Foreign key: Field for which every entry has a unique value in another table and where the field in the other table is the primary key for that table Rule of Referential Integrity: every foreign-key field value must appear in another table’s primary-key field One to many relationship: A foreign key can appear many times in its own table, but only once as primary key in another table Foreign keys also allow related data in multiple tables to be joined.

15 18.3 Relational Database Overview: Books Database (Cont.)
Common Programming Error 18.1 Not providing a value for every column in a primary key breaks the Rule of Entity Integrity and causes the DBMS to report an error. Common Programming Error 18.2 Providing the same value for the primary key in multiple rows breaks the Rule of Entity Integrity and causes the DBMS to report an error. Common Programming Error 18.3 Providing a foreign-key value that does not appear as a primary-key value in another table breaks the Rule of Referential Integrity and causes the DBMS to report an error.

16 18.3 Relational Database Overview: Books Database (Cont.)
Figure 18.9 is an entity-relationship (ER) diagram for the Books database. Note that primary keys are italic. On the Authors end of the line, there is a 1, and on the AuthorISBN end, an infinity symbol (∞), indicating a one-to-many relationship. Fig | Entity-relationship diagram for the Books database.

17 18.3 Books Database Fig. 18.11 Table relationships in Books.
Lines represent the link between the foreign key in one table and the primary in another table The fields whose names appears in italic and with a 1 contains that tables’s primary key. The AuthorISBN table contains a compound primary key. publisherID in the Titles table is a foreign key

18 18.4 Structured Query Language (SQL)
SQL - used to request data (perform queries) and manipulate data

19 Extracts information from one or more tables in a database Format:
18.4.1Basic Select Query Extracts information from one or more tables in a database Format: Basic: SELECT * FROM tableName e.g.: SELECT * FROM Authors * extracts all columns from the tableName table should be retrieved. To get specific fields use a comma separated list instead of *

20 18.4 Structured Query Language (SQL)
To retrieve only specific columns, use a list of the column names: SELECT AuthorID, LastName FROM Authors This query returns the data listed in Fig. 18.11. Fig | AuthorID and LastName data from the Authors table.

21 Used to specify certain criteria in a query
Where Clause Used to specify certain criteria in a query The basic form of a query with selection criteria is SELECT columnName1, columnName2, FROM tableName WHERE criteria SELECT * FROM tableName WHERE criteria Example: SELECT * FROM Titles WHERE copyright > 1999 Can use LIKE clause Used for pattern matching Uses wildcards *: zero or more characters take its place in Access, Linux ?: exactly one character takes its place in Acceess, Linux

22 18.4 Structured Query Language (SQL)
To select books for which the Copyright is more recent than 2007: SELECT BookTitle, EditionNumber, Copyright. FROM Titles WHERE Copyright > '2007' Figure 18.12 shows the result of the preceding query. Fig | Books with copyright dates after 2007 from table Titles.

23 18.4.2 WHERE Clause SELECT authorID, firstName, lastName FROM Authors
The following query locates authors whose last names start with the letter D: SELECT authorID, firstName, lastName FROM Authors WHERE lastName LIKE ‘D%’ The % indicates that any number of chrs can appear after the letter D SELECT authorID, firstName, lastName FROM Authors WHERE lastName LIKE ‘_i%’

24 18.4 Structured Query Language (SQL)
An underscore (_) indicates a single wildcard character at that position. The following query locates authors whose last names have the letter y as the second letter. SELECT AuthorID, FirstName, LastName FROM Authors WHERE LastName LIKE '_y%' Fig | The only author from the Authors table whose last name contains y as the second letter.

25 18.4 Structured Query Language (SQL)
18.4.3 ORDER BY Clause Rows in the result can be sorted into ascending or descending order by using the optional ORDER BY clause. SELECT columnName1, columnName2, FROM tableName ORDER BY column ASC ORDER BY column DESC ASC specifies ascending order, DESC specifies descending order column specifies the column on which the sort is based.

26 Used to arrange results of a query
ORDER BY Clause Used to arrange results of a query Can be ascending or descending order Uses ASC and DESC respectively Example: SELECT authorID FROM Authors ORDER BY authorID ASC Can be used to sort by multiple fields

27 18.4 Structured Query Language (SQL)
To obtain the list of authors in ascending order by last name (Fig. 18.15), use the query SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName ASC Fig | Authors from table Authors in ascending order by LastName.

28 18.4 Structured Query Language (SQL)
To obtain the same list of authors in descending order by last name (Fig. 18.16), use SELECT AuthorID, FirstName, LastName FROM Authors ORDER BY LastName DESC Fig | Authors from table Authors in descending order by LastName.

29 18.4 Structured Query Language (SQL)
Multiple columns can be used for sorting with an ORDER BY clause: ORDER BY column1 sortingOrder, column2 sortingOrder,… Note that the sortingOrder does not have to be identical for each column. SELECT BookTitle, EditionNumber,Copyright FROM Titles ORDER BY Copyright DESC, BookTitle ASC This query returns books sorted first in descending order by copyright date, then in ascending order by title (Fig. 18.17).

30 18.4 Structured Query Language (SQL)
Fig | Data from Titles in descending order by Copyright and ascending order by BookTitle. SELECT BookTitle, EditionNumber,Copyright FROM Titles ORDER BY Copyright DESC, BookTitle ASC This query returns books sorted first in descending order by copyright date, then in ascending order by title (Fig. 18.17).

31 18.4 Structured Query Language (SQL)
The WHERE and ORDER BY clauses can be combined. ORDER BY must be the last clause in the query. SELECT ISBN, BookTitle, EditionNumber, Copyright FROM Titles WHERE BookTitle LIKE '%How to Program' ORDER BY BookTitle ASC

32 18.4 Structured Query Language (SQL)
18.4.4 Retrieving Data from Multiple Tables: INNER JOIN Database designers typically normalize databases - i.e., split related data into separate tables to ensure that a database does not store redundant data. For example, we use a table to store “links” between authors and titles. If we did not separate this information into individual tables, we would need to include author information with each entry in the Titles table.

33 18.4.4 Merging Data from Multiple Tables: INNER JOIN
Merges records from multiple tables into a single record Tests for matching values in a common field General Form: SELECT * FROM table1 INNER JOIN table2 ON table1.fieldName=table2.fieldName Example: SELECT firstName, lastName, isbn FROM Authors INNER JOIN AuthorISBN ON Authors.authorID= AuthorISBN.authorID Fully-qualified names use the table name and dot operator followed by the field name

34 18.4.4 Merging Data from Multiple Tables: INNER JOIN
The ON clause specifies the columns from each table that are compared to determine which rows are merged. SELECT FirstName, LastName, ISBN FROM Authors INNER JOIN AuthorISBN ON Authors.AuthorID = AuthorISBN.AuthorID ORDER BY LastName, FirstName Fig | Authors and ISBNs for their books in ascending order by LastName and FirstName. (Part 1 of 2.)

35 18.4 Structured Query Language (SQL)
Fig | Authors and ISBNs for their books in ascending order by LastName and FirstName. (Part 2 of 2)

36 18.4.6 Insert Statement Inserts a new record into a table Form:
INSERT INTO tableName(fieldName1, fieldName2,…,fieldNameN) VALUES (value1, value2, …,valueN) Ex: INSERT INTO Authors (firstName, lastName) VALUES (‘Sue’, ‘Smith’) Values must match field names in order and type

37 18.4 Structured Query Language (SQL)
INSERT INTO Authors (firstName, lastName) VALUES (‘Sue’, ‘Smith’) AuthorID is an identity column, so it is assigned the next value in an autoincremented sequence. Fig | Table Authors after an INSERT operation.

38 18.4 Structured Query Language (SQL)
Common Programming Error 18.5 It is an error to specify a value for an identity column in an INSERT statement. Common Programming Error 18.6 To specify a string containing a single quote in a SQL statement, there must be two single quotes in the position where the single-quote character appears in the string (e.g., 'O''Malley').

39 Modifies data in a table Form: UPDATE tableName
UPDATE Statement Modifies data in a table Form: UPDATE tableName SET fieldName1 = value1, fieldName2 = value2, … WHERE criteria Ex: UPDATE Authors SET LastName = 'Jones‘ WHERE LastName = 'Smith' AND FirstName = 'Sue'

40 Fig. 18.21 | Table Authors after an UPDATE operation.
UPDATE Statement Fig | Table Authors after an UPDATE operation. UPDATE Authors SET LastName = 'Jones‘ WHERE LastName = 'Smith' AND FirstName = 'Sue' Keyword AND is a logical operator that returns true if and only if both of its operands are true. SQL also provides other logical operators, such as OR and NOT.

41 Fig. 18.22 | Table Authors after a DELETE operation.
DELETE Statement Removes data from a table Form: DELETE FROM tableName WHERE criteria DELETE FROM Authors WHERE LastName = 'Jones' AND FirstName = 'Sue' Fig | Table Authors after a DELETE operation.


Download ppt " 2012 Pearson Education, Inc. All rights reserved."

Similar presentations


Ads by Google