bacs--485 sql 11 bacs 485 structured query language
TRANSCRIPT
BACS--485 SQL 1 1
BACS 485
Structured Query Language
BACS--485 SQL 1 2
Table Access
2 general mechanisms to access data in tables exists:» Record-at-a-time access
– Traditional programming languages» Set-at-a-time access
– SQL, QBE, Both methods can accomplish the same
thing, but set-at-a-time is usually more efficient.
BACS--485 SQL 1 3
Table Access
Set-at-a-time access means that you do not have to explicitly manipulate the record pointer or perform a loop.
This creates a non-procedural environment were you describe what the solution looks like, not how to do it.
The most popular set-at-a-time language is called Structured Query Language.
BACS--485 SQL 1 4
Structured Query Language
Structured Query Language (SQL) is a 4th generation language designed to work with relational sets.
Commands exist to create and load tables, select subsets of tables, and modify existing tables.
SQL is not a full programming language. It is intended to be embedded in another, more traditional, language.
BACS--485 SQL 1 5
Structured Query Language
There are many types of SQL» ANSI-86 SQL» ANSI-89 SQL» ANSI-92 SQL» ANSI-99 SQL (SQL3)
» ANSI-03 SQL (added XML features)
» ANSI-06 SQL (XML as stored queries)
» ANSI-08 SQL (Modified Order BY, added Instead, & Truncate)
» ANSI-11 SQL (added temporal support)
» Visual Basic/Access SQL» ORACLE SQL» other software have their own versions...
BACS--485 SQL 1 6
Structured Query Language
ANSI-SQL commands are divided into 3 primary groups:» Data Definition Language commands» Data Manipulation Language commands» Data Control Language commands
Oracle SQL supports all three areas completely
BACS--485 SQL 1 7
Data Definition Language
Common DDL commands include:» CREATE TABLE
Define the structure of a new table» ALTER TABLE
Change the structure of an existing table» CREATE INDEX
Add an index to an existing table» DROP TABLE
Delete the structure (and data) of a table» DROP INDEX
Delete the index from a table
BACS--485 SQL 1 8
Create Table
Define the structure of a new table.
CREATE TABLE name (col-name type [(size)] [CONSTRAINT],...);
-Where-
CONSTRAINT name {PRIMARY KEY | UNIQUE |
REFERENCES foreign-table [(foreign-field)] }
BACS--485 SQL 1 9
Create Table Example
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));
BACS--485 SQL 1 10
Alter Table
Add a column to the "right" of an existing table or drop an existing column. Also allows you to add, drop, anf modify constraints.
ALTER TABLE tablename
{ADD {col-name type [(size)] | constraint}}
| MODIFY {col_name type [(size)]
| DROP {col-name [drop-clause];
BACS--485 SQL 1 11
Alter Table Example
Example1: Add column MINOR to STUDENT table
ALTER TABLE STUDENT ADD MINOR CHAR(8);
Example2: Drop the MGR-SSN column
ALTER TABLE EMPLOYEE DROP COLUMN MGR-SSN;
Example3: Add a foreign key ALTER TABLE DEPT ADD FOREIGN KEY EMP_ID
REFERENCES EMP EMP_ID;
BACS--485 SQL 1 12
Create Index
Create an index on an attribute within a table
CREATE [UNIQUE] INDEX index-name ON table-name {(col-name [ASC | DESC])};
BACS--485 SQL 1 13
Create Index Example
Example1: Create an index on the STUID attribute of the STUDENT table
CREATE INDEX stu_index ON STUDENT (STUID);
Example2: Create a unique index on SSN of EMPLOYEES where no nulls are allowed
CREATE UNIQUE INDEX emp_index ON EMPLOYEES (SSN) WITH DISALLOW NULL;
BACS--485 SQL 1 14
Create Index Example
Example 3: Create a composite index on COURSENUM and STUID from ENROLL table
CREATE INDEX enroll-idx ON ENROLL (COURSENUM,STUID);
BACS--485 SQL 1 15
Drop Table/Index
Remove a table (and all data) or an index on a table from database
DROP TABLE table-name [CASCADE CONSTRAINTS];
-or-
DROP INDEX index-name;
BACS--485 SQL 1 16
Drop Table Example
Example1: Delete the table STUDENT
DROP TABLE STUDENT;
Example2: delete table ENROLL (with foreign key constraints)
DROP TABLE ENROLL CASCADE CONSTRAINTS;
Example3: Remove the emp-name index on employee table
DROP INDEX emp-name;
BACS--485 SQL 1 17
Data Manipulation Language
Visual Basic DML commands include:» SELECT
Retrieve data from a database, create copies of tables, specify tuples for updating
» INSERTAdd data to tables
» UPDATEChange existing data in tables
» DELETERemove data from tables
BACS--485 SQL 1 18
Generic Select Statement
By far, the most commonly used DML statement is the SELECT. It combines a range of functionality into one complex command. This is the generic format.
SELECT {field-list | * | DISTINCTROW field} FROM table-list WHERE expression GROUP BY group-fields
HAVING group-expressionORDER BY field-list;
BACS--485 SQL 1 19
Select Clauses
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".
BACS--485 SQL 1 20
Select Clauses
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 WHERE clause, except that it only applies to the output of GROUP BY.
BACS--485 SQL 1 21
Select Clauses
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.
BACS--485 SQL 1 22
Select Examples
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 received a 10% raise.
SELECT LNAME, SALARY AS CURRENT, SALARY * 1.1 AS PROPOSED
FROM EMPLOYEES;
BACS--485 SQL 1 23
Single Table Select Examples
Example 1: Retrieve all information about students
SELECT *
FROM STUDENT;
Example 2: Find the last name, ID, and credits of all students
SELECT LNAME, STUID, CREDITS
FROM STUDENT;
BACS--485 SQL 1 24
Single Table Select Examples
Example 3: Find all information about students who are math majors
SELECT * FROM STUDENTWHERE MAJOR = 'Math';
Example 4: Find the student ID of all History majors
SELECT STUIDFROM STUDENTWHERE MAJOR = 'History';
BACS--485 SQL 1 25
Enhanced Where Clauses
The WHERE clause can be enhanced to be more selective. Operators that can appear in WHERE conditions include:
=, <> ,< ,> ,>= ,<=INBETWEEN...AND...LIKEIS NULLAND, OR, NOT
BACS--485 SQL 1 26
Single Table Select Examples
Example 1: Find the student ID of all math majors with more than 30 credit hours.
SELECT STUIDFROM STUDENTWHERE MAJOR = 'Math' AND CREDITS > 30;
Example 2: Find the student ID and last name of students with between 30 and 60 hours (inclusive).
SELECT STUID, LNAMEFROM STUDENTWHERE CREDITS BETWEEN 30 AND 60;
BACS--485 SQL 1 27
Single Table Select Examples
Example 3: Retrieve the ID of all students who are either a math or an art major.
SELECT STUIDFROM STUDENTWHERE MAJOR IN ('Math','Art');
Example 4: Retrieve the ID and course number of all students without a grade in a class.
SELECT STUID, COURSENUMFROM ENROLLWHERE GRADE IS NULL;
BACS--485 SQL 1 28
Single Table Select Examples
Example 5: List the course number and faculty ID for all math courses.
SELECT COURSENUM, FACID
FROM CLASS
WHERE COURSENUM LIKE 'MTH%';
BACS--485 SQL 1 29
Aggregate Function Select
SQL also allows several aggregate functions to appear in the SELECT line of the SELECT statement. These include:
Max, Min, Avg, Sum, Count, StdDev, Variance Example 1: How many students are there?
SELECT COUNT(*)FROM STUDENT;
BACS--485 SQL 1 30
Aggregate Function Select
Example 2: Find the number of departments that have faculty in them.SELECT COUNT(DISTINCTROW DEPT)
FROM FACULTY;
Example 3: Find the average number of credits for students who major in math.
SELECT AVG(CREDITS)
FROM STUDENT
WHERE MAJOR = 'Math';
BACS--485 SQL 1 31
Ordering the Select Result
Example 1: List the names and IDs of all faculty members arranged in alphabetical order.
SELECT FACID, FACNAMEFROM FACULTYORDER BY FACNAME;
Example 2: List names and IDs of faculty members.
SELECT FACID, FACNAMEFROM FACULTYORDER BY FACNAME, FACID DESC;
BACS--485 SQL 1 32
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.
BACS--485 SQL 1 33
Group By Examples
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;
BACS--485 SQL 1 34
Group By Examples
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;
BACS--485 SQL 1 35
Group By Examples
Example 3: Find all courses in which fewer than three students are enrolled.
SELECT COURSENUM
FROM ENROLL
GROUP BY COURSENUM
HAVING COUNT(*) < 3;
BACS--485 SQL 1 36
SQL Join Operation
A JOIN operation is performed when more than one table is specified in the FROM clause. You join two tables if you need information from both.
You must specify the JOIN condition explicitly in SQL. This includes naming the columns the two tables have in common and the comparison operator.
BACS--485 SQL 1 37
SQL Join Examples
Example 1: Find the name and courses that each faculty member teaches.
SELECT FACULTY.FACNAME, COURSENUMFROM FACULTY, CLASSWHERE FACULTY.FACID = CLASS.FACID;
Note how the table name is appended to the FACNAME field of the SELECT clause. This is called qualification. It is required if the same name is used in 2 tables.
BACS--485 SQL 1 38
SQL Join Examples
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;
BACS--485 SQL 1 39
SQL Nested Queries
SQL allows the nesting of one query inside another, but only in the WHERE and the HAVING clauses.
ANSI SQL permits a subquery only on the right hand side of an operator.
The innermost query is performed first and its results are passed to the next level out of the query.
BACS--485 SQL 1 40
SQL Nested Example
Example 1: Find the names and IDs of all faculty members who teach a class in room 'H221'.
SELECT FACNAME, FACID
FROM FACULTY
WHERE FACID IN
(SELECT FACID
FROM CLASS
WHERE ROOM = 'H221');
BACS--485 SQL 1 41
SQL Nested Example
Example 2: Retrieve an alphabetical list of last names and IDs of all students in any class taught by faculty number 'F110'.
SELECT LNAME, STUIDFROM STUDENTWHERE STUID IN
(SELECT STUID FROM ENROLL WHERE COURSENUM IN
(SELECT COURSENUM FROM CLASS WHERE FACID =
'F110'))ORDER BY LNAME;
BACS--485 SQL 1 42
SQL Nested Example
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);
BACS--485 SQL 1 43
Other Select Types
SQL provides other select options. One of the more useful options is a Union Query»Union Queries - Allows you to combine
the results of several queries into a single table. The resulting table contains all tuples from all queries.
BACS--485 SQL 1 44
Union Queries
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;
BACS--485 SQL 1 45
Views
Views are a way to save your select queries so that you do not have to build them each time you need them.
The view saves the procedure (not the result) for he query.
Views are a “free” form of security
BACS--485 SQL 1 46
Views
Views are used to simplify queries and to provide security.
They are often called "virtual tables" because the table is not stored in the database. Instead, the procedure to derive the view is stored.
The view is generated whenever it is requested, thus it is always up-to-date and does not take up any disk space.
BACS--485 SQL 1 47
Views
You build views by first creating a valid select and then adding one line of code before the select.
Any valid select can fill in the select portion.
In all cases (except for update) views can be used in the same was as select statements.
BACS--485 SQL 1 48
Views
Example: Build a view called CLASS_LIST that contains the student IDs and last name for all students in the class 'ART103A'.
CREATE VIEW CLASS_LIST AS
SELECT STUID, LNAME
FROM ENROLL, STUDENT
WHERE COURSENUM = 'ART103A'
AND ENROLL.STUID = STUDENT.STUID;
BACS--485 SQL 1 49
Update Statement
Update gives you a way to modify individual attributes of a single tuple, a group of tuples, or a whole table (or view).
UPDATE table SET col-name = {value | expression}
[col-name = value,...] [WHERE update_criteria];
BACS--485 SQL 1 50
Update Examples
Example 1: Change the major of student 'S1020' to music.
UPDATE STUDENT
SET MAJOR = 'Music'
WHERE STUID = 'S1020';
Example 2: Change grades of all students in 'CIS201A' to A.
UPDATE ENROLL
SET GRADE = 'A'
WHERE COURSENUM = 'CIS201A';
BACS--485 SQL 1 51
Insert Statement
The INSERT operator is used to put new records into a table. You can use it with a nested SELECT to load existing data efficiently into a new table.
It is also useful to remove columns from existing tables. INSERT also allows you to 1) change the data type of an existing column, 2) rename an existing table, and 3) rename an existing column.
BACS--485 SQL 1 52
Insert Statement
Format1:
INSERT INTO table (fieldlist)
SELECT fieldlist
FROM table
WHERE append_criteria;
Format2:
INSERT INTO table (col1, col2...) VALUES (val1, val2...);
BACS--485 SQL 1 53
Insert Examples
Example 1: Insert a new faculty record with ID of 'F330', name of Jones, department of CIS, and rank of Instructor.
INSERT INTO FACULTY (FACID, FACNAME, DEPT, RANK)VALUES ('F330','Jones','CIS',Instructor');
Example 2: Fill a new ENROLLMENT table that shows each course and the number of students enrolled in it.
INSERT INTO ENROLLMENT (COURSENUM, STUDENTS)SELECT COURSENUM, COUNT(*)
FROM ENROLL GROUP BY COURSENUM;
BACS--485 SQL 1 54
Delete Statement
The DELETE operator is used to erase tuples (not table structure). The number of tuples deleted may be 0, 1, or many, depending on how many satisfy the predicate.
DELETE FROM table WHERE delete_criteria;
BACS--485 SQL 1 55
Delete Examples
Example 1: Erase the record of student 'S1020'.
DELETE FROM STUDENT
WHERE STUID = 'S1020';
Example 2: Erase all enrollment records for student 'S1020'.
DELETE FROM ENROLL
WHERE STUID = 'S1020';
BACS--485 SQL 1 56
Delete Examples
Example 3: Erase all enrollment records for Owen McCarthy.
DELETE FROM ENROLL
WHERE STUID =
(SELECT STUID
FROM STUDENT
WHERE FNAME = 'Owen' AND LNAME = 'McCarthy');