Kamis, 23 Oktober 2014

MULTIPLE TABLE QUERIES

JOIN operation is performed when more than one table is specified in the FROM clause.  You would join two tables if you need information from both. You must specify the JOIN condition explicitly in SQL.  This includes naming the columns in common and the comparison operator.

Example 1

Find the name and courses that each faculty member teaches.
SELECT FACULTY.FACNAME, COURSENUM FROM FACULTY, CLASS WHERE FACULTY.FACID = CLASS.FACID;
FACULTY.FACNAMECOURSENUM
AdamsART103A
TanakaCIS201A
ByrneMTH101B
SmithHST205A
ByrneMTH103C
TanakaCIS203A
When both tables have an attribute name in common, you must specify which version of the attribute that you are referring to by preceding the attribute name with the table name and a period.  (e.g.,table‑name.col‑name).  This is called “qualification”.
It is sometimes more convenient to use an “alias” (an alternative name) for each table.  SQL specifies alias names in the FROM clause immediately following the actual table.  Once defined, you can use the alias anywhere in the SELECT where you would normally use the table name.

Example 2

Find the course number and the major of all students taught by the faculty member with ID number ‘F110′. (3 table JOIN)
SELECT ENROLL.COURSENUM, LNAME, MAJOR FROM CLASS , ENROLL, STUDENT WHERE FACID = ‘F110′ AND CLASS.COURSENUM = ENROLL.COURSENUM AND ENROLL.STUID = STUDENT.STUID;
ENROLL.COURSENUM
LNAME
MAJOR
MTH101B
Rivera
CIS
MTH103C
Burns
ART
MTH103C
Chin
Math
Using aliases, this would be:SELECT E.COURSENUM, LNAME, MAJOR FROM CLASS C, ENROLL E, STUDENT S WHERE FACID = ‘F110′ AND C.COURSENUM = E.COURSENUM AND E.STUID = S.STUID;

NESTED QUERIES

SQL allows the nesting of one query inside another, but only in the WHERE and the HAVING clauses.  In addition, SQL permits a subquery only on the right hand side of an operator.

Example 1

Find the names and IDs of all faculty members who teach a class in room ‘H221′. You could do this with 2 queries as follows:
SELECT FACID FROM CLASS WHERE ROOM = ‘H221′;
—> RESULT:  F101, F102
SELECT FACNAME, FACID FROM FACULTY WHERE FACID IN (F101, F102);
or you could combine the 2 into a nested query:
SELECT FACNAME, FACID FROM FACULTY WHERE FACID IN (SELECT FACID FROM CLASS WHERE ROOM = ‘H221′);
Note that the nested SELECT is executed first and its results are used as the argument to the outer SELECTs IN clause.
FACNAMEFACID
AdamsF101
SmithF202

Example 2

Retrieve an alphabetical list of last names and IDs of all students in any class taught by faculty number ‘F110′.
SELECT LNAME, STUID FROM STUDENT  WHERE STUID IN (SELECT STUID FROM ENROLL WHERE COURSENUM IN (SELECT COURSENUM FROM CLASS WHERE FACID = ‘F110′)) ORDER BY LNAME;
LNAMESTUID
BurnsS1010
ChinS1002
RiveraS1020
The most deeply nested SELECT is done first.  Thus, after the first select you have:
SELECT LNAME, STUID FROM STUDENT WHERE STUID IN (SELECT STUID FROM ENROLL WHERE COURSENUM IN (‘MTH101B’,'MTH103C’)) ORDER BY LNAME;
Next, the next most deeply is done.
SELECT LNAME, STUID FROM STUDENT WHERE STUID IN (‘S1020′,’S1010′,’S1002′) ORDER BY LNAME;
Finally, the outer Select is executed giving the result printed above.

Example 3

Find the name and IDs of students who have less than the average number of credits.
SELECT LNAME, STUID FROM STUDENT WHERE CREDITS < (SELECT AVG(CREDITS) FROM STUDENT);
LNAMESTUID
ChinS1002
RiveraS1020
McCarthyS1013

UNION QUERIES

A union query performs the ‘union‘ set operation on two or more tables.  The union operation returns all tuples from all tables (like appending a second table to the bottom of the first). The union operation also allows you to sort the resulting data, perform where restriction, etc.  The syntax for the UNION operator is shown below.

Format

SELECT fields FROM tables WHERE criteria GROUP BY field HAVING criteria
UNION
SELECT fields FROM tables WHERE criteria 
GROUP BY field HAVING criteria ORDER BY sortcriteria;
Each select is a standard select with two exceptions.  First, the fields shown in the SELECT clause must be ‘union compatible’ (i.e., equivalent number, type, and order).  Second, there can only be one order by for the entire query.

Example 1

Join a compatible customer table and a supplier table for all customers and suppliers located in ‘Brazil’.  Sort the final result by zip code.
SELECT CompanyName, City, Zip, Region, SupplierID AS ID FROM Suppliers WHERE Country = ‘Brazil’ UNION SELECT CompanyName, City, Zip, Region, CustomerID AS ID FROM Customer WHERE Country = ‘Brazil’ ORDER BY Zip;
Oracle SQL also supports an INTERSECTION and MINUS clause that is similar to the UNION clause.  These two new connectors have the same syntax as the UNION clause and perform the set operations indicated by their name.

UPDATE

Update gives you a way to modify individual attributes of a single tuple, a group of tuples, or a whole table (or view).
Format:
UPDATE table/view SET col-name = {value | expression} [col-name = value | subquery,...] [WHERE update_criteria];
You can only update tuples already present in the table (i.e., you cannot use UPDATE to add new tuples).  You can either UPDATE one table at a time.  You don’t have to know the present value of a field to set it (although you can refer to it in the “expression” clause).  The expression cannot be a sub-query or involve aggregate operations.

Example 1

Change the major of student ‘S1020′ to music. (Update a single field of one tuple)
UPDATE STUDENT SET MAJOR = ‘Music’ WHERE STUID = ‘S1020′;

Example 2

Change Tanaka’s department to MIS and rank to Assistant.  (Update several fields in one tuple)
UPDATE FACULTY SET DEPT = ‘MIS’ RANK = ‘Assistant’ WHERE FACNAME = ‘Tanaka’;

Example 3

Change the major of student ‘S1013′ from math to NULL.  (Updating using NULL)
UPDATE STUDENT SET MAJOR = NULL WHERE STUID = ‘S1013′;

Example 4

Change grades of all students in ‘CIS201A’ to A. (Updating several tuples)
UPDATE ENROLL SET GRADE = ‘A’ WHERE COURSENUM = ‘CIS201A’;

Example 5

Give all students three extra credits. (Update all tuples)
UPDATE STUDENT SET CREDITS = CREDITS + 3;

Example 6

Change the room to ‘B220′ for all courses taught by Tanaka. (Updating with a subquery)
UPDATE CLASS SET ROOM = ‘B220′ WHERE FACID = (SELECT FACID FROM FACULTY WHERE FACNAME = ‘Tanaka’);

INSERT

The INSERT operator is used to put new records into a table.  Normally it is not used to load an entire database (since other utilities can do that more efficiently).  Aside from this, older implementations of SQL use it to remove columns from existing tables (before the ALTER TABLE had this capability).
Format1:
INSERT INTO table (fieldlist) SELECT fieldlist FROM table WHERE append_criteria;
OR
Format2
INSERT INTO table (col1, col2…) VALUES (val1, val2…);
On the general format2 above, you can specify the columns in any order you wish and the system will match them to the appropriate table attributes.

Example 1

Insert a new faculty record with ID of ‘F330′, name of Jones, department of CIS, and rank of Instructor.  (Inserting a single record).
INSERT INTO FACULTY (FACID, FACNAME, DEPT, RANK) VALUES (‘F330′,’Jones’,'CIS’,Instructor’);
Since you are inserting for all fields, you can leave off the column names after FACULTY and get the same effect.  For instance, the following two examples are equivalent:
INSERT INTO FACULTY VALUES (‘F330′,’Jones’,'CIS’,Instructor’);
INSERT INTO FACULTY SELECT * FROM DATATABLE;
‘Datatable’ is a table that holds the data to be inserted.  Since the data is already in a table, this format of the INSERT is not as useful as the first version.

Example 2

Insert a new student record with Id of ‘S1031′, name of Maria Bono, 0 credits, and no major.  (Insert a record with NULL value in a field)
INSERT INTO STUDENT (FNAME, LNAME, STUID, CREDITS) VALUES (‘Maria’, ‘Bono’, ‘S1031′, 0);
Notice that the field names are rearranged from the table order.  This does not matter.  Also notice that major is missing and will therefore be inserted into the tuple as NULL.

Example 3

Create and fill a new table that shows each course and the number of students enrolled in it.  (Inserting multiple tuples into a new table)
CREATE TABLE ENROLLMENT (COURSENUM CHAR(7) PRIMARY KEY, STUDENTS INTEGER);
INSERT INTO ENROLLMENT (COURSENUM, STUDENTS) SELECT COURSENUM, COUNT(*) FROM ENROLL GROUP BY COURSENUM;

DELETE

The DELETE operator is used to erase records (not table structure).  The number of records deleted may be 0, 1, or many, depending on how many satisfy the predicate.
Format:
DELETE FROM table/view WHERE delete_criteria;

Example 1

Erase the record of student ‘S1020′  (Delete a single tuple)
DELETE FROM STUDENT WHERE STUID = ‘S1020′;

Example 2

Erase all enrollment records for student ‘S1020′.  (Delete several tuples).
DELETE FROM ENROLL WHERE STUID = ‘S1020′;

Example 3

Erase all the class records.  (Deleting all the tuples from a table)
DELETE FROM CLASS;
Note that the table CLASS still exists, but is empty.  To remove the data and the table you use the DROP TABLE operator.

Example 4

Erase all enrollment records for Owen McCarthy.  (Delete with a subquery)
DELETE FROM ENROLL WHERE STUID = (SELECT STUID FROM STUDENT WHERE FNAME = ‘Owen’ AND LNAME = ‘McCarthy’);
In our database there is no such student, so no records are deleted from ENROLL.

EXAMPLE DATABASE

The following E/R diagram and tables are used in the examples throughout this post.

STUDENT

STUIDLNAMEFNAMEMAJORCREDITS
S1001SmithTomHistory90
S1010BurnsEdwardArt63
S1015JonesMaryMath42
S1002ChinAnnMath36
S1020RiveraJaneCIS15
S1015McCarthyOwenMath9

CLASS

COURSENUMFACIDSCHEDROOM
ART103AF101MWF9H221
CIS201AF105TUTHF10M110
MTH101BF110MTUTH9H225
HST205AF202MWF11H221
MTH103CF110MWF11H225
CIS203AF105MTHF12M110

FACULTY

FACIDFACNAMEDEPTRANK
F101AdamsArtProfessor
F202SmithHistoryAssociate
F105TanakaCISInstructor
F110ByrneMathAsistant
F221BlumeCISProfessor

ENROLL

COURSENUMSTUIDGRADE
ART103AS1001A
CIS201AS1020B
CIS201AS1002F
ART103AS1010-0-
ART103AS1002D
MTH101BS1020A
HST205AS1001C
MTH103CS1010-0-
MTH103CS1002B