Presentation is loading. Please wait.

Presentation is loading. Please wait.

BACS--485 SQL 11 BACS 485 Structured Query Language.

Similar presentations


Presentation on theme: "BACS--485 SQL 11 BACS 485 Structured Query Language."— Presentation transcript:

1 BACS--485 SQL 11 BACS 485 Structured Query Language

2 BACS--485 SQL 12 Table Access l 2 general mechanisms to access data in tables exists: »Record-at-a-time access –Traditional programming languages »Set-at-a-time access –SQL, QBE, l Both methods can accomplish the same thing, but set-at-a-time is usually more efficient.

3 BACS--485 SQL 13 Table Access l Set-at-a-time access means that you do not have to explicitly manipulate the record pointer or perform a loop. l This creates a non-procedural environment were you describe what the solution looks like, not how to do it. l The most popular set-at-a-time language is called Structured Query Language.

4 BACS--485 SQL 14 Structured Query Language l Structured Query Language (SQL) is a 4th generation language designed to work with relational sets. l Commands exist to create and load tables, select subsets of tables, and modify existing tables. l SQL is not a full programming language. It is intended to be embedded in another, more traditional, language.

5 BACS--485 SQL 15 Structured Query Language l 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...

6 BACS--485 SQL 16 Structured Query Language l ANSI-SQL commands are divided into 3 primary groups: »Data Definition Language commands »Data Manipulation Language commands »Data Control Language commands l Oracle SQL supports all three areas completely

7 BACS--485 SQL 17 Data Definition Language l 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

8 BACS--485 SQL 18 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)] }

9 BACS--485 SQL 19 Create Table Example CREATE TABLE STUDENT ( STUIDCHAR(5), LNAMECHAR(10) NOT NULL, FNAMECHAR(8), MAJORCHAR(7) CHECK (MAJOR IN (‘HIST’,’ART’,’CIS’)), CREDITSINTEGER CHECK (CREDITS > 0), PRIMARY KEY (STUID));

10 BACS--485 SQL 110 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];

11 BACS--485 SQL 111 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;

12 BACS--485 SQL 112 Create Index Create an index on an attribute within a table CREATE [UNIQUE] INDEX index-name ON table-name {(col-name [ASC | DESC])};

13 BACS--485 SQL 113 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;

14 BACS--485 SQL 114 Create Index Example Example 3: Create a composite index on COURSENUM and STUID from ENROLL table CREATE INDEX enroll-idx ON ENROLL (COURSENUM,STUID);

15 BACS--485 SQL 115 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;

16 BACS--485 SQL 116 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;

17 BACS--485 SQL 117 Data Manipulation Language l 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

18 BACS--485 SQL 118 Generic Select Statement l 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;

19 BACS--485 SQL 119 Select Clauses l 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". l 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".

20 BACS--485 SQL 120 Select Clauses l 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. l 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.

21 BACS--485 SQL 121 Select Clauses l 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. l 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.

22 BACS--485 SQL 122 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;

23 BACS--485 SQL 123 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;

24 BACS--485 SQL 124 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';

25 BACS--485 SQL 125 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

26 BACS--485 SQL 126 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;

27 BACS--485 SQL 127 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;

28 BACS--485 SQL 128 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%';

29 BACS--485 SQL 129 Aggregate Function Select l 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;

30 BACS--485 SQL 130 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';

31 BACS--485 SQL 131 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;

32 BACS--485 SQL 132 Grouping Query Results l 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. l 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.

33 BACS--485 SQL 133 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;

34 BACS--485 SQL 134 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;

35 BACS--485 SQL 135 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;

36 BACS--485 SQL 136 SQL Join Operation l 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. l You must specify the JOIN condition explicitly in SQL. This includes naming the columns the two tables have in common and the comparison operator.

37 BACS--485 SQL 137 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; l 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.

38 BACS--485 SQL 138 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;

39 BACS--485 SQL 139 SQL Nested Queries l SQL allows the nesting of one query inside another, but only in the WHERE and the HAVING clauses. l ANSI SQL permits a subquery only on the right hand side of an operator. l The innermost query is performed first and its results are passed to the next level out of the query.

40 BACS--485 SQL 140 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');

41 BACS--485 SQL 141 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;

42 BACS--485 SQL 142 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);

43 BACS--485 SQL 143 Other Select Types l 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.

44 BACS--485 SQL 144 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;

45 BACS--485 SQL 145 Views l Views are a way to save your select queries so that you do not have to build them each time you need them. l The view saves the procedure (not the result) for he query. l Views are a “free” form of security

46 BACS--485 SQL 146 Views l Views are used to simplify queries and to provide security. l They are often called "virtual tables" because the table is not stored in the database. Instead, the procedure to derive the view is stored. l The view is generated whenever it is requested, thus it is always up-to-date and does not take up any disk space.

47 BACS--485 SQL 147 Views l You build views by first creating a valid select and then adding one line of code before the select. l Any valid select can fill in the select portion. l In all cases (except for update) views can be used in the same was as select statements.

48 BACS--485 SQL 148 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;

49 BACS--485 SQL 149 Update Statement l 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];

50 BACS--485 SQL 150 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';

51 BACS--485 SQL 151 Insert Statement l 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. l 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.

52 BACS--485 SQL 152 Insert Statement Format1: INSERT INTO table (fieldlist) SELECT fieldlist FROM table WHERE append_criteria; Format2: INSERT INTO table (col1, col2...) VALUES (val1, val2...);

53 BACS--485 SQL 153 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;

54 BACS--485 SQL 154 Delete Statement l 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;

55 BACS--485 SQL 155 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';

56 BACS--485 SQL 156 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');


Download ppt "BACS--485 SQL 11 BACS 485 Structured Query Language."

Similar presentations


Ads by Google