appendix 1 - sql reference
TRANSCRIPT
-
8/2/2019 Appendix 1 - SQL Reference
1/21
1
Structured Query Language
Many database management systems support some version of structured query language (SQL).
In some DBMSs (i.e., ORACLE) SQL is the primary data manipulation interface. Consequently,
SQL is a very important topic. The purpose of this document is to introduce you to the majorSQL statements and to show you how they work. This document will concentrate primarily on
ORACLE SQL; however, some attention also will be given to other versions of SQL. This is not
a complete reference of SQL. If you are interested in a more detailed coverage I can suggest
several good textbooks for outside reading.
SQL commands can be broken into the 3 following functional groups: .
- Data Definition Language (DDL) - used to define the schema (structure) of the
database
- CREATE TABLE
- ALTER TABLE- CREATE INDEX
- DROP TABLE
- DROP INDEX
- Data Manipulation Language (DML) - used to retrieve and
update from the database
- SELECT
- INSERT
- UPDATE
- DELETE
- Data Control Language (DCL) - used to manipulate the processing of data and erform
other misc. functions
- COMMIT
- ROLLBACK
I. SQL DATA DEFINITION (DDL)
TABLES
CREATE TABLE - Define the structure of a new table
-
8/2/2019 Appendix 1 - SQL Reference
2/21
2
Format:
CREATE TABLEtablename ({col-name type [(size)][constraint],...});
The 'constraint' clause in the CREATE TABLE statement is used to enforce referential integrity.
Specifically, PRIMARY KEY, FOREIGN KEY, and CHECK integrity can be set when youdefine the table. The syntax for key and check constraints is shown below.
{PRIMARY KEY | FOREIGN KEY} (local-field) [REFERENCESforeign-field] }
for attribute constraints...
CHECK (condition)
Example: Define the student table
CREATE TABLE STUDENT( STUID CHAR(5),
LNAME CHAR(10) NOT NULL,
FNAME CHAR(8),
MAJOR CHAR(7) CHECK (MAJOR IN (HIST,ART,CIS)),
CREDITS INTEGER CHECK (CREDITS > 0),
PRIMARY KEY (STUID));
ALTER TABLE - Add a column to the "right" of an existing table, modify an existing attribute,
or drop an existing column or constraint.
Format:
ALTER TABLEtablename
{ADD {col-name type [(size)] | constraint}}
| MODIFY {col_name type [(size)]
| DROP {col-name [drop-clause];
where the drop clause is ...
DROP {PRIMARY KEY | UNIQUE {col-name} | CONSTRAINT constraint|
Example1: Add column called MINOR to STUDENT table
ALTER TABLE STUDENT ADD MINOR CHAR(8);
Example2: Drop the MGR-SSN column
ALTER TABLE EMPLOYEE DROP MGR-SSN;
Example3: Modify existing attribute
-
8/2/2019 Appendix 1 - SQL Reference
3/21
3
ALTER TABLE DEPT MODIFY MINOR CHAR(10);
LIMITATIONS/ENHANCEMENTS:
When you add a column, all existing tuples get the extra column filled with NULL values. You
have to go in and update the column to enter valid data later to get rid of the NULLs. You can
only add or drop a single column at a time in the ALTER statement.
CREATE INDEX - Create an index on attribute(s) within a table
Indexes are used to improve system performance by providing a more efficient means of
accessing selected attributes.
Format:
CREATE [UNIQUE] INDEX index-name ONtable-name {(col-name [ASC |
DESC])};
Example1: Create an index on the STUID attribute of the STUDENT table
CREATE INDEX stuindex ON STUDENT (STUID);
Example2: Create a unique index on SSN of EMPLOYEES and make it sort in reverse order
CREATE UNIQUE INDEX empindex ON EMPLOYEES (SSN) DESC;
Example 3: Create a composite index on COURSENUM and SDUID from ENROLL table
CREATE INDEX enroll-idx ON ENROLL (COURSENUM, STUID);
DROP TABLE - Remove a table (and all data) or an index on a table from database. If the table
has any foreign key constraints then the CASCADE CONSTRAINTS clause is required to dropthe table.
Format:
DROP TABLEtable-name [CASCADE CONSTRAINTS];
DROP INDEX index-name;
Example1: Delete the table STUDENT (no foreign key constraints)
DROP TABLE STUDENT;
Example2: Delete the table ENROLL (with foreign key constraints)
DROP TABLE ENROLL CASCADE CONSTRAINTS;
Example3: Remove the emp-name index on employee table
DROP INDEX emp-name;
When you drop a table you also delete all data currently in that table. Be careful!
-
8/2/2019 Appendix 1 - SQL Reference
4/21
4
II. SQL DATA MANIPULATION LANGUAGE (DML)
The DML component of SQL is the part that is used to query and update the tables (once they
are built via DDL commands or other means).
By far, the most commonly used DML statement is the SELECT. It combines a range of
functionality into one complex command.
SELECT
Used primarily to retrieve data from the database. Also used to create copies of tables, create
views, and to specify rows for updating.
General Format: Generic overview applicable to most commercial SQL implementations - lots of
potential combinations. There are several variations available in Oracle.
SELECT {field-list | * | ALL | DISTINCT | expression}
FROM table-list
WHERE expression
GROUP BY group-fields
HAVING group-expression
ORDER BY field-list;
Only the SELECT and the FROM clauses are required. The others are optional.
FROM - A required clause that lists the tables that the select works on. You can define
"alias" names with this clause to speed up query input and to allow recursive "self-joins".
WHERE - An optional clause that selects rows that meet the stated condition. A "sub-
select" can appear as the expression of a where clause. This is called a "nested select".
GROUP BY - An optional clause that groups rows according to the values in one or
more columns and sorts the results in ascending order (unless otherwise specified). The
duplicate rows are not eliminated, rather they are consolidated into one row. This is
similar to a control break in traditional programming.
HAVING - An optional clause that is used with GROUP BY. It selects from the rows
that result from applying the GROUP BY clause. This works the same as the WHEREclause, except that it only applies to the output of GROUP BY.
ORDER BY - An optional clause that sorts the final result of the SELECT into either
ascending or descending order on one or more named columns.
There can be complex interaction between the WHERE, GROUP BY, and HAVING clauses.
When all three are present the WHERE is done first, the GROUP BY is done second, and the
HAVING is done last.
-
8/2/2019 Appendix 1 - SQL Reference
5/21
5
Example 1: Select all employees from the 'ACCT department.
SELECT * FROM EMPLOYEES WHERE EMP-DEPT = 'ACCT';
Example 2: Show what salary would be if each employee recieved a 10% raise.
SELECT LNAME, SALARY AS CURRENT, SALARY * 1.1 AS PROPOSEDFROM EMPLOYEES;
SIMPLE SINGLE TABLE RETRIEVAL
Example 1: Retrieve all information about students ('*' means all attributes)
SELECT * FROM STUDENT;
STUID LNAME FNAME MAJOR CREDITS
S1001 Smith Tom History 90
S1010 Burns Edward Art 63S1015 Jones Mary Math 42
S1002 Chin Ann Math 36
S1020 Rivera Jane CIS 15
S1013 McCarchy Owen Math 9
Example 2: Find the last name, ID, and credits of all students
SELECT LNAME, STUID, CREDITS
FROM STUDENT;
LNAME STUID CREDITS
Smith S1001 90
Burns S1010 63
Jones S1015 42
Chin S1002 36
Rivera S1020 15
McCarthy S1013 9
Example 3: Find all information about students who are math majors
SELECT *FROM STUDENT
WHERE MAJOR = 'Math';
STUID LNAME FNAME MAJOR CREDITS
S1015 Jones Mary Math 42
S1002 Chin Ann Math 36
S1013 McCarthy Owen Math 9
-
8/2/2019 Appendix 1 - SQL Reference
6/21
6
Example 4: Find the student ID of all History
SELECT STUID
FROM STUDENTWHERE MAJOR = 'History';
STUID
S1001
Example 5: Retrieve a list of all majors that currently have students
SELECT DISTINCT MAJOR
FROM STUDENT;
MAJORArt
CIS
History
Math
MORE COMPLEX SINGLE TABLE RETRIEVAL
The WHERE clause can be enhanced to be more selective. Operators that can appear in
WHERE conditions include:
=, ,< ,> ,>= , 30;
STUID
S1015
S1002
-
8/2/2019 Appendix 1 - SQL Reference
7/21
7
Example 2: Find the student ID and last name of students with between 30 and 60 hours
(inclusive).
SELECT STUID, LNAME
FROM STUDENT
WHERE CREDITS BETWEEN 30 AND 60;
this is the same as...
SELECT STUID, LNAME
FROM STUDENT
WHERE (CREDITS >= 30) AND (CREDITS
-
8/2/2019 Appendix 1 - SQL Reference
8/21
8
Example 4: Retrieve the ID and course number of all students without a grade in a class.
SELECT STUID, COURSENUM
FROM ENROLL
WHERE GRADE IS NULL;
STUID COURSENUM
S1010 ART103A
S1010 MTH103C
NOTE: IS NULL may only appear in the WHERE clause. Also note that you say "IS NULL",
not "= NULL". NULL means "unknown" and does not really have a value in the normal sense.
Example 5: List the ID and course number for all students that successfully completed classes
(the inverse of #4 above).
SELECT STUID, COURSENUMFROM ENROLL
WHERE GRADE IS NOT NULL;
STUID COURSENUM
S1001 ART103A
S1020 CIS201A
S1002 CIS201A
S1002 ART103A
S1020 MTH101B
S1001 HST205A
S1002 MTH103C
Example 6: List the course number and faculty ID for all math courses.
SELECT COURSENUM, FACID
FROM CLASS
WHERE COURSENUM LIKE 'MTH%';
COURSENUM FACID
MTH101B F110
MTH103C F110
NOTE: % is a wildcard for any number of characters. _ is a wildcard that replaces a single
character. They can be used together along with normal characters.
COLUMN FUNCTIONS (AGGREGATE FUNCTIONS)
-
8/2/2019 Appendix 1 - SQL Reference
9/21
9
Aggregate functions allow you to calculate values based upon all data in an attribute of a table.
The SQL aggregate functions are: Max, Min, Avg, Sum, Count,StdDev, Variance. Note that
AVG and SUM work only with numeric values and both exclude NULL values from the
calculations.
Example 1: How many students are there?
SELECT COUNT(*)
FROM STUDENT;
COUNT(*)
6
NOTE: COUNT can be used in two ways. COUNT(*) is used to count the number of tuples that
satisfy a query. COUNT with DISTINCT is used to count the number of unique values in anamed column.
Example 2: Find the number of departments that have faculty in them.
SELECT COUNT(DISTINCT DEPT)
FROM FACULTY;
COUNT(DISTINCT)
4
Example 3: Find the average number of credits for students who major in math.
SELECT AVG(CREDITS)
FROM STUDENT
WHERE MAJOR = 'Math';
AVG(CREDITS)
29
ORDERING OF THE QUERY RESULT
The ORDER BY clause is used to force the query result to be sorted based on one or more
column values. You can select either ascending or descending sort for each named column.
Example 1: List the names and IDs of all faculty members arranged in alphabetical order.
SELECT FACID, FACNAME
-
8/2/2019 Appendix 1 - SQL Reference
10/21
10
FROM FACULTY
ORDER BY FACNAME;
FACID FACNAME
F101 Adams
F110 ByrneF221 Smith
F202 Smith
F105 Tanaka
Example 2: List names and IDs of faculty members. The primary sort is the name and the
secondary sort is by descending ID (for seniority purposes).
SELECT FACID, FACNAME
FROM FACULTY
ORDER BY FACNAME, FACID DESC;
GROUPING QUERY RESULTS
The GROUP BY clause is used to specify one or more fields that are to be used for organizing
tuples into groups. Rows that have the same value(s) are grouped together.
The only fields that can be displayed are the ones used for grouping and ones derived using
column functions. The column function is applied to a group of tuples instead to the entire table.
If the HAVING clause is used, it takes the intermediate table produced by the GROUP BY and
applies further selection criteria. Note that the data are aggregated when the HAVING is
applied, so the HAVING expression should be written appropriately.
Example 1: Find the number of students enrolled in each course. Display the course number and
the count.
SELECT COURSENUM, COUNT(*)
FROM ENROLL
GROUP BY COURSENUM;
-
8/2/2019 Appendix 1 - SQL Reference
11/21
11
COURSENUM COUNT(*)
ART103A 3
CIS201A 2
HST205A 1
MTH101B 1MTH103C 2
Example 2: Find the average number of hours taken for all majors. Display the name of the
major, the number of students, and the average.
SELECT MAJOR, COUNT(*), AVG(CREDITS)
FROM STUDENT
GROUP BY MAJOR;
MAJOR COUNT(*) AVG(CREDIT)
Art 1 63
CIS 1 15
History 1 90
Math 3 29
Example 3: Find all courses in which fewer than three students are enrolled.
SELECT COURSENUM
FROM ENROLLGROUP BY COURSENUM
HAVING COUNT(*) < 3;
COURSENUM
CIS201A
HST205A
MTH101B
MTH103C
MULTIPLE TABLE QUERIES
A 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.
-
8/2/2019 Appendix 1 - SQL Reference
12/21
12
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.FACNAME COURSENUM
Adams ART103A
Tanaka CIS201A
Byrne MTH101B
Smith HST205A
Byrne MTH103C
Tanaka CIS203A
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:
-
8/2/2019 Appendix 1 - SQL Reference
13/21
13
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 FACIDFROM 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 FACULTYWHERE 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.
FACNAME FACID
Adams F101
Smith F202
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
-
8/2/2019 Appendix 1 - SQL Reference
14/21
14
WHERE STUID IN
(SELECT STUID
FROM ENROLL
WHERE COURSENUM IN
(SELECT COURSENUM
FROM CLASSWHERE FACID = 'F110'))
ORDER BY LNAME;
LNAME STUID
Burns S1010
Chin S1002
Rivera S1020
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.
-
8/2/2019 Appendix 1 - SQL Reference
15/21
15
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