560 likes | 664 Views
BACS 485. Structured Query Language. 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.
E N D
BACS 485 Structured Query Language
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.
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.
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.
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...
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
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
Create Table Define the structure of a new table. CREATE TABLE name (col-nametype [(size)] [CONSTRAINT],...); -Where- CONSTRAINT name {PRIMARY KEY | UNIQUE | REFERENCES foreign-table [(foreign-field)] }
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));
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];
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;
Create Index Create an index on an attribute within a table CREATE [UNIQUE] INDEX index-name ON table-name {(col-name [ASC | DESC])};
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;
Create Index Example Example 3: Create a composite index on COURSENUM and STUID from ENROLL table CREATE INDEX enroll-idx ON ENROLL (COURSENUM,STUID);
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;
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;
Data Manipulation Language • Visual Basic DML commands include: • SELECT Retrieve data from a database, create copies of tables, specify tuples for updating • INSERT Add data to tables • UPDATE Change existing data in tables • DELETE Remove data from tables
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-expression ORDER BY field-list;
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".
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.
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.
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;
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;
Single Table Select Examples Example 3: Find all information about students who are math majors SELECT * FROM STUDENT WHERE MAJOR = 'Math'; Example 4: Find the student ID of all History majors SELECT STUID FROM STUDENT WHERE MAJOR = 'History';
Enhanced Where Clauses The WHERE clause can be enhanced to be more selective. Operators that can appear in WHERE conditions include: =, <> ,< ,> ,>= ,<= IN BETWEEN...AND... LIKE IS NULL AND, OR, NOT
Single Table Select Examples Example 1: Find the student ID of all math majors with more than 30 credit hours. SELECT STUID FROM STUDENT WHERE 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, LNAME FROM STUDENT WHERE CREDITS BETWEEN 30 AND 60;
Single Table Select Examples Example 3: Retrieve the ID of all students who are either a math or an art major. SELECT STUID FROM STUDENT WHERE MAJOR IN ('Math','Art'); 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;
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%';
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;
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';
Ordering the Select Result Example 1: List the names and IDs of all faculty members arranged in alphabetical order. SELECT FACID, FACNAME FROM FACULTY ORDER BY FACNAME; Example 2: List names and IDs of faculty members. 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.
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;
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;
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;
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.
SQL Join Examples Example 1: Find the name and courses that each faculty member teaches. SELECT FACULTY.FACNAME, COURSENUM FROM FACULTY, CLASS WHERE 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.
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;
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.
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');
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, STUID FROM STUDENT WHERE STUID IN (SELECT STUID FROM ENROLL WHERE COURSENUM IN (SELECT COURSENUM FROM CLASS WHERE FACID = 'F110')) ORDER BY LNAME;
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);
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.
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;
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
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.
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.
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;
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];
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';