Introduction to Relational Database and SQL Minder Chen CSU Channel Islands
RDBMS&SQL - 2 ©Minder Chen, 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.
RDBMS&SQL - 3 ©Minder Chen, 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 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.
RDBMS&SQL - 4 ©Minder Chen, 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
RDBMS&SQL - 5 ©Minder Chen, 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
RDBMS&SQL - 6 ©Minder Chen, SQL Terminology p_nonamequantityprice 101 Color TV B&W TV PC 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
RDBMS&SQL - 7 ©Minder Chen, 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 PC2000 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
RDBMS&SQL - 8 ©Minder Chen, SQL: Data Manipulation Language (DML) SELECT UPDATE INSERT DELETE SELECT UPDATE INSERT DELETE p_nonamequantityprice 101 Color TV B&W TV PC SELECT p_no, name, price FROM PRODUCT WHERE PRICE < = 1000 ORDER BY PRICE DESC; p_nonameprice Color TV B&W TV250
RDBMS&SQL - 9 ©Minder Chen, 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.
RDBMS&SQL - 10 ©Minder Chen, 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
RDBMS&SQL - 11 ©Minder Chen, Database Server in the Client-Server Architecture User File Server Client Application Database Server 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
RDBMS&SQL - 12 ©Minder Chen, 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
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
RDBMS&SQL - 14 ©Minder Chen, 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
RDBMS&SQL - 15 ©Minder Chen, 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.
RDBMS&SQL - 16 ©Minder Chen, 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.
RDBMS&SQL - 17 ©Minder Chen, 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.
RDBMS&SQL - 18 ©Minder Chen, 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).
RDBMS&SQL - 19 ©Minder Chen, 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.
RDBMS&SQL - 20 ©Minder Chen, The Relational Model DIVISION INSTRUCTOR PK FK
RDBMS&SQL - 21 ©Minder Chen, 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?
RDBMS&SQL - 22 ©Minder Chen, 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.
RDBMS&SQL - 23 ©Minder Chen, 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
RDBMS&SQL - 24 ©Minder Chen, Foreign Keys & Primary Keys in a Sample Database (ACCESS)
RDBMS&SQL - 25 ©Minder Chen, 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)
RDBMS&SQL - 26 ©Minder Chen, 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.
RDBMS&SQL - 27 ©Minder Chen, 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
RDBMS&SQL - 28 ©Minder Chen, 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?
RDBMS&SQL - 29 ©Minder Chen, Basic Elements Character Set –The upper- and lower-case letters A.. Z, a.. z –The numerals –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.
RDBMS&SQL - 30 ©Minder Chen, 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., should be declared as DEC(6,2) –FLOAT: Single precision floating-point number. –SMALLINT: Half word (2 bytes) binary integer. Value can range from to –INT: Full word(4 bytes) binary integer. Value can range from to –CHAR: Fixed length character string. –VARCHAR: Variable length character string. –DATE: Data stored in Gregorian date format.
RDBMS&SQL - 31 ©Minder Chen, 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.
RDBMS&SQL - 32 ©Minder Chen, 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.
RDBMS&SQL - 33 ©Minder Chen, 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
RDBMS&SQL - 34 ©Minder Chen, 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.
RDBMS&SQL - 35 ©Minder Chen, 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.
RDBMS&SQL - 36 ©Minder Chen, 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
RDBMS&SQL - 37 ©Minder Chen, Sample Database REGISTRATION OFFERING COURSE INSTRUCTOR DIVISION STUDENT
RDBMS&SQL - 38 ©Minder Chen, Relationships in Access Database
RDBMS&SQL - 39 ©Minder Chen, Edit Relationships in Access Referential Integrity
RDBMS&SQL - 40 ©Minder Chen, 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.
RDBMS&SQL - 41 ©Minder Chen, 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.
RDBMS&SQL - 42 ©Minder Chen, 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.
RDBMS&SQL - 43 ©Minder Chen, 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.
RDBMS&SQL - 44 ©Minder Chen, 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.
RDBMS&SQL - 45 ©Minder Chen, 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));
RDBMS&SQL - 46 ©Minder Chen, 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));
RDBMS&SQL - 47 ©Minder Chen, 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));
RDBMS&SQL - 48 ©Minder Chen, 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));
RDBMS&SQL - 49 ©Minder Chen, 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);
RDBMS&SQL - 50 ©Minder Chen, 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 ALBERT STONE TEACHER BRUCE FLYNN TEACHER 48000
RDBMS&SQL - 51 ©Minder Chen, Using a View Query against a saved query SELECT * FROM TEACHER WHERE SALARY >= 50000; I_NO F_NAME L_NAM TITLE SALARY ALBERT STONE TEACHER 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
RDBMS&SQL - 52 ©Minder Chen, 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.
RDBMS&SQL - 53 ©Minder Chen, PROCESSVIEWBASE TABLE SELECT UPDATE COLUMN DELETE ROW INSERT ROW Processing A View ? NULL or default value
RDBMS&SQL - 54 ©Minder Chen, Access DMBS: DMBS vs Database
RDBMS&SQL - 55 ©Minder Chen, 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
RDBMS&SQL - 56 ©Minder Chen, 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.
RDBMS&SQL - 57 ©Minder Chen, 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
RDBMS&SQL - 58 ©Minder Chen, 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)
RDBMS&SQL - 59 ©Minder Chen, 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]*
RDBMS&SQL - 60 ©Minder Chen, 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.
RDBMS&SQL - 61 ©Minder Chen, 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
RDBMS&SQL - 62 ©Minder Chen, 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.
RDBMS&SQL - 63 ©Minder Chen, 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
RDBMS&SQL - 64 ©Minder Chen, 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.
RDBMS&SQL - 65 ©Minder Chen, SELECT Selecting All Columns: EXAMPLE SELECT * FROM STUDENT; RESULT S_NO NAME ADDRESS CITY ST ZIP TEL_NO MARY 102 1ST ST FAIRFAX VA TOM 39 5th AVE ARLINGTON DC LINDA 1 ROCK RD ROCKVILLE MD JAMES KATHY 2 KING LA FAIRFAX VA MIKE P.O.BOX 1 FAIRFAX VA NULL values Null means that there is no data and it is different from empty string.
RDBMS&SQL - 66 ©Minder Chen, 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
RDBMS&SQL - 67 ©Minder Chen, 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;
RDBMS&SQL - 68 ©Minder Chen, 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.
RDBMS&SQL - 69 ©Minder Chen, SELECT Finding NULL Columns EXAMPLE SELECT S_NO, NAME FROM STUDENT WHERE ADDRESS IS NULL; RESULT S_NO NAME JAMES
RDBMS&SQL - 70 ©Minder Chen, 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 MAR-83PATRICK LEE 02-SEP-88 JEAN LOU #01/01/1990# In Access SQL
RDBMS&SQL - 71 ©Minder Chen, 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 LOU 52 08
RDBMS&SQL - 72 ©Minder Chen, 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 SEP AND
RDBMS&SQL - 73 ©Minder Chen, 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 MAR SEP OR
RDBMS&SQL - 74 ©Minder Chen, 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 < OR ED < 11); RESULT I_NO D_O_H SALARY SEP
RDBMS&SQL - 75 ©Minder Chen, 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.
RDBMS&SQL - 76 ©Minder Chen, 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'
RDBMS&SQL - 77 ©Minder Chen, 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 D D020 1 D030 1
RDBMS&SQL - 78 ©Minder Chen, Selecting Values Within a Range SELECT I_NO, SALARY FROM INSTRUCTOR WHERE SALARY NOT BETWEEN AND 50000; - - WHERE SALARY RESULT I_NO SALARY
RDBMS&SQL - 79 ©Minder Chen, 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 D 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.)
RDBMS&SQL - 80 ©Minder Chen, 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
RDBMS&SQL - 81 ©Minder Chen, 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 D D020 1 D030 1 D040 1 D050 1
RDBMS&SQL - 82 ©Minder Chen, 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;
RDBMS&SQL - 83 ©Minder Chen, 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;
RDBMS&SQL - 84 ©Minder Chen, 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* 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)
RDBMS&SQL - 85 ©Minder Chen, 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
RDBMS&SQL - 86 ©Minder Chen, 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 D 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;
RDBMS&SQL - 87 ©Minder Chen, SELECT Expressions in Conditions: EXAMPLE SELECT I_NO, L_NAME, SALARY FROM INSTRUCTOR WHERE SALARY > 800 * 52; RESULT I_NO L_NAM SALARY LEE STONE FLYNN 48000
RDBMS&SQL - 88 ©Minder Chen, 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');
RDBMS&SQL - 89 ©Minder Chen, 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 D ADMINISTRATION D020 1 COMPUTER SCIENCE D030 1 ACCOUNTING D040 1 STATISTICS D050 1 MATHEMATICS D060 MARKETING D070 R&D
RDBMS&SQL - 90 ©Minder Chen, 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
RDBMS&SQL - 91 ©Minder Chen, 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';
RDBMS&SQL - 92 ©Minder Chen, 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 PATRICK D LEE ALBERT Y STONE BRUCE C WANG JEAN E LOU Click Run
RDBMS&SQL - 93 ©Minder Chen, 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.
RDBMS&SQL - 94 ©Minder Chen, 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.
RDBMS&SQL - 95 ©Minder Chen, FUNCTIONS AGGREGATE FUNCTIONS –COUNT (*) or COUNT(DISTINT column) –MAX –MIN –SUM –AVG Other Functions –SUBSTR –TRUNC –Format
RDBMS&SQL - 96 ©Minder Chen, COUNT PURPOSE: Counts the number of rows in each group that satisfy the condition(s) specified. EXAMPLE SELECT COUNT(*) FROM STUDENT; RESULT COUNT(*)
RDBMS&SQL - 97 ©Minder Chen, Count() How many students that we have from VA state? SELECT Count(*) AS [VA-Student-count] FROM STUDENT WHERE STUDENT.STATE='VA';
RDBMS&SQL - 98 ©Minder Chen, Use Query Design View SELECT Count(STUDENT.S_NO) AS CountOfS_NO FROM STUDENT WHERE (((STUDENT.STATE)="VA")); Tool Bar
RDBMS&SQL - 99 ©Minder Chen, COUNT EXAMPLE SELECT COUNT(ADDRESS) FROM STUDENT; RESULT COUNT(ADDRESS)
RDBMS&SQL ©Minder Chen, 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)
RDBMS&SQL ©Minder Chen, 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)
RDBMS&SQL ©Minder Chen, 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)
RDBMS&SQL ©Minder Chen, 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)
RDBMS&SQL ©Minder Chen, 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)
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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;
RDBMS&SQL ©Minder Chen, How to count distinct values 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.
RDBMS&SQL ©Minder Chen, Access Report Wizard 1 2 3
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, 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 DEAN TEACHER SELECT GB-column-name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY GB-column-name
RDBMS&SQL ©Minder Chen, 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) D D
RDBMS&SQL ©Minder Chen, 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 Show me each title and average salary of the title which has more than one instructors with such title. This is for privacy purpose.
RDBMS&SQL ©Minder Chen, 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 D ROUND(n[,m]): Returns n rounded to m decimal places; if m is omitted, to 0 places. Cannot use aggregate functions in WHERE clause!
RDBMS&SQL ©Minder Chen, 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;
RDBMS&SQL ©Minder Chen, 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 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;
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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#?
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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;
RDBMS&SQL ©Minder Chen, 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 FLYNN BRUCE C FLYNN BRUCE C STONE ALBERT C STONE ALBERT C STONE ALBERT C FLYNN BRUCE C STONE ALBERT C STONE ALBERT C 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.
RDBMS&SQL ©Minder Chen, Inner & Outer Joins Inner Join Left Outer Join Right Outer Join
RDBMS&SQL ©Minder Chen, 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 LEE PATRICK 19 STONE ALBERT C STONE ALBERT C STONE ALBERT C STONE ALBERT C STONE ALBERT C FLYNN BRUCE C FLYNN BRUCE C FLYNN BRUCE C 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
RDBMS&SQL ©Minder Chen, 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;
RDBMS&SQL ©Minder Chen, 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;
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, Create Forms in Access
RDBMS&SQL ©Minder Chen, Create a Simple Form
RDBMS&SQL ©Minder Chen, Form Layout and Style
RDBMS&SQL ©Minder Chen,
RDBMS&SQL ©Minder Chen, Detail Form in Datasheet Layout
RDBMS&SQL ©Minder Chen,
RDBMS&SQL ©Minder Chen,
RDBMS&SQL ©Minder Chen,
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, LOCK Permits users to explicitly acquire table locks. –Lock Objects »Row »Page »Table »Table Space –Lock Modes »Shared(S) Lock »Exclusive(X) Lock
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, 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.
RDBMS&SQL ©Minder Chen, APPENDIX A. Sample Database Tables 1. Instructor Table 2. Student Table 3. Division Table
RDBMS&SQL ©Minder Chen, Course Table 5. Offering Table 6. Registration Table
RDBMS&SQL ©Minder Chen, Physical Data Model
RDBMS&SQL ©Minder Chen, Normalization First Normal Form A table is in the first normal form if it contains no repeating value. Un-Normalized Relation: Normalized Relation:
RDBMS&SQL ©Minder Chen, 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
RDBMS&SQL ©Minder Chen, 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