Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Relational Database and SQL Minder Chen CSU Channel Islands

Similar presentations


Presentation on theme: "Introduction to Relational Database and SQL Minder Chen CSU Channel Islands"— Presentation transcript:

1

2 Introduction to Relational Database and SQL Minder Chen CSU Channel Islands Minder.Chen@CSUCI.EDU

3 RDBMS&SQL - 2 ©Minder Chen, 1996-2011 What is a RDBMS? A Data Base (DB) is an integrated collection of shared data designed to meet the varied information needs of an organization. A Data Base Management System (DBMS) consists of a collection of software program that receives and satisfies all requests for data. A Relational Data Base Management System (RDBMS) is a DBMS which processes data with the Relational Data Model.

4 RDBMS&SQL - 3 ©Minder Chen, 1996-2011 History of RDBMS The relational database model was originally developed by Dr. E.F. Codd in the early 1970s The SQL language was originally developed by IBM in a prototype relational database management system, System R, in the mid 1970s. The original SQL language (SEQUEL 2) was described in IBM Journal of R&D, November 1976. In 1979, Oracle Corporation introduced the first commercially available implementation of SQL. SQL has also been implemented in IBM's DB2 and SQL/DS database systems in the mid 1980s. Today SQL is widely implemented and is accepted as the industry standard database access language.

5 RDBMS&SQL - 4 ©Minder Chen, 1996-2011 Database Technology Before Relational systems people has been using: - File Systems like ISAM, VSAM and B-Tree; - Hierarchy Database; - Network Database. RDBMS has both a physical and a logical structure. By doing so, the physical storage of data can be managed without affecting the access to logical storage structures. File SystemsHierarchyNetworkRelational

6 RDBMS&SQL - 5 ©Minder Chen, 1996-2011 Relational Database Introduction A relational data base is perceived by its users as a collection of tables Invented by E. F. Codd in 1969 Dominate the markets since late 1980s Strengths: –Simplicity –End-user orientation –Standardization (SQL – Structured Query Language) –Value-based instead of pointer-based to provide data independence –Endorsed by major computer companies Most CASE products support the development of relational data base centered applications

7 RDBMS&SQL - 6 ©Minder Chen, 1996-2011 SQL Terminology p_nonamequantityprice 101 Color TV24500 201B&W TV10250 202PC 52000 Product Table Row Column Set Theory Relational DB File Example Relation Table File Product_table Attribute Column Data itemProduct_name TupleRow Record Product_101's info. Domain Data TypeData type DATE or Domain

8 RDBMS&SQL - 7 ©Minder Chen, 1996-2011 SQL Terminology CREATE TABLE PRODUCT (p_noCHAR(5)NOT NULL, nameCHAR(20), quantitySMALLINT, priceDECIMAL(10, 2)); INSERT INTO PRODUCT VALUES (101, 'Color TV', 24, 500); INSERT INTO PRODUCT VALUES (201, 'B&W TV ', 24, 500); INSERT INTO PRODUCT VALUES (202, 'PC', 5, 2000); SELECT p_no, name, price FROM PRODUCT WHERE PRICE > = 1000; p_nonameprice ------------------------------ 202PC2000 CREATE TABLE PRODUCT (p_no CHAR(5) NOT NULL, Name CHAR(20), Quantity INTEGER, Price Currency, CONSTRAINT pk_product PRIMARY KEY (p_no)); In Access

9 RDBMS&SQL - 8 ©Minder Chen, 1996-2011 SQL: Data Manipulation Language (DML) SELECT UPDATE INSERT DELETE SELECT UPDATE INSERT DELETE p_nonamequantityprice 101 Color TV24500 201B&W TV10250 202PC 52000 SELECT p_no, name, price FROM PRODUCT WHERE PRICE < = 1000 ORDER BY PRICE DESC; p_nonameprice -------------------------------- 101 Color TV500 201B&W TV250

10 RDBMS&SQL - 9 ©Minder Chen, 1996-2011 SQL Principles The result of a SQL query is always in a table like format and is not stored (View or Dynamic Table). The definition of a query can be stored. Rows in a table are considered to be unordered. Columns sequence in a table is irrelevant in your database queries. Can be used in interactive programming environments. Provide both data definition language (DDL), data manipulation language (DML), and data control language (DCL). It is a non-procedural language. Can be embedded in 3GL (third generation languages), such as C, COBOL, etc.: –Embedded SQL: Embedding SQL statements in host languages. –Dynamic SQL: Constructing SQL statements dynamically.

11 RDBMS&SQL - 10 ©Minder Chen, 1996-2011 Database Application in the Client/Server Environments Customer Management Name: John Doe Address: 101 Dalmation Street Salary: $43,000 Age: 34 PF1 - Help PF2 - Add PF3 - Update File Edit Window Help Customer Management Name: Address: Salary: John Doe 101 Dalmation St. $48,000 Cancel Loan History Update Age: 34 CUI client GUI client Database Server Disks & Files Enter details and press PF3 to update Networks

12 RDBMS&SQL - 11 ©Minder Chen, 1996-2011 Database Server in the Client-Server Architecture User File Server Client Application Database Server 23 4 5 1. User enters query through client application's user interface. 2. Client application sends the formulated query to the data base server. 3. Database server processes request. Search all records. 4. Database server returns only the results from the query. 5. Client application's user interface displays retrieved information. Mechanism Mechanism: SQL via SQL*Net, ODBC, Stored Procedures, Remote Procedure Calls Access is not a database server. 3 Client Machine Server Machine 1

13 RDBMS&SQL - 12 ©Minder Chen, 1996-2011 Data Software Layers Using Oracle as Example Operating Systems Oracle Server SQL PL/SQL Developer/2000 (Forms, Reports, Graphics) SQL*Plus Custom-build Oracle Database Applications JDeveloper Procedure Builder Visual Web Developer Visual Studio.NET Designer/2000

14 IndicesStatistical data Data files Transaction manager Buffer manager File manager Application programs object code Query evaluation engine Embedded DML precompiler DML precompiler DDL interpreter Application interface 3GL & 4GL Query tools Database schema Naïve users (tellers, agents,etc) Application programmers Sophisticated users Database Administrator Query processor Storage manager Disk storage DBMS Users 3GL: Third Generation Languages such as C and COBOL 4GL: Fourth Generation Language such as Visual Basic and PowerBuilder Data dictionary

15 RDBMS&SQL - 14 ©Minder Chen, 1996-2011 Database Structures The database structures should be understood in different views at different stages or for different viewers. In 1974, the following conceptual framework was introduced in a conference at New Orleans city, so called New Orleans Schema. It is also known as ANSI/X3/SPARC DBMS Framework. Conceptual Schema Application Schema 1 Application Schema N Logical Schema Physical Schema Logical Database Physical Database e. g., E-R Diagram External level (Individual User View) Conceptual View (Community User View) Internal Level (Storage View) * E-R Diagram: Entity Relationship Diagram

16 RDBMS&SQL - 15 ©Minder Chen, 1996-2011 Benefits of RDBMS Integration of Data: Data are organized into a single, logical structure with logical relationships defined between associated data entities to eliminate redundancy and inconsistency. Sharing of Data: All qualified users in the organization have access to the same data, for use in a variety of activities or applications. Enforcement of Standards: Centralized data administration function has authority for defining and enforcing data standards. All changes to the data standards would have to be approved by the Database Administrator. Ease of Application Development: An end user/ programmer is no longer saddled with the burden of designing, building and maintaining traditional master files.

17 RDBMS&SQL - 16 ©Minder Chen, 1996-2011 Benefits of RDBMS Uniform Security, Privacy and Integrity Controls: The data administration function has complete jurisdiction over the database and is responsible for establishing controls for accessing, updating and protection data. Centralized control and standard procedures can offer improved level of data base protection. Data Accessibility and Responsiveness: Provides multiple retrieval paths to each item of data, giving a user much greater flexibility in locating and retrieving data. A database system is generally much more responsive to changing information requirements. Data Independence: The separation of data descriptions from application programs that use the data.

18 RDBMS&SQL - 17 ©Minder Chen, 1996-2011 Benefits of RDBMS Reduce Program Maintenance: Due to the data independence in a database system, within limits, either the data or the application program that use the data can be changed without necessitating a change in the others. User Friendly: SQL is a non-procedural easy-to-learn language. It allows you to work with higher level data structures. Rather than manipulating single rows. A user can gets the desired data simply by specifying SQL without go through complex procedure programming language. Supported by Mathematics Theory: RDBMS is the only DBMS that is supported by mathematics theory. The relational algebra is formed by a set of operators, each of which maps one or more relations into another relation.

19 RDBMS&SQL - 18 ©Minder Chen, 1996-2011 The Relational Model A model represents both entities and relationships in a flat file (table) structure. Relation: A mathematical concept about an entity or a relationship. Properties of a Relation: - No duplicate rows in a relation (table). - The order of rows in a relation is insignificant - The order of columns in a relation is insignificant. - All attributes must be atomic (single value). - Each row must be uniquely identified by a primary key. In the relational model, data are logically presented in two dimensional tables (files) made up of rows (tuples, records) and columns (attributes, fields, data item).

20 RDBMS&SQL - 19 ©Minder Chen, 1996-2011 The Relational Model Table: A table is a group of homogeneously defined records, all with identical field names and types. Within a database, each table has a unique name. Row: The rows of a table are known as records. They are made up of a collection of values that describe an entity. Field: A field is the intersection of a row and a column in a table or query result. Key: An attribute or a set of attributes which can uniquely identify a row in a table.

21 RDBMS&SQL - 20 ©Minder Chen, 1996-2011 The Relational Model DIVISION INSTRUCTOR PK FK

22 RDBMS&SQL - 21 ©Minder Chen, 1996-2011 The Relational Model Primary Key: A key chosen to identify the rows in a table. Simple Key: A key contains only one column. Compound(Composite, Concatenated) Key: A key has more than one column. Alternate Key: A key which is other than the primary key in a relation. Foreign Key: An attribute or a set of attributes appears in a table which also plays the role of a primary key in another tables. Question: What is the trick to implement relationships in the relational model?

23 RDBMS&SQL - 22 ©Minder Chen, 1996-2011 The Relational Model Index: An index is a data structure used to speed up data retrieval or enforce certain constraints on the records in a table. Relational databases use automatic query optimization algorithms to determine which indices to use when searching the database, therefore the user does not specify which indices to use in a search. Null value: A null value is an empty or undefined value for a field. It indicates that there is presently no data available for the field instance. View: A view is a logic representation of another table or combination of tables. A view derives its data from the tables on which it is based. Views permit you to query subsets of data, or joins of multiple tables as though they are an actual table. Only the view definition is stored in the database, not the data retrieved by a view. Some views are updateable; update commands actually affect the underlying table. View is called (stored) Query in Access.

24 RDBMS&SQL - 23 ©Minder Chen, 1996-2011 The Relational Model Referential Integrity: The relationship between a referencing (child) table and a referenced (parent) table. The referential integrity rule requires that, for any value in the referencing columns, there must exist a row in the referenced table such that the value of the referencing columns equals the value of the corresponding referenced columns. Essence of a Relational Data Model: –Representation of Entities –Representation of Relationship –Database Integrity Rules: »Primary Key Rule »Referential Integrity Rule »Existing Rule (NOT NULL) »Value Checking Rule –DB Languages: DDL, DML, DCL

25 RDBMS&SQL - 24 ©Minder Chen, 1996-2011 Foreign Keys & Primary Keys in a Sample Database (ACCESS)

26 RDBMS&SQL - 25 ©Minder Chen, 1996-2011 SQL Programming SQL is a standard language used to define and manipulate data in a RDBMS, and can be used interactively or embedded in host languages such as C, PASCAL, COBOL, etc. SQL generally functions on sets of records rather than individual records. References to data are symbolic; they do not use any physical data structures such as pointers. SQL are divided into three sublanguages: –DDL (Data Definition Language) –DML (Data Manipulation Language) –DCL (Data Control Language)

27 RDBMS&SQL - 26 ©Minder Chen, 1996-2011 SQL Programming Data Definition Language (DDL) –Create, alter and drop database and database objects –Impose integrity constraints on tables –Automatically update system catalog tables –Add comments to the tables. Data Manipulate Language (DML) –Retrieve, –insert, –update, and –delete rows from database tables. Data Control Language (DCL) –Grant and Revoke privileges and roles –Controls concurrent access to database.

28 RDBMS&SQL - 27 ©Minder Chen, 1996-2011 CREATE TABLE CREATE TABLE division (D_ID CHAR(4)NOT NULL, DIRNUMBER(4), DIV_NAMEVARCHAR(15)NOT NULL, CONSTRAINT pk_division PRIMARY KEY (D_ID)); Table name Primary Key Column(s) Data Type Mandatory or Optional * The Primary Key column(s) of a table should be "NOT NULL" A Constraint Name A Constraint Type

29 RDBMS&SQL - 28 ©Minder Chen, 1996-2011 Create a Table in Access CREATE TABLE division2 (D_ID CHAR(4)NOT NULL, DIRInteger, DIV_NAMEVARCHAR(15)NOT NULL, CONSTRAINT pk_division PRIMARY KEY (D_ID)); What is AutoNumber in Access?

30 RDBMS&SQL - 29 ©Minder Chen, 1996-2011 Basic Elements Character Set –The upper- and lower-case letters A.. Z, a.. z –The numerals 0.. 9 –Tabs, spaces, and carriage returns –The symbols ( ) + - * / = ! ~ ; :. ' @ %, " # $ ^ & | _ { } ? [ ] Identifiers An identifier consists of a letter optionally followed by more letters, numerals and the special characters ‘#’, ‘$’, ‘_’, ‘%’, ‘&’. Comments –Single-line comments begin with a double hyphen (--) anywhere on a line and extend to the end of the line. –Multiline comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines.

31 RDBMS&SQL - 30 ©Minder Chen, 1996-2011 Data Types Every constant and variable has a data type, which specifies a storage format, constraints, and valid range of values. –NUMBER: General numeric type. –DEC(p,s): Decimal value. Precision(p) is the total number of digits. Scale(s) is the number of fractional digits. E.g., 9999.99 should be declared as DEC(6,2) –FLOAT: Single precision floating-point number. –SMALLINT: Half word (2 bytes) binary integer. Value can range from -32767 to 32767. –INT: Full word(4 bytes) binary integer. Value can range from -2147483647 to 2147483647. –CHAR: Fixed length character string. –VARCHAR: Variable length character string. –DATE: Data stored in Gregorian date format.

32 RDBMS&SQL - 31 ©Minder Chen, 1996-2011 NULL DATA ELEMENT CHARACTERISTIC A B C NOT NULL must be a given value, including blank or zero. NULL Value not required. (Column flagged null -- “empty value”) NOT NULL WITH DEFAULT will provide default value if one is not entered.

33 RDBMS&SQL - 32 ©Minder Chen, 1996-2011 NULL NOTE: In SQL, NULL is an empty value, it is not equal to blank or space. Be aware of the results when use NULL in: –COMPARISON:Result is unknown –COMPUTATION:Result is unknown –FUNCTIONS:Null rows are omitted from AVG, SUM, MAX and MIN functions. –COUNT(DISTINCT): Does not count NULLS.

34 RDBMS&SQL - 33 ©Minder Chen, 1996-2011 Operators Logical negation:NOT Identity:+ Negation:- Multiplication:* Division:/ Addition:+ Subtraction:- Concatenation:|| Comparison:=, !=,, =, IS NULL, LIKE, BETWEEN, IN, EXIST,ALL, SOME, ANY Conjunction:AND Inclusion:OR

35 RDBMS&SQL - 34 ©Minder Chen, 1996-2011 PRIMARY KEY A PRIMARY KEY constraint is identical to a UNIQUE constraint, except that a table can have at most one constraint condition specified as a PRIMARY KEY. The purpose of the primary key is to uniquely identify each row of a table. The fields in the primary key must be defined as NOT NULL. A unique index will be built automatically by RDBMS on the primary key.

36 RDBMS&SQL - 35 ©Minder Chen, 1996-2011 FOREIGN KEY FOREIGN KEY is used to enforce referential integrity -- the relationship between referencing (child) table and a referenced (parent) table. The referential integrity rule requires that, for any value in the referencing columns, there must exist a row in the referenced table such that the value of the referencing columns equals the value of the corresponding referenced columns. This is enforced as the following: –UPDATE/INSERT Rule: The set of values placed in the referencing columns must match a set of values that exists in the referenced table. –DELETE Rules (When you delete rows of the referenced table): »RESTRICT: The row in referenced table can be deleted if no other row referencing it. »SET NULL: That each nullable column of the matched foreign key in each referencing row is set to null. »CASCADE: The designated rows in the referenced table and all match referencing rows will be deleted.

37 RDBMS&SQL - 36 ©Minder Chen, 1996-2011 FOREIGN KEY In order to create a referential integrity constraint, you must create a FOREIGN KEY constraint on the referencing table. The FOREIGN KEY constraint must reference the PRIMARY (or a UNIQUE) KEY on the referenced table. alter table OFFERING add constraint FK_OFFERING_OFFERS_FOR_COURSES foreign key (C_ID) references COURSE (C_ID) ON DELETE CASCADE; The foreign key must reference an existing UNIQUE or PRIMARY KEY. An index will be built on the referencing columns. create index Offers_for_Courses_FK on OFFERING (C_ID asc) Referenced table PK in the Referenced table Column name(s) of the referencing table Referencing table

38 RDBMS&SQL - 37 ©Minder Chen, 1996-2011 Sample Database REGISTRATION OFFERING COURSE INSTRUCTOR DIVISION STUDENT

39 RDBMS&SQL - 38 ©Minder Chen, 1996-2011 Relationships in Access Database

40 RDBMS&SQL - 39 ©Minder Chen, 1996-2011 Edit Relationships in Access Referential Integrity

41 RDBMS&SQL - 40 ©Minder Chen, 1996-2011 DDL CREATE DATABASE: Creates a database. CREATE TABLE: Creates a table and defines its columns and their data types. CREATE SYNONYM: Creates an alternate name for a table or view. CREATE VIEW: Defines a logical table, or view of data derived from columns and rows of existing tables and views. CREATE INDEX: Creates an index on one or more columns of a table, for the purpose of speeding data retrieval, and enforcing uniqueness constraints. ALTER: Adds, removes or renames table columns, or changes the data types of columns. Also used to create or drop UNIQUE, PRIMARY, FOREIGN KEY and CHECK constraints to enforce uniqueness, referential integrity.

42 RDBMS&SQL - 41 ©Minder Chen, 1996-2011 DDL DROP DATABASE: Deletes database and all objects associated with it. DROP TABLE: Deletes a table and the indexes built on that table. DROP SYNONYM: Deletes an alternate name for a table or view from the system catalog. DROP VIEW: Deletes a view from the system catalog. DROP INDEX: Deletes a specified index. Note that an index created as the result of a UNIQUE, PRIMARY or FOREIGN KEY constraint can only be dropped by dropping the constraint through the ALTER command. RENAME: Changes a table name. COMMENT ON: Places a remark on a database object in the appropriate system catalog table.

43 RDBMS&SQL - 42 ©Minder Chen, 1996-2011 DML SELECT: Retrieves data from one or more tables. UPDATE: Modifies the data in one or more rows of a table. INSERT: Inserts one or more rows into a table. DELETE: Deletes one or more rows from a table.

44 RDBMS&SQL - 43 ©Minder Chen, 1996-2011 DCL COMMIT: Instructs the system to make all DML commands executed by a transaction permanent. ROLLBACK: Instructs the system to reverse all DML commands executed by a transaction. GRANT: Assigns database access privileges to database users. REVOKE: Cancels database access privileges from database users. LOCK: Permits users to explicitly acquire table locks. UNLOCK: Used to unlock a table prior to the commit point.

45 RDBMS&SQL - 44 ©Minder Chen, 1996-2011 CREATE TABLE: Data Type in Access CREATE TABLE STUDENT (S_NONUMBER(4)NOT NULL, NAMEVARCHAR(10), ADDRESSVARCHAR(10), CITYVARCHAR(10), STATEVARCHAR(2), ZIPNUMBER(5), TEL_NOVARCHAR(10), CONSTRAINT S_NO_ZERO CHECK (S_NO > 0), CONSTRAINT STUDENT_PRIMARY_KEY PRIMARY KEY (S_NO)); NOTE: The fields in the primary key must be defined as NOT NULL.

46 RDBMS&SQL - 45 ©Minder Chen, 1996-2011 CREATE TABLE CREATE TABLE INSTRUCTOR (I_NONUMBER(4)NOT NULL, F_NAMEVARCHAR(8)NOT NULL, MCHAR(1)NOT NULL, L_NAMEVARCHAR(5)NOT NULL, DIVCHAR(4), TELVARCHAR(10), D_O_HDATE, TITLEVARCHAR(8), EDSMALLINT, SEXCHAR(1), D_O_BDATE, SALARYDECIMAL(9,2), CONSTRAINT INSTRUCT_FOREIGN_KEY FOREIGN KEY (DIV) REFERENCES DIVISION(D_ID), CONSTRAINT INSTRUCT_PRIMARY_KEY PRIMARY KEY (I_NO));

47 RDBMS&SQL - 46 ©Minder Chen, 1996-2011 CREATE TABLE CREATE TABLE COURSE (C_ID CHAR(4)NOT NULL, TITLEVARCHAR(10) NOT NULL, DIVCHAR(4)NOT NULL, FEEDECIMAL(5,2), CONSTRAINT COURSE_FOREIGN_KEY FOREIGN KEY (DIV) REFERENCES DIVISION(D_ID), CONSTRAINT COURSE_PRIMARY_KEY PRIMARY KEY (C_ID));

48 RDBMS&SQL - 47 ©Minder Chen, 1996-2011 CREATE TABLE CREATE TABLE OFFERING (C_IDCHAR(4)NOT NULL, O_NONUMBER(4)NOT NULL, START_DATEDATENOT NULL, LOCATIONVARCHAR(12), CONSTRAINT OFFERING_FOREIGN_KEY FOREIGN KEY (C_ID) REFERENCES COURSE(C_ID) ON DELETE CASCADE, CONSTRAINT OFFERING_PRIMARY_KEY PRIMARY KEY (C_ID, O_NO));

49 RDBMS&SQL - 48 ©Minder Chen, 1996-2011 CREATE TABLE CREATE TABLE REGISTRATION (C_IDCHAR(4)NOT NULL, O_NONUMBER(4)NOT NULL, S_NONUMBER(4)NOT NULL, GRADESMALLINT, CONSTRAINT REGISTRATION_FOREIGN_KEY FOREIGN KEY (C_ID,O_NO) REFERENCES OFFERING(C_ID, O_NO) ON DELETE CASCADE, CONSTRAINT STUDENT_FOREIGN_KEY FOREIGN KEY (S_NO) REFERENCES STUDENT(S_NO), CONSTRAINT REGISTRATION_PRIMARY_KEY PRIMARY KEY (C_ID, O_NO, S_NO));

50 RDBMS&SQL - 49 ©Minder Chen, 1996-2011 Create Index This command creates an index on one or more columns of a table. TYPE OF INDEXES –UNIQUE INDEX: An index built on a unique columns (or columns) in a table. –NON-UNIQUE INDEX: An index built on a columns (or columns) which may have the same value in more than one row. EXAMPLE CREATE UNIQUE INDEX DIVISION_NAME ON DIVISION(DIV_NAME ASC); CREATE INDEX LOC_INDEX ON OFFERING(LOCATION DESC);

51 RDBMS&SQL - 50 ©Minder Chen, 1996-2011 Create View This command is used to define a view (a logical or virtual table) based on one or more (base) tables or views. In Access, views are saved queries. CREATE VIEW TEACHER AS SELECT I_NO, F_NAME, L_NAME, TITLE, SALARY FROM INSTRUCTOR WHERE TITLE = 'TEACHER'; SELECT * FROM TEACHER; I_NO F_NAME L_NAM TITLE SALARY --------- -------- ----- -------- --------- 19 ALBERT STONE TEACHER 60000 21 BRUCE FLYNN TEACHER 48000

52 RDBMS&SQL - 51 ©Minder Chen, 1996-2011 Using a View Query against a saved query SELECT * FROM TEACHER WHERE SALARY >= 50000; I_NO F_NAME L_NAM TITLE SALARY --------- -------- ----- -------- --------- 19 ALBERT STONE TEACHER 60000 The query is merged with the defining query of the view TEACHER to produce the following query to be executed by the DBMS: SELECT I_NO, F_NAME, L_NAME, TITLE, SALARY FROM INSTRUCTOR WHERE TITLE = 'TEACHER' and SALARY >= 50000; DROP VIEW TEACHER; - - Delete the view

53 RDBMS&SQL - 52 ©Minder Chen, 1996-2011 Create View Define a subset of a single table. Combine data from two or more tables. The data presented via the view is retrieved dynamically from the base table. Restrictions: –ORDER BY and UNION can not be used in the definition of a view. –A view is "read only" if its definition involves »A JOIN »The keyword DISTINCT »A GROUP BY clause »A HAVING clause »A function –If you insert a row into a view, the base table columns that are not in the view must allow NULLs or set to default values.

54 RDBMS&SQL - 53 ©Minder Chen, 1996-2011 PROCESSVIEWBASE TABLE SELECT UPDATE COLUMN DELETE ROW INSERT ROW Processing A View ? NULL or default value

55 RDBMS&SQL - 54 ©Minder Chen, 1996-2011 Access DMBS: DMBS vs Database

56 RDBMS&SQL - 55 ©Minder Chen, 1996-2011 Basic Structures and Contents of a Database Database Schema (Meta Data) –Tables »Columns Column Name Data Types and Size Primary key –Relationships »Foreign Keys –Indexes Actual data stored in the Database

57 RDBMS&SQL - 56 ©Minder Chen, 1996-2011 Table Query (View) FormReport Database Application Basic Database Objects Relationships among Access Database Objects A saved SELECT query is officially called View in SQL. QUERY in Access can be SELECT, INSERT, UPDATE, or DELETE. You can create a query against a table or a query. You can create a form or report against a table or a query.

58 RDBMS&SQL - 57 ©Minder Chen, 1996-2011 Stakeholders of a Database Environment Application Programmers AdvancedUsers Database Query/Reporting Tools DBA:DatabaseAdministrator Internal End Users External End Users Database Designer E-commerce Web site

59 RDBMS&SQL - 58 ©Minder Chen, 1996-2011 Query Four types of operations against data in a database –CRUD: Create, Read, Update, Delete –SQL Data Manipulation Language (MDL): »Insert, Select, Update, Delete Select statement allows you to retrieve data from the database (read only). It is also referred to as a query in Access. A definition of a query (not the query result) written in SQL statement can be saved in the database to be run later. A saved query is called “View” in SQL and you can created a query against a saved query (view)

60 RDBMS&SQL - 59 ©Minder Chen, 1996-2011 SELECT The SELECT command is a versatile and powerful command used to retrieve information from the database. SELECT commands may be executed alone, or embedded in CREATE, UPDATE, INSERT and DELETE commands. The SELECT command is composed of 8 clauses: SELECT [DISTINCT | ALL ] projection list FROM table or view list [WHERE search condition ] [GROUP BY column list] [HAVING search condition] [ORDER BY {expr|position} [ ASC|DESC]] [FOR UPDATE OF column list]* [INTO host variable list]*

61 RDBMS&SQL - 60 ©Minder Chen, 1996-2011 SELECT The SELECT clause and the FROM clause are required for all SELECT commands. THE WHERE clauses are permitted in all SELECT commands as a filter defining the criteria of rows to be selected. The WHERE clause of a subquery (i.e., subselect) may also contain nested subquery. Subquery cannot contain the UNION operator or an ORDER BY clause.

62 RDBMS&SQL - 61 ©Minder Chen, 1996-2011 Create a new query: Choose Create > Query Design Highlight a table or a query, click Add; or Double click on a table or a query. You may select more than one table when performing SQL JOIN

63 RDBMS&SQL - 62 ©Minder Chen, 1996-2011 Select Columns Field: Double click a column from the table to select it to the query design form column, or drag and drop it to the form (columns listed in the SQL SELECT clause); Table: A table or query from the database (SQL FROM Clause) Sort: Sorting the query result (SQL ORDER BY clause) Show: Whether to display the column’s value in the query result Criteria : Define criteria (filter) for rows in a table (SQL WHERE clause) You may select a column and use it in a criteria or for sorting without show it’s value in the query result.

64 RDBMS&SQL - 63 ©Minder Chen, 1996-2011 SELECT COURSE.C_ID, COURSE.TITLE, COURSE.FEE FROM COURSE WHERE COURSE.FEE>250 And COURSE.FEE)<=350 ORDER BY COURSE.FEE DESC; SQL Select and Query Design in Access

65 RDBMS&SQL - 64 ©Minder Chen, 1996-2011 Choose Design tab control under Query Tools. Click on View (not the Icon above it) from the Toolbar: Datasheet: See the result of the query, i.e., RUN the query SQL View: Edit SQL statement directly Design view: Create SQL via Query Design tool.

66 RDBMS&SQL - 65 ©Minder Chen, 1996-2011 SELECT Selecting All Columns: EXAMPLE SELECT * FROM STUDENT; RESULT S_NO NAME ADDRESS CITY ST ZIP TEL_NO ------------------ ---------------- ----------------- --------------------------- 5001 MARY 102 1ST ST FAIRFAX VA12345 7037772311 5002 TOM 39 5th AVE ARLINGTON DC 22313 2021112222 5003 LINDA 1 ROCK RD ROCKVILLE MD20852 3019380975 5004 JAMES 7039784444 5005 KATHY 2 KING LA FAIRFAX VA12345 7037775534 5006 MIKE P.O.BOX 1 FAIRFAX VA12345 7037771122 NULL values Null means that there is no data and it is different from empty string.

67 RDBMS&SQL - 66 ©Minder Chen, 1996-2011 SELECT Selecting some columns: EXAMPLE SELECT D_ID, DIV_NAME FROM DIVISION; RESULT D_ID DIV_NAME ------- --------------- D010 ADMINISTRATION D020 COMPUTER SCIENCE D030 ACCOUNTING D040 STATISTICS D050 MATHEMATICS

68 RDBMS&SQL - 67 ©Minder Chen, 1996-2011 SELECT with a calculated column Create a calculated column (Expression): SELECT L_NAME, F_NAME, (SALARY-20000)*0.1 AS BONUS FROM INSTRUCTOR; RESULT L_NAM F_NAME BONUS ----- -------- --------- LEE PATRICK 5200 STONE ALBERT 4000 FLYNN BRUCE 2800 LOU JEAN 200 SELECT L_NAME, F_NAME, ([SALARY]-20000)*0.1 AS [Annual BONUS] FROM INSTRUCTOR;

69 RDBMS&SQL - 68 ©Minder Chen, 1996-2011 SELECT Criteria Select s ome r ows: EXAMPLE SELECT L_NAME, M, F_NAME FROM INSTRUCTOR WHERE DIV = 'D020'; RESULT L_NAM M F_NAME --------------- ------------ LEE D PATRICK STONE Y ALBERT FLYNN C BRUCE NOTE In a WHERE Clause, values to be compared with text data type must be enclosed in single quotation mark ( 'text' ). In Access you can use both single quotes or double quotes.

70 RDBMS&SQL - 69 ©Minder Chen, 1996-2011 SELECT Finding NULL Columns EXAMPLE SELECT S_NO, NAME FROM STUDENT WHERE ADDRESS IS NULL; RESULT S_NO NAME --------- ---------- 5004 JAMES

71 RDBMS&SQL - 70 ©Minder Chen, 1996-2011 SELECT Criteria -- Date format Less Than, Greater Than, Equal: = EXAMPLE SELECT D_O_H, F_NAME, L_NAME FROM INSTRUCTOR WHERE D_O_H < '01-JAN-90' ORDER BY D_O_H; RESULT D_O_H F_NAME L_NAM -------------------------------------------- 08-MAR-83PATRICK LEE 02-SEP-88 JEAN LOU #01/01/1990# In Access SQL

72 RDBMS&SQL - 71 ©Minder Chen, 1996-2011 SELECT Criteria Less Than, Greater Than, Equal: = EXAMPLE SELECT L_NAME, I_NO, ED FROM INSTRUCTOR WHERE ED <= 10; RESULT L_NAM I_NO ED ------------------------- FLYNN 21 10 LOU 52 08

73 RDBMS&SQL - 72 ©Minder Chen, 1996-2011 SELECT Criteria Multiple Conditions: AND EXAMPLE SELECT I_NO, D_O_H, SALARY FROM INSTRUCTOR WHERE D_O_H < '31-DEC-90' AND SALARY < 26000; RESULT I_NO D_O_H SALARY --------- --------------- --------- 52 02-SEP-88 22000 AND

74 RDBMS&SQL - 73 ©Minder Chen, 1996-2011 SELECT Criteria Multiple Conditions: OR EXAMPLE SELECT I_NO, D_O_H, SALARY FROM INSTRUCTOR WHERE D_O_H < '31-DEC-90' OR SALARY < 26000; RESULT I_NO D_O_H SALARY --------- ------------ ------------- 1 8-MAR-83 72000 52 02-SEP-88 22000 OR

75 RDBMS&SQL - 74 ©Minder Chen, 1996-2011 SELECT Criteria Multiple Conditions: AND, OR EXAMPLE SELECT I_NO, D_O_H, SALARY FROM INSTRUCTOR WHERE D_O_H < '01-JAN-90' AND (SALARY < 40000 OR ED < 11); RESULT I_NO D_O_H SALARY --------- ------------- ------------ 52 02-SEP-88 22000

76 RDBMS&SQL - 75 ©Minder Chen, 1996-2011 SELECT Criteria Selecting All Rows Except... : NOT, <>, ^= EXAMPLE SELECT D_ID, DIR FROM DIVISION WHERE NOT (D_ID <= 'D010'); RESULT D_ID DIR -------- ----- D020 1 D030 1 D040 1 D050 1 NOTE –The NOT keyword must precede the condition.

77 RDBMS&SQL - 76 ©Minder Chen, 1996-2011 Selecting Rows...LIKE... SELECT NAME, CITY FROM STUDENT WHERE CITY LIKE 'FAIR%'; - - match 'Fairlake' SELECT NAME, CITY FROM STUDENT WHERE CITY LIKE 'FAIR_ _ _'; - - does not match 'Fairlake' RESULT: Both query get same results. NAME CITY ---------- MARY FAIRFAX KATHY FAIRFAX MIKE FAIRFAX ***NOTE*** –Use a percent sign (%) to indicate any string of zero or more characters. Use * in Access instead of % –Use an underscore (_) for any single character. ( use ? In Access ) –Use the LIKE keyword only with data type CHAR, VARCHAR not with NUMERIC or DATE. SELECT NAME, CITY FROM STUDENT WHERE CITY LIKE '%FAIR%'; - - match 'Fairlake' and 'Myfaircity' SELECT NAME, CITY FROM STUDENT WHERE CITY LIKE '%FAIR%'; - - match 'Fairlake' and 'Myfaircity'

78 RDBMS&SQL - 77 ©Minder Chen, 1996-2011 SELECT Values Within a Range EXAMPLE SELECT D_ID, DIR FROM DIVISION WHERE D_ID BETWEEN 'D010' AND 'D030' ORDER BY D_ID; - - WHERE D_ID >= 'D10' AND D_ID <= 'D030' RESULT D_ID DIR ------- --------- D010 52 D020 1 D030 1

79 RDBMS&SQL - 78 ©Minder Chen, 1996-2011 Selecting Values Within a Range SELECT I_NO, SALARY FROM INSTRUCTOR WHERE SALARY NOT BETWEEN 30000 AND 50000; - - WHERE SALARY 50000 RESULT I_NO SALARY --------- ------------ 1 72000 19 60000 52 22000

80 RDBMS&SQL - 79 ©Minder Chen, 1996-2011 SELECT ORDER BY: Showing Values in Sequence ORDER BY: (ASC or DESC) Ascending Order is the default. SELECT D_ID, DIR FROM DIVISION ORDER BY D_ID; RESULT D_ID DIR ------- --------- D010 52 D020 1 D030 1 D040 1 D050 1 NOTE: All columns named in the ORDER BY clause must be named in the SELECT clause. (In Access the above statement is NOT TRUE. Sorting columns don’t have to be selected for display.)

81 RDBMS&SQL - 80 ©Minder Chen, 1996-2011 SELECT: ORDER BY clause EXAMPLE: In Descending Order SELECT D_ID, DIR FROM DIVISION ORDER BY D_ID DESC; - - ASC (Ascending) is the default sorting order - - The default order for character fields is a case sensitive ASCII sequence RESULT D_ID DIR ------- --------- D050 1 D040 1 D030 1 D020 1 D010 52

82 RDBMS&SQL - 81 ©Minder Chen, 1996-2011 SELECT: ORDER BY column number EXAMPLE: Order by the first column 12 SELECT D_ID, DIR FROM DIVISION ORDER BY 1; RESULT D_ID DIR ------- --------- D010 52 D020 1 D030 1 D040 1 D050 1

83 RDBMS&SQL - 82 ©Minder Chen, 1996-2011 Top N Rows TOP n [PERCENT]: Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause. In Access you need to add TOP N qualifier in SQL View SELECT TOP 2 L_NAME,F_NAME, SALARY FROM INSTRUCTOR ORDER BY INSTRUCTOR.SALARY DESC;

84 RDBMS&SQL - 83 ©Minder Chen, 1996-2011 SELECT: ORDER BY sort-list (multiple columns) INSERT INTO INSTRUCTOR (I_NO, L_NAME, M, F_NAME, SALARY) VALUES (60, 'SMITH', 'F', 'BOB', 60000); SELECT L_NAME, F_NAME, SALARY * 0.1 AS BONUS FROM INSTRUCTOR ORDER BY Bonus DESC, L_NAME; - - primary order column is BONUS - - Secondary column is L_NAME L_NAM F_NAME BONUS ----- -------- --------- LEE PATRICK 7200 SMITH BOB 6000 STONE ALBERT 6000 FLYNN BRUCE 4800 LOU JEAN 2200 Access SQL Access SQL: (cannot use alias column name in Order By clause) SELECT L_NAME, F_NAME, SALARY * 0.1 AS BONUS FROM INSTRUCTOR ORDER BY 3 DESC, L_NAME;

85 RDBMS&SQL - 84 ©Minder Chen, 1996-2011 ORDER BY the Position of Columns SELECT L_NAME, F_NAME, SALARY * 0.1 FROM INSTRUCTOR ORDER BY 3 DESC, L_NAME; L_NAM F_NAME SALARY*0.1 ----- -------- ---------- LEE PATRICK 7200 SMITH BOB 6000 STONE ALBERT 6000 FLYNN BRUCE 4800 LOU JEAN 2200 Sort first by third column in descending order Sort secondly by L_NAME (asc)

86 RDBMS&SQL - 85 ©Minder Chen, 1996-2011 SELECT Concatenation Operations || EXAMPLE SELECT L_NAME | | ', ' | | F_NAME | | ' ' | | M AS NAME FROM INSTRUCTOR; RESULT NAME --------------------------- LEE, PATRICK D STONE, ALBERT Y FLYNN, BRUCE C LOU, JEAN E Access SQL : (use & instead of || for string concatenation) SELECT L_NAME & ', ' & F_NAME & ' ' & M AS NAME FROM INSTRUCTOR; A space character

87 RDBMS&SQL - 86 ©Minder Chen, 1996-2011 SELECT: IN Selecting Value in or not in a List: EXAMPLE SELECT D_ID, DIR FROM DIVISION WHERE D_ID IN ('D010', 'D020', 'D040') ORDER BY D_ID; RESULT D_ID DIR ------- --------- D010 52 D020 1 D040 1 SELECT D_ID, DIR FROM DIVISION WHERE D_ID NOT IN ('D010', 'D020', 'D040') ORDER BY D_ID; SELECT D_ID, DIR FROM DIVISION WHERE D_ID NOT IN ('D010', 'D020', 'D040') ORDER BY D_ID;

88 RDBMS&SQL - 87 ©Minder Chen, 1996-2011 SELECT Expressions in Conditions: EXAMPLE SELECT I_NO, L_NAME, SALARY FROM INSTRUCTOR WHERE SALARY > 800 * 52; RESULT I_NO L_NAM SALARY --------- ----- --------- 1 LEE 72000 19 STONE 60000 21 FLYNN 48000

89 RDBMS&SQL - 88 ©Minder Chen, 1996-2011 INSERT INSERT INTO [table-name | view-name] [(column-name1, column-name2, …)] VALUES (value1, value2, …); Adding one or more row(s) into an existing table. –Table with Foreign Keys »Target (referenced column) of foreign key must exist »NULL value of the foreign key (referencing column) allowed –CHECK Constraint INSERT INTO DIVISION VALUES('D010',52,'ADMINISTRATION');

90 RDBMS&SQL - 89 ©Minder Chen, 1996-2011 INSERT Examples INSERT INTO DIVISION VALUES('D060',NULL,'MARKETING'); -- This does not work in Access INSERT INTO DIVISION (DIV_NAME, D_ID) VALUES('R&D', 'D070'); D_ID DIR DIV_NAME ---- --------- ---------------- D010 52 ADMINISTRATION D020 1 COMPUTER SCIENCE D030 1 ACCOUNTING D040 1 STATISTICS D050 1 MATHEMATICS D060 MARKETING D070 R&D

91 RDBMS&SQL - 90 ©Minder Chen, 1996-2011 Access Append Query (Insert) INSERT INTO DIVISION ( D_ID, DIV_NAME ) SELECT 'D060' AS Expr1, 'Marketing' AS Expr2; INSERT INTO DIVISION ( D_ID, DIV_NAME ) VALUES ('D060', 'Marketing' ); Don’t select any tables from the Show Table dialog box     

92 RDBMS&SQL - 91 ©Minder Chen, 1996-2011 INSERT Multiple Rows INSERT INTO [table-name | view-name] [column-name1, column-name2, …)] SELECT statement; CREATE TABLE TEACHER1 (I_NONUMBER(4)NOT NULL, F_NAMEVARCHAR(8)NOT NULL, L_NAMEVARCHAR(5)NOT NULL, DIVCHAR(4)); INSERT INTO TEACHER1 (I_NO, F_NAME, L_NAME, DIV) SELECT I_NO, F_NAME, L_NAME, DIV FROM INSTRUCTOR WHERE TITLE = 'TEACHER';

93 RDBMS&SQL - 92 ©Minder Chen, 1996-2011 UPDATE: Modify One or More Columns UPDATE [table-name | view-name] SET column-name1 = expression1, column-name2 = expression2,... [WHERE clause]; - - Change the last name of the instructor (I_NO = 21) to 'WANG' UPDATE UPDATE INSTRUCTOR SET SET L_NAME='WANG' WHERE WHERE I_NO = 21; -- Give all the instructors in --D010 department a 10% raise. UPDATE INSTRUCTOR SET SALARY = SALARY * 1.1 WHERE DIV = 'D010'; I_NO F_NAME M L_NAM SALARY --------- ------------- --- ----------- ------------- 1 PATRICK D LEE 72000 19 ALBERT Y STONE 60000 21 BRUCE C WANG 48000 52 JEAN E LOU 24200 Click Run

94 RDBMS&SQL - 93 ©Minder Chen, 1996-2011 UPDATE You cannot update a view if the view's defining query contains one of the following constructs: –JOIN –set operator –GROUP BY clause –group function –DISTINCT operator –Non-columns are used in SELECT clause.

95 RDBMS&SQL - 94 ©Minder Chen, 1996-2011 DELETE: Deleting One or More Rows DELETE FROM table-name [WHERE clause]; EXAMPLE - - Delete instructor whose I_NO is 52 DELETE FROM INSTRUCTOR WHERE I_NO = 52; - - delete students with 301 area code DELETE FROM STUDENT WHERE TEL_NO LIKE = '301*'; - - delete the whole table DELETE FROM DIVISION; NOTES: DELETE command is a very powerful command, please use it with care.

96 RDBMS&SQL - 95 ©Minder Chen, 1996-2011 FUNCTIONS AGGREGATE FUNCTIONS –COUNT (*) or COUNT(DISTINT column) –MAX –MIN –SUM –AVG Other Functions –SUBSTR –TRUNC –Format

97 RDBMS&SQL - 96 ©Minder Chen, 1996-2011 COUNT PURPOSE: Counts the number of rows in each group that satisfy the condition(s) specified. EXAMPLE SELECT COUNT(*) FROM STUDENT; RESULT COUNT(*) --------------- 6

98 RDBMS&SQL - 97 ©Minder Chen, 1996-2011 Count() How many students that we have from VA state? SELECT Count(*) AS [VA-Student-count] FROM STUDENT WHERE STUDENT.STATE='VA';

99 RDBMS&SQL - 98 ©Minder Chen, 1996-2011 Use Query Design View SELECT Count(STUDENT.S_NO) AS CountOfS_NO FROM STUDENT WHERE (((STUDENT.STATE)="VA")); Tool Bar

100 RDBMS&SQL - 99 ©Minder Chen, 1996-2011 COUNT EXAMPLE SELECT COUNT(ADDRESS) FROM STUDENT; RESULT COUNT(ADDRESS) --------------------------- 5

101 RDBMS&SQL - 100 ©Minder Chen, 1996-2011 MAX PURPOSE Selects the maximum value in each group of a column. Null values will be ignored. EXAMPLE SELECT MAX(SALARY) FROM INSTRUCTOR; RESULT MAX(SALARY) --------------------- 72000

102 RDBMS&SQL - 101 ©Minder Chen, 1996-2011 MIN PURPOSE Selects the mininum value in each group of a column. Null values will be ignored. EXAMPLE SELECT MIN(SALARY) FROM INSTRUCTOR; RESULT MIN(SALARY) -------------------- 22000

103 RDBMS&SQL - 102 ©Minder Chen, 1996-2011 SUM PURPOSE Adds up all the values in each group of a column. Null values will be ignored. EXAMPLE SELECT SUM(SALARY) FROM INSTRUCTOR; RESULT SUM(SALARY) --------------------- 202000

104 RDBMS&SQL - 103 ©Minder Chen, 1996-2011 AVG PURPOSE Averages the values in each group of a column. This function is for numeric columns only. Null values will be ignored. EXAMPLE SELECT AVG(SALARY) FROM INSTRUCTOR; RESULT AVG(SALARY) -------------------- 50500

105 RDBMS&SQL - 104 ©Minder Chen, 1996-2011 Use Several Functions Together More than one function can be used in a command. SELECT COUNT(I_NO), AVG(SALARY), MIN(SALARY), MAX(SALARY) FROM INSTRUCTOR; COUNT(I_NO) AVG(SALARY) MIN(SALARY) MAX(SALARY) ----------- ----------- ----------- --- -------- 4 50500 22000 72000

106 RDBMS&SQL - 105 ©Minder Chen, 1996-2011 SELECT with Distinct Values Selecting unique values in a column: EXAMPLE SELECT DISTINCT ( TITLE ) FROM INSTRUCTOR; RESULT TITLE -------------- CLERK DEAN TEACHER Selecting values in a column: EXAMPLE SELECT TITLE FROM INSTRUCTOR; RESULT TITLE -------------- DEAN TEACHER CLERK Create a query to tell me “How many distinct titles we have?” You can only create this query in Access SQL View

107 RDBMS&SQL - 106 ©Minder Chen, 1996-2011 Count and Distinct Statement Limitation Oracle SQL: SELECT COUNT(DISTINCT CITY) FROM STUDENT; -- Answer: 3 (exclude records that have NULL value in their city column) Access SQL (Include NULL value; cannot use distinct and Count together) You have to use the SQL view to enter the distinct keyword. It will not work in the Design view. SELECT DISTINCT (CITY) FROM STUDENT;

108 RDBMS&SQL - 107 ©Minder Chen, 1996-2011 How to count distinct values 1 2 3 4 5 6 Create the first query using distinct and save it as DistinctTitles Create the second query against the DistinctTitles query. Use count function in this second query.

109 RDBMS&SQL - 108 ©Minder Chen, 1996-2011 Access Report Wizard 1 2 3

110 RDBMS&SQL - 109 ©Minder Chen, 1996-2011 Group By  Control Break Group By DIV (Division ID) Aggregate Functions 4 The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

111 RDBMS&SQL - 110 ©Minder Chen, 1996-2011 Group By SELECT clause contains both an aggregate function and a column name are not allowed unless the result set is GROUP BY the same column. SELECT TITLE, SUM (SALARY) FROMINSTRUCTOR GROUP BY TITLE; TITLE SUM(SALARY) -------- ----------- CLERK 22000 DEAN 72000 TEACHER 108000 SELECT GB-column-name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY GB-column-name

112 RDBMS&SQL - 111 ©Minder Chen, 1996-2011 SELECT: Grouping Rows Summarize Group Values: Build-in functions (e.g., MAX, MIN) can be applied to selected groups of rows in a table. GROUP BY produces one row in the returned set for each different value it finds in the GROUP BY column(s). EXAMPLE SELECT DIV, MAX(SALARY), MIN(SALARY) FROM INSTRUCTOR GROUP BY DIV ORDER BY DIV; RESULT DIV MAX(SALARY) MIN(SALARY) ------- -------------------- -------------------- D010 22000 22000 D020 60000 48000

113 RDBMS&SQL - 112 ©Minder Chen, 1996-2011 Group By … Having... Use HAVING instead of WHERE clause after GROUP to qualify groups. Nested queries are permitted in the HAVING clause. SELECT TITLE, AVG(SALARY) FROM INSTRUCTOR GROUP BY TITLE HAVING COUNT(*) > 1; TITLE AVG(SALARY) -------- ----------- TEACHER 54000 Show me each title and average salary of the title which has more than one instructors with such title. This is for privacy purpose.

114 RDBMS&SQL - 113 ©Minder Chen, 1996-2011 SELECT Groups with Conditions Groups with Conditions: EXAMPLE SELECT DIV, ROUND(AVG(SALARY)/52, 2) AS AVG_SAL FROM INSTRUCTOR GROUP BY DIV HAVING COUNT(*) > 1 ORDER BY DIV; RESULT DIV AVG_SAL ---- --------- D020 1153.85 ROUND(n[,m]): Returns n rounded to m decimal places; if m is omitted, to 0 places. Cannot use aggregate functions in WHERE clause!

115 RDBMS&SQL - 114 ©Minder Chen, 1996-2011 SUBSTR(char, m [,n]) PURPOSE Returns a portion of char, beginning at character m for n characters long. EXAMPLE SELECT SUBSTR(DIV_NAME,1,4) "SUBS" FROM DIVISION; RESULT SUBS -------- ADMI COMP ACCO STAT MATH Access SQL: (use LEFT string function) SELECT Left(DIV_NAME,4) as SUBS FROM DIVISION;

116 RDBMS&SQL - 115 ©Minder Chen, 1996-2011 TRUNC(n, d) Truncates a number n and display d decimal positions. EXAMPLE SELECT I_NO, TRUNC(MONTHS_BETWEEN(SYSDATE, D_O_B)/12, 0) AS AGE FROM INSTRUCTOR; RESULT I_NO AGE --------- 1 46 19 43 21 39 52 33 Assuming that the SYSDATE returns 10/4/1998. Should you store “age” in the database instead of birthday? Access SQL: (Date function) SELECT I_NO, ROUND(DateDiff("m", D_O_B, Now)/12, 0) AS AGE FROM INSTRUCTOR;

117 RDBMS&SQL - 116 ©Minder Chen, 1996-2011 Advanced SQL Programming JOIN Correlated subquery Non-correlated subquery UNION JOIN: A SQL join is used to query data from two or more tables, based on a relationship between certain columns in these tables. The common columns that are used to connect these tables are usually a foreign key-primary key pair.

118 RDBMS&SQL - 117 ©Minder Chen, 1996-2011 Join Show all instructors from the Instructor table with the following information: –I_NO, L_Name, F_Name, plus DIV and DIV_Name where the instructor belongs.

119 RDBMS&SQL - 118 ©Minder Chen, 1996-2011 JOIN Join condition: Join operation must based on one or more columns from each of the two tables whose data values share a common domain. To get data from two or more tables resulting in a wide table, you need to name all tables in the FROM clause. EXAMPLE SELECT D_ID, L_NAME, F_NAME, DIV_NAME FROM DIVISION, INSTRUCTOR WHERE Division.DIR = Instructor.I_NO ORDER BY D_ID; Show me the Division ID, Last name, First Name of its Director, and the Division Name of all the Division and sorted it by Division ID

120 RDBMS&SQL - 119 ©Minder Chen, 1996-2011 JOIN RESULT D_ID L_NAM F_NAME DIV_NAME ------- ------------- --------------- ------------------------------- D010 LOU JEAN ADMINISTRATION D020 LEE PATRICK COMPUTER SCIENCE D030 LEE PATRICK ACCOUNTING D040 LEE PATRICK STATISTICS D050 LEE PATRICK MATHEMATICS NOTE –The FROM DIVISION, INSTRUCTOR clause shows this is a join. –The WHERE DIR = I_NO clause makes the connection between the two tables.

121 RDBMS&SQL - 120 ©Minder Chen, 1996-2011 JOIN: Access Query and SQL SELECT INSTRUCTOR.I_NO, INSTRUCTOR.F_NAME, INSTRUCTOR.L_NAME, DIVISION.DIV_NAME FROM DIVISION INNER JOIN INSTRUCTOR ON DIVISION.D_ID = INSTRUCTOR.DIV; INSTRUCTOR DIVISION

122 RDBMS&SQL - 121 ©Minder Chen, 1996-2011 Qualifying Column Names If the same column name is used in more than one table, you must qualify its name to show which table or view you mean. You can also qualify column names by correlation variables SELECT TITLE, COURSE.C_ID, LOCATION, START_DATE FROM COURSE, OFFERING WHERE COURSE.C_ID = OFFERING.C_ID ORDER BY TITLE; or SELECT TITLE, X.C_ID, LOCATION, START_DATE FROM COURSE X, OFFERING Y WHERE X.C_ID = Y.C_ID ORDER BY TITLE; X, Y are correlation variables or aliases. OFFERING COURSE

123 RDBMS&SQL - 122 ©Minder Chen, 1996-2011 Qualifying Column Names RESULT TITLE C_ID LOCATION START_DAT ------------------- -------------------------- ------------------ INTRO C++ C010 LOUDOUN 01-APR-97 INTRO C++ C010 LOUDOUN 01-OCT-97 INTRO C++ C010 ROCKVILLE 01-OCT-97 INTRO PB C020 LOUDOUN 01-APR-97 INTRO PB C020 LOUDOUN 01-OCT-97 INTRO PB C020 ROCKVILLE 01-OCT-97 RDBMS SQL C030 LOUDOUN 01-OCT-97 WINDOWS NT C040 LOUDOUN 01-OCT-97

124 RDBMS&SQL - 123 ©Minder Chen, 1996-2011 JOIN and Aggregation Function Show students ID, name, and GPA (assuming all courses are 3 credits) SELECT STUDENT.S_NO, STUDENT.NAME, Round(Avg(REGISTRATION.GRADE)*100)/100 AS AvgOfGRADE FROM STUDENT.S_NO = REGISTRATION.S_NO GROUP BY STUDENT.S_NO, STUDENT.NAME; SQL: Format(Avg(GRADE), "###.00") AS GPA Design View: GPA: Format(Avg(GRADE), "###.00") Don’t choose any table here! Change this to expression

125 RDBMS&SQL - 124 ©Minder Chen, 1996-2011 Examples How many students in each section of the fall 1997 class assuming the START_DATE of the fall 1997 semester is #10/1/1997#?

126 RDBMS&SQL - 125 ©Minder Chen, 1996-2011 JOIN and Aggregation Function Show the total fees generated by each course (with multiple offering) SELECT COURSE.C_ID, COURSE.TITLE, Sum(COURSE.FEE) AS SumOfFEE FROM (COURSE INNER JOIN OFFERING ON COURSE.C_ID = OFFERING.C_ID) INNER JOIN REGISTRATION ON (OFFERING.O_NO = REGISTRATION.O_NO) AND (OFFERING.C_ID = REGISTRATION.C_ID) GROUP BY COURSE.C_ID, COURSE.TITLE ORDER BY Sum(COURSE.FEE) DESC; – How about fees generated in fall 1997 semester? _ How about top 2 courses that generate most fees

127 RDBMS&SQL - 126 ©Minder Chen, 1996-2011 Alternative Join Syntax Oracle: (This works in Access as well) SELECT TITLE, COURSE.C_ID, LOCATION, START_DATE FROM COURSE, OFFERING WHERE COURSE.C_ID = OFFERING.C_ID ORDER BY TITLE; Access SQL and SQL-92 Standard: (May not work in Oracle SQL*Plus) SELECT Title, COURSE.C_ID, LOCATION, START_DATE FROM COURSE INNER JOIN OFFERING ON COURSE.C_ID = OFFERING.C_ID ORDER BY TITLE;

128 RDBMS&SQL - 127 ©Minder Chen, 1996-2011 JOIN Inner Join: SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO = OFFERING.I_NO; I_NO L_NAM F_NAME C_ID O_NO --------- ----- -------- ---- --------- 21 FLYNN BRUCE C010 1 21 FLYNN BRUCE C010 10 19 STONE ALBERT C010 20 19 STONE ALBERT C020 1 19 STONE ALBERT C020 10 21 FLYNN BRUCE C020 20 19 STONE ALBERT C030 10 19 STONE ALBERT C040 10 With inner join operation, only rows that satisfy the comparison used to create the join are included in the result. Instructors who do not have any offering entry in the OFFERING table will not be retrieved.

129 RDBMS&SQL - 128 ©Minder Chen, 1996-2011 Inner & Outer Joins Inner Join Left Outer Join Right Outer Join

130 RDBMS&SQL - 129 ©Minder Chen, 1996-2011 Left Outer Join SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO = OFFERING.I_NO (+); I_NO L_NAM F_NAME C_ID O_NO --------- ----- -------- ---- --------- 1 LEE PATRICK 19 STONE ALBERT C010 20 19 STONE ALBERT C020 1 19 STONE ALBERT C030 10 19 STONE ALBERT C020 10 19 STONE ALBERT C040 10 21 FLYNN BRUCE C010 1 21 FLYNN BRUCE C010 10 21 FLYNN BRUCE C020 20 52 LOU JEAN When instructors from INSTRUCTOR table do not have any offering, they will be listed with NULL values in columns from OFFERING table. (+) qualifier in the WHERE clause indicate which table's columns should contain entries with NULL values when there is no matching value in the other column. (Oracle only) NULL Values

131 RDBMS&SQL - 130 ©Minder Chen, 1996-2011 Outer Join Right Outer Join: SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO (+) = OFFERING.I_NO; Alternative Notation (SQL-92 standard) SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING, INSTRUCTOR RIGHT OUTER JOIN OFFERING ON INSTRUCTOR.I_NO = OFFERING.I_NO; Left Outer Join SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING WHERE INSTRUCTOR.I_NO = OFFERING.I_NO (+); Alternative Notation (SQL-92 standard) SELECT INSTRUCTOR.I_NO, L_NAME, F_NAME, C_ID, O_NO FROM INSTRUCTOR, OFFERING, INSTRUCTOR LETF OUTER JOIN OFFERING ON INSTRUCTOR.I_NO = OFFERING.I_NO;

132 RDBMS&SQL - 131 ©Minder Chen, 1996-2011 Multiway Join This query joins six tables. EXAMPLE SELECT A.C_ID, B.TITLE, C.LOCATION, C.START_DATE, D.DIV_NAME, E.L_NAME AS INSTR, F.NAME AS STUDENT FROM REGISTRATION A, COURSE B, OFFERING C, DIVISION D, INSTRUCTOR E, STUDENT F WHERE A.C_ID = 'C010' AND A.C_ID = B.C_ID AND(A.C_ID = C.C_ID AND A.O_NO = C.O_NO) AND C.I_NO = E.I_NO ANDB.DIV = D.D_ID AND A.S_NO = F.S_NO;

133 RDBMS&SQL - 132 ©Minder Chen, 1996-2011 Multiway Join RESULT C_IDTITLE LOCATIONSTART_DATDIV_NAME INSTRSTUDENT ------- ------------------------------- ------------------------------------------------------------------------ C010INTRO C++ LOUDOUN 01-APR-97 COMPUTER SCIENCE FLYNN MARY C010 INTRO C++ LOUDOUN 01-APR-97 COMPUTER SCIENCE FLYNN TOM C010 INTRO C++ LOUDOUN 01-OCT-97 COMPUTER SCIENCE FLYNN LINDA C010 INTRO C++ LOUDOUN 01-OCT-97 COMPUTER SCIENCE FLYNN JAMES C010 INTRO C++ LOUDOUN 01-OCT-97 COMPUTER SCIENCE FLYNN KATHY

134 RDBMS&SQL - 133 ©Minder Chen, 1996-2011 Server Generated Sequence Numbers In some database servers such as Sybase, the system maintains a sequence number for an identity column. It is special data type called AutoNumber is Access. Create table employee ( id numeric(4, 0) identify, namechar(20)not null, titlechar(50)not null); Insert into employee values ('Minder', 'Dean'); Insert into employee values ('Justin', 'Instructor'); Result: idnametitle 1MinderDean 2JustinInstructor

135 RDBMS&SQL - 134 ©Minder Chen, 1996-2011 Table Query (View) FormReport Database Application Basic Database Objects Relationships among Access Database Objects A saved SELECT query is officially called View in SQL. QUERY in Access can be SELECT, INSERT, UPDATE, or DELETE. You can create a query against a table or a query. You can create a form or report against a table or a query.

136 RDBMS&SQL - 135 ©Minder Chen, 1996-2011 Create Forms in Access

137 RDBMS&SQL - 136 ©Minder Chen, 1996-2011 Create a Simple Form

138 RDBMS&SQL - 137 ©Minder Chen, 1996-2011 Form Layout and Style

139 RDBMS&SQL - 138 ©Minder Chen, 1996-2011

140 RDBMS&SQL - 139 ©Minder Chen, 1996-2011 Detail Form in Datasheet Layout

141 RDBMS&SQL - 140 ©Minder Chen, 1996-2011

142 RDBMS&SQL - 141 ©Minder Chen, 1996-2011

143 RDBMS&SQL - 142 ©Minder Chen, 1996-2011

144 RDBMS&SQL - 143 ©Minder Chen, 1996-2011 LOCK Locking mechanism is used to prevent loss of data integrity in reading and writing data to the database. The lock controls whether some other users can access (read or write) the database. Transaction requests and releases for locks are normally implicit. Shared lock (S): Allow the lock owner to read the lock data, but not to change it. You can acquire a shared lock on data after other users also acquired a shared lock on the it. Exclusive lock (X): Allow the lock owner to read and update the lock data. No other user can access the locked data or acquired locks on it while a exclusive lock is in effect. Lock Compatibility

145 RDBMS&SQL - 144 ©Minder Chen, 1996-2011 LOCK Permits users to explicitly acquire table locks. –Lock Objects »Row »Page »Table »Table Space –Lock Modes »Shared(S) Lock »Exclusive(X) Lock

146 RDBMS&SQL - 145 ©Minder Chen, 1996-2011 COMMIT & ROLLBACK COMMIT: Instructs the system to make all DML commands executed by a transaction permanent and releases the transaction's locks. You can also use this command to manually commit an in-doubt distributed transaction. ROLLBACK: Instructs the system to reverse all DML commands executed by a transaction. When the ROLLBACK command is issued, all changes caused by INSERT, UPDATE and DELETE commands of the transaction are backed out. All locks acquired during a transaction are released by the ROLLBACK command.

147 RDBMS&SQL - 146 ©Minder Chen, 1996-2011 Indexing & Performance: Retrieval vs. Update All Indexed No index Fastest Slowest Retrieval speed Update speed Trade off between retrieval and update Consider the creation of indexes when faster retrieval performance is required.

148 RDBMS&SQL - 147 ©Minder Chen, 1996-2011 APPENDIX A. Sample Database Tables 1. Instructor Table 2. Student Table 3. Division Table

149 RDBMS&SQL - 148 ©Minder Chen, 1996-2011 4. Course Table 5. Offering Table 6. Registration Table

150 RDBMS&SQL - 149 ©Minder Chen, 1996-2011 Physical Data Model

151 RDBMS&SQL - 150 ©Minder Chen, 1996-2011 Normalization First Normal Form A table is in the first normal form if it contains no repeating value. Un-Normalized Relation: Normalized Relation:

152 RDBMS&SQL - 151 ©Minder Chen, 1996-2011 Normalization Second Normal Form A table is in the second normal form if you remove any partial functional dependencies. Un-normalized Relation: Registration Normalized Relation: Registration Course Partial Functional Dependency

153 RDBMS&SQL - 152 ©Minder Chen, 1996-2011 Normalization Third Normal Form A table is in the third normal form if it contains no transitive functional dependencies. Un-normalized Relation: Course Normalized Relation: Course Instructor COURSECourse Title Instructor_ID InstructorTel Transitive Functional Dependencies


Download ppt "Introduction to Relational Database and SQL Minder Chen CSU Channel Islands"

Similar presentations


Ads by Google