Structured Query Language – The Basics By Hitesh Sahni www.hiteshsahni.com.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

Advanced SQL (part 1) CS263 Lecture 7.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
Database Systems: Design, Implementation, and Management Tenth Edition
Introduction to Database Systems 1 SQL: The Query Language Relation Model : Topic 4.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
1 Lecture 11: Basic SQL, Integrity constraints
SQL: Queries, Constraints, Triggers
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
Database Management Systems 1 Raghu Ramakrishnan SQL: Queries, Programming, Triggers Chpt 5.
SQL Constraints and Triggers
SQL: The Query Language Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein and etc for some slides.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
CS 405G: Introduction to Database Systems
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
FALL 2004CENG 351 File Structures and Data Management1 SQL: Structured Query Language Chapter 5.
Introduction to Structured Query Language (SQL)
Rutgers University SQL: Queries, Constraints, Triggers 198:541 Rutgers University.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5 (cont.)
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
1 SQL: Constraints and Triggers Chapter 5,
Unit 5/COMP3300/ SQL: Queries, Programming, Triggers Chapter 5.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
SQL: Queries, Programming, Triggers. Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Constraints and Triggers Chapter 5,
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Example Instances R1 S1 S2  We will use these instances of the Sailors and Reserves relations in our.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Overview: Features of SQL  Data definition language: used to create, destroy, and modify tables and.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
More SQL: Complex Queries,
SQL – Part 2.
COP Introduction to Database Structures
SQL The Query Language R & G - Chapter 5
SQL: Structured Query Language (‘Sequel’)
SQL: Queries, Programming, Triggers
SQL: Queries, Constraints, Triggers
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL: Structured Query Language
SQL: Queries, Programming, Triggers
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
Structured Query Language – The Basics
SQL: The Query Language (Part III)
SQL: Queries, Programming, Triggers
Presentation transcript:

Structured Query Language – The Basics By Hitesh Sahni

What We’re Going to Cover  Overview of SQL (This may be review for some of you) Data Definition Language  Creating tables (we’ll just talk about this) Data Manipulation Language  Inserting/Updating/Deleting data  Retrieving data  Single table queries  Where  Joins  Grouping

SQL  SQL is a data manipulation language.  SQL is not a programming language.  SQL commands are interpreted by the DBMS engine.  SQL commands can be used interactively as a query language within the DBMS.  SQL commands can be embedded within programming languages.

3 Types of SQL Commands  Data Definition Language (DDL): Commands that define a database - Create, Alter, Drop  Data Manipulation Language (DML) Commands that maintain and query a database.  Data Control Language (DCL) Commands that control a database, including administering privileges and committing data.

Data Manipulation Language (DML) Four basic commands:  INSERT  UPDATE  DELETE  SELECT

INSERT INTO tablename (column-list) VALUES (value-list) PUTS ONE ROW INTO A TABLE INSERT INTO COURSE (COURSE_CODE, COURSE_NAME, CREDIT_HOURS) VALUES (‘MIS499’,’ADVANCED ORACLE’,4); Inserting Data into a Table

INSERT INTO COURSE VALUES (‘MIS499’,’ADVANCED ORACLE’,4); INSERT INTO COURSE (COURSE_NAME, COURSE_CODE, CREDIT_HOURS) VALUES (’ADVANCED ORACLE’,‘MIS499’,4); More on Inserting Data COLUMN LIST IS OPTIONAL IF YOU PLAN TO INSERT A VALUE IN EVERY COLUMN AND IN THE SAME ORDER AS IN THE TABLE COLUMN LIST IS NEEDED TO CHANGE THEORDER - MUST MATCH VALUE LIST NOTE - TABLE STILL HAS THE ORIGINAL COLUMN ORDER

INSERT INTO COURSE (COURSE_CODE, CREDIT_HOURS) VALUES (‘MIS499’,4); INSERT INTO COURSE VALUES (‘MIS499’,’’,4); INSERT INTO COURSE VALUES (‘MIS499’,NULL,4); COLUMN LIST IS NEEDED IF YOU PLAN TO LEAVE OUT A VALUE IN THE VALUE LIST COLUMN LIST CAN BE OMITTED IF YOU PUT IN A BLANK VALUE THE NULL KEYWORD CAN BE USED TO CREATE A BLANK COLUMN ALL OF THESE ASSUME THAT THE DATABASE ALLOWS THE COLUMN TO BE NULL. YOU CANNOT LEAVE PRIMARY KEYS AND FOREIGN KEYS BLANK Inserting Null Data

SQL> INSERT INTO SECTION VALUES ('1234','MIS333','10-12','MW','COPE101',' '); INSERT INTO SECTION VALUES ('1234','MIS333','10-12','MW','COPE101', * ERROR at line 1: ORA-02291: integrity constraint (ORA40.SYS_C00337) violated - parent key not found SECTION CALL_NUMBERKEY COURSE_CODE SECTION_TIME SECTION_DAYS SECTION_ROOM INSTRUCTOR_ID COURSE COURSE_CODEKEY COURSE_NAME CREDIT_HOURS INSTRUCTOR INSTRUCTOR_IDKEY INSTRUCTOR_NAME INSTRUCTOR_OFFICE Inserting and Integrity Constraints

Entity Integrity Problems SQL> INSERT INTO COURSE VALUES ('MIS220','NEW',4); insert into course values ('MIS220','NEW',4) * ERROR at line 1: ORA-00001: unique constraint (ORA40.SYS_C00335) violated

DELETE COURSE; DELETES ALL ROWS DELETE COURSE WHERE COURSE_CODE = ‘MIS220’; DELETES SPECIFIC ROWS (MORE TYPICAL) DELETE COURSE WHERE HOURS=4; DELETES A GROUP OF ROWS DELETE COURSE WHERE HOURS<4; Be careful!! This deletes ALL of the rows in your table. If you use this command in error, you can use ROLLBACK to undo the changes. Deleting Data

SQL> DELETE COURSE WHERE COURSE_CODE='MIS220'; DELETE COURSE WHERE COURSE_CODE='MIS220' * ERROR at line 1: ORA-02292: integrity constraint (ORA40.SYS_C00341) violated - child record found Deleting and Integrity Constraints

UPDATE COURSE SET HOURS=5; CHANGES EVERY ROW UPDATE COURSE SET HOURS=5 WHERE COURSE_CODE=‘MIS220’ CHANGES ONE ROW(MORE TYPICAL) UPDATE COURSE SET HOURS=3 WHERE COURSE_CODE LIKE ‘MIS%’ CHANGES A GROUP OF ROWS Updating Data

YOU CAN CHANGE THE VALUE OF A FOREIGN KEY AS LONG AS THE NEW VALUE ALSO COMPLIES WITH REFERENTIAL INTEGRITY CONSTRAINTS. PRIMARY KEY VALUES CAN BE UPDATED AS LONG AS THERE ARE NO ROWS IN OTHER TABLES WITH FOREIGN KEYS WITH THE SAME VALUE DOES NOT MATTER IF CONSTRAINT IS RESTRICTED OR CASCADED Updating and Integrity Constraints

Integrity Error SQL> UPDATE COURSE SET COURSE_CODE='MIS221‘ WHERE COURSE_CODE='MIS220'; UPDATE COURSE * ERROR at line 1: ORA-02292: integrity constraint (ORA40.SYS_C00341) violated - child record found

CHANGES TO DATA ARE TEMPORARY DURING YOUR SQLPLUS SESSION DOES NOT APPLY TO CHANGES IN DATABASE STRUCTURE - ALTER... BEFORE LEAVING SQLPLUS, YOU CAN REVERSE THEM APPLIES TO INSERTS, UPDATES, AND DELETES Rollback and Commit

SQL>ROLLBACK; Rollback complete. REVERSES ALL CHANGES TO DATA MADE DURING YOUR SESSION SQL>COMMIT; MAKES ALL CHANGES TO THIS POINT PERMANENT POINTS AT WHICH COMMIT IS ISSUED, DEFINE EXTENT OF ROLLBACK ROLLBACK REVERSES EVERY CHANGE SINCE THE LAST COMMIT EXITING SQLPLUS ISSUES A COMMIT Rollback and Commit

SQL for Retrieving Data from One Table SELECT column_name, column_name, … FROM table_name WHERE condition/criteria;  This statement will retrieve the specified field values for all rows in the specified table that meet the specified conditions.  Every SELECT statement returns a recordset.

Conceptual Evaluation Strategy  Semantics of an SQL query defined in terms of the following conceptual evaluation strategy: Compute the cross-product of relation-list. Discard resulting tuples if they fail qualifications. Delete attributes that are not in target-list. If DISTINCT is specified, eliminate duplicate rows.  This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers.

SELECT * FROM COURSE WHERE COURSE_CODE LIKE ‘MIS%’; SELECT * FROM COURSE WHERE CREDIT HOURS BETWEEN 3 AND 5; SELECT * FROM CUSTOMER WHERE BALANCE < CREDIT_LIMIT; USE % TO SUBSTITUTE FOR ANY STRING 3 AND 5 ARE INCLUDED YOU CAN COMPARE TWO COLUMNS WHERE Conditions

More WHERE Conditions SELECT * FROM CUSTOMER WHERE STATE IN (‘OH’,’WV’,’KY’); SELECT * FROM CUSTOMER WHERE (CREDIT_LIMIT - BALANCE) <1000; LIST OF SPECIFIC VALUES TO LOOK FOR CAN MANIPULATE NUMBER VALUES MATHMATICALLY

SELECT * FROM CUSTOMER WHERE BALANCE >=500 AND BALANCE<=1000; SELECT * FROM CUSTOMER WHERE STATE = ‘OH’ OR CREDIT_LIMIT>1000; SELECT * FROM CUSTOMER WHERE NOT (STATE=‘OH’); TWO COMPARISONS ON THE SAME COLUMN TWO COMPARISONS ON THE DIFFERENT COLUMNS SAME AS STATE<>‘OH’ AND/OR/NOT Conditions

More on AND/OR/NOT CUSTSTATELIMIT BAL AOH BWV COH DOH EKY FKY GMA HNB Use parentheses to make complex logic more understandable. SELECT * FROM CUSTOMER WHERE STATE = ‘OH’ OR (CREDIT_LIMIT=1000 AND BALANCE <500); Who will be selected??

SQL - Other Features  * - All columns in a table  Aliases SELECT EmployeeID, LastName, FirstName, BirthDate AS DOB FROM Employee; SELECT EmployeeID, LastName, FirstName, FROM Employee AS E;  Dot Notation - ambiguous attribute names SELECT Customer.LName, E.Lname FROM Customer, Employee AS E WHERE...

SQL - Other Features  DISTINCT  Arithmetic operators: +, -, *, /  Comparison operators: =, >, >=,  Concatenation operator: ||  Substring comparisons: %, _  BETWEEN  AND, OR

SQL - Other Features  ORDER BY Clause  UNION, EXCEPT, INTERSECT  IN

SQL for Retrieving Data from Two or More Tables SQL provides two ways to retrieve data from related tables:  Join - When two or more tables are joined by a common field.  Subqueries - When one Select command is nested within another command.

SQL - Joins Joins:  The WHERE clause is used to specify the common field.  For every relationship among the tables in the FROM clause, you need one WHERE condition (2 tables - 1 join, 3 tables - 2 joins…) SELECT C.Cust_ID, Comp_Name, Country,OrderID FROM Customer AS C, Order AS O WHERE C.Cust_ID = O.Cust_ID AND Country = ‘USA’;

SQL - Joins  Inner Join - records from two tables are selected only when the records have the same value in the common field that links the tables (the default join).  Outer Join - A join between two tables that returns all the records from one table and, from the second table, only those records in which there is a matching value in the field on which the tables are joined.

STUDENT#: NAME: JOE STUDENT CODENAMEHOURSGRADEQUAR/YR MIS220FILE PROC4A389 ZOO100BIOLOGY3B288 PSY280EXP PSY4B+190 Getting tables into 3NF eliminates unnecessary redundancy, BUT now we need data from multiple tables to create some forms and reports. TRANSCRIPT Multi-Table Queries & Views

SECTION CALL_NUMBER COURSE_CODE SECTION_TIME SECTION_DAYS SECTION_ROOM INSTRUCTOR_ID INSTRUCTOR INSTRUCTOR_ID INSTRUCTOR_NAME INSTRUCTOR_OFFICE DESIRED OUTPUT: CALL-NUMBER1234 COURSE_CODEMIS380 SECTION_ROOMCOPE012 INSTRUCTOR_ID INSTRUCTOR_NAMEDAY REQUIRED NAVIGATION: JOIN SECTION 1234MIS WFCOPE INSTRUCTOR DAYCOPE290A Two-Table Query

SELECT CALL_NUMBER, COURSE_CODE, SECTION_ROOM, SECTION.INSTRUCTOR_ID, INSTRUCTOR_NAME FROM SECTION, INSTRUCTOR WHERE SECTION.INSTRUCTOR_ID = INSTRUCTOR.INSTRUCTOR_ID; THE WHERE CLAUSE IS USED TO TELL ORACLE HOW TO MATCH ROWS BETWEEN THE TWO TABLES – REQUIRES A COMMON KEY FOR COLUMN NAMES WHOSE LOCATION IS AMBIGUOUS, YOU MUST SPECIFY A TABLE NAME - SEE INSTRUCTOR_ID SELECT Command with Join Two Tables  One Join

Results CALL COURSSECTION INSTRU INSTR_NAME MIS300 COPE SUTHERLAND 0031 MIS300 COPE CHEN 0032 MKT301 COPE KIRCH 0033 MKT301 COPE KIRCH 0034 BUSL255COPE CHEN 0035 OPN310 COPE CUTRIGHT 0036 OPN310 COPE JDAY

STUDENT#: NAME: JOE STUDENT CODE NAME HOURSGRADEQUAR/YR MIS220FILE PROC 4A389 BIO100BIOLOGY 3B288 PSY280 EXP PSY 4B+190 STUDENT STUDENT_NUMBER STUDENT_NAME STUDENT_ADDRESS STUDENT_PHONE MAJOR COURSE COURSE_CODE COURSE_NAME CREDIT_HOURS TRANSCRIPT STUDENT_NUMBER COURSE_CODE GRADE QUAR_YR Joining More Than Two Tables

SELECT STUDENT.STUDENT_NUMBER, STUDENT_NAME, TRANSCRIPT.COURSE_CODE, GRADE, QUAR_YR, COURSE_NAME, CREDIT_HOURS FROM STUDENT, TRANSCRIPT, COURSE WHERE STUDENT.STUDENT_NUMBER =TRANSCRIPT.STUDENT_NUMBER AND TRANSCRIPT.COURSE_CODE =COURSE.COURSE_CODE; Three Tables  Two Joins The number of joins is always one less than the number of tables involved in the query SELECT Command

Results STUD STUDENT_NAME COUR GR QUA COURSE_NAME CREDIT 1121 TRENT RAZEK MIS320 A 1/91 SYSTEMS I TRENT RAZEK MIS420 C 2/92 SYSTEMS II TRENT RAZEK MIS495 B 3/93 MGT INFO SYSTEMS 4 NOTICE HOW YOU GET “LOGICAL” ROWS BACK FROM THE SELECT AS IF THEY CAN FROM A SINGLE TABLE WHEN IN FACT THE DATA COMES FROM THREE SEPARATE TABLES

Aliases for table names can be created in the FROM part of the SELECT statement. Then you can use the alias in place of the full table name when referring to columns in that table. Sometimes this can save you considerable typing! Using Aliases

Alias Example SELECT S.STUDENT_NUMBER, STUDENT_NAME, T.COURSE_CODE, GRADE, QUAR_YR, COURSE_NAME, CREDIT_HOURS FROM STUDENT S, TRANSCRIPT T, COURSE C WHERE S.STUDENT_NUMBER =T.STUDENT_NUMBER AND T.COURSE_CODE=C.COURSE_CODE;

Hints for Successful Joins  Plan your joins Draw a mini-ERD to show what tables are involved.  Count the number of tables involved in the SELECT query.  The number of joins is always one less than the number of tables in the query.  Watch out for ambiguous column names.

SQL - Aggregate Functions  These functions are applied to a set(s) of records/rows and return one value for each set. Count (…) Min (…) Max (…) Sum (…) Avg (…)  These functions thus aggregate the rows to which they are applied.

SQL - Aggregation  If one field in a Select clause is aggregated, all fields in the clause must be aggregated.  Aggregation: The process of transforming data from a detail to a summary level.  You can aggregate a field by including it after the GROUP BY clause or by making it the argument of an aggregating function. SELECT Region, SUM(UnitPrice * Quantity) FROM [Order_Details] GROUP BY Region;

SQL - Aggregation  When you use GROUP BY, every field in your recordset must be aggregated in some manner.  The same rule applies when you use an aggregating function such as SUM, COUNT, AVERAGE …. If one field in the Select clause is aggregated, then every other field in the Select clause must be aggregated in some manner.

SQL - Aggregation Additional SQL Clause - HAVING:  The HAVING clause is only used after the GROUP BY clause.  The HAVING clause specifies criteria for a GROUP, similar to how the WHERE clause specifies criteria for individual rows.

SELECT INSTRUCTOR_ID, SUM(SALARY) FROM STAFFING GROUP BY INSTRUCTOR_ID; INSTRUCTO SUM(SALARY) ORIGINAL DATA IN TABLE INSTRUCTOR SALARY USED WITH FUNCTIONS FOR SUBTOTALING GROUP BY

INSTRUCTO CALL SALARY SELECT INSTRUCTOR_ID, SUM(SALARY) FROM STAFFING GROUP BY CALL_NUMBER; DOES NOT MAKE SENSE TO DISPLAY SALARY OR CALL_NUMBER ON A GROUP BY INSTRUCTOR_ID BECAUSE THEY VARY DOES MAKE SENSE TO DISPLAY INSTRUCTOR_ID SINCE IT IS THE SAME ACROSS THE GROUP GROUP BY Columns

SELECT INSTRUCTOR_ID, SUM(SALARY) FROM STAFFING WHERE SALARY>2500 GROUP BY INSTRUCTOR_ID; INSTRUCTO SUM(SALARY) INSTRUCTO CALL SALARY WHERE CAN RESTRICT WHICH ROWS ARE PUT INTO THE GROUP GROUP BY and WHERE

SELECT INSTRUCTOR_ID, SUM(SALARY) FROM STAFFING HAVING SUM(SALARY)>4000 GROUP BY INSTRUCTOR_ID INSTRUCTO SUM(SALARY) INSTRUCTO CALL SALARY HAVING DETERMINES WHICH GROUPS WILL BE DISPLAYED GROUP BY and HAVING

SQL statement processing order (adapted from van der Lans, p.100) An intermediate recordset is developed after each clause.

Summary of Select Statements  SELECT - list of attributes and functions  FROM - list of tables  WHERE - conditions / join conditions  GROUP BY - attributes not aggregated in select clause  HAVING - group condition  ORDER BY - list of attributes

SQL – Advanced Topics ISM Advanced Database

What We’re Going to Cover  Subqueries (Nested queries) Example Correlated subquery  Join types Inner/outer  Integrity constraints  Triggers  Functions

Sample Database  Scripts to create and populate the database are available on the 6217 Web site.

Subqueries  A subquery is a query that is used in the WHERE condition of another query  AKA Nested query  Can be multiple levels of nesting  Can be used with SELECT, INSERT, UPDATE

Example 1: By “Hand” **** LIST PARTS W/ > AVERAGE NUMBER OF Q_ON_HAND **** FIRST QUERY: DETERMINE AVERAGE SELECT AVG(Q_ON_HAND) FROM INVENTORY ; **** SECOND QUERY: PLUG AVERAGE INTO WHERE CLAUSE SELECTPART_NO, Q_ON_HAND, DESCRIPTION FROMINVENTORY WHEREQ_ON_HAND > ORDER BY PART_NO ;

Example 1: Using Subquery SELECTPART_NO, Q_ON_HAND, DESCRIPTION FROMINVENTORY WHEREQ_ON_HAND > (SELECTAVG(Q_ON_HAND) FROM INVENTORY) ORDER BY PART_NO ;

Example 2: Using Join  List all suppliers who can deliver at least one product in less than 10 days SELECT DISTINCT (S.SUPPLIER_NO), SUPPLIER_NAME FROMSUPPLIERS S, QUOTATIONS Q WHERES.SUPPLIER_NO = Q.SUPPLIER_NO ANDDELIVERY_TIME < 10 ORDER BY S.SUPPLIER_NO ;

Example 2: Using Subquery SELECTSUPPLIER_NO, SUPPLIER_NAME FROMSUPPLIERS WHERESUPPLIER_NO IN (SELECTSUPPLIER_NO FROM QUOTATIONS WHEREDELIVERY_TIME < 10) ORDER BY SUPPLIER_NAME DESC ;

Example 3: With Aggregation  List all suppliers who can deliver a product in less than the average delivery time. SELECT SUPPLIER_NO, SUPPLIER_NAME FROM SUPPLIERS WHERE SUPPLIER_NO IN (SELECT SUPPLIER_NO FROM QUOTATIONS WHERE DELIVERY_TIME < (SELECT AVG(DELIVERY_TIME) FROM QUOTATIONS) ) ORDER BY SUPPLIER_NAME DESC ;

Example 4: ANY  LIST SUP_NO, PART, DEL FOR QUOTES WHERE DEL > ANY SUPPLIED BY #71 SELECTSUPPLIER_NO, PART_NO, DELIVERY_TIME FROM QUOTATIONS WHERE DELIVERY_TIME > ANY (SELECTDELIVERY_TIME FROM QUOTATIONS WHERE SUPPLIER_NO = 71) ;

Example 5: ALL  LIST SUP_NO, PART, DEL FOR QUOTES WHERE DEL > ALL SUPPLIED BY #71 SELECTSUPPLIER_NO, PART_NO, DELIVERY_TIME FROM QUOTATIONS WHERE DELIVERY_TIME > ALL (SELECTDELIVERY_TIME FROM QUOTATIONS WHERESUPPLIER_NO = 71) ;

Example 6: ANY  Who are alternate suppliers for parts supplied by #71? SELECTSUPPLIER_NO, PART_NO, DELIVERY_TIME FROMQUOTATIONS WHEREPART_NO = ANY (SELECTPART_NO FROMQUOTATIONS WHERESUPPLIER_NO = 71) ANDSUPPLIER_NO != 71 ORDER BY SUPPLIER_NO ;

Example 7: NOT EXISTS  List all suppliers who have not provided a quote SELECT* FROMSUPPLIERS WHERE NOT EXISTS (SELECT* FROMQUOTATIONS WHERESUPPLIER_NO = SUPPLIERS.SUPPLIER_NO) ORDER BY SUPPLIER_NO ;

Correlated Subqueries  A correlated subquery is a subquery that is evaluated once for each row processed by the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement. These examples show the general syntax of a correlated subquery:

Example 8: Step-by-Step  List all suppliers, parts and prices where quoted price is less than the average quote for that part. SELECTAVG(PRICE) FROM QUOTATIONS WHEREPART_NO = 321; SELECTSUPPLIER_NO, PART_NO, PRICE FROMQUOTATIONS Q WHEREPRICE < 4 ANDPART_NO = 321; SELECTSUPPLIER_NO, PART_NO, PRICE FROMQUOTATIONS Q WHEREPART_NO = 321;

Example 8: Correlated Subquery SELECTSUPPLIER_NO, PART_NO, PRICE FROMQUOTATIONS Q WHEREPRICE < (SELECTAVG(PRICE) FROM QUOTATIONS WHEREQ.PART_NO = PART_NO) ORDER BY PART_NO, SUPPLIER_NO;

Join Types  Natural join/inner join This is what you’re used to. Returns only rows where PK and FK values match. Does not repeat PK/FK columns  Equi-Join Similar to natural join, but includes both PK and FK values in record set.

Equi-Join Example SELECTI.PART_NO, Q.PART_NO, SUPPLIER_NO, PRICE FROMINVENTORY I, QUOTATIONS Q WHERE I.PART_NO = Q.PART_NO ORDER BY I.PART_NO ;

More Join Types  Outer join Includes columns with null FK values Problem: Inner join will not return a row that does not have a matching value.  Sometimes this prevents you from getting the output you want. Example: List all parts (including description) and any quotes that exist for each part. We want to include all parts even if there are no quotes for some of them.

Solution: Left Outer Join SELECTI.PART_NO, DESCRIPTION, SUPPLIER_NO, PRICE FROMINVENTORY I, QUOTATIONS Q WHEREI.PART_NO = Q.PART_NO (+) ORDER BY I.PART_NO ; This is what makes it an outer join. Include all rows from the table away from the (+) Includes all rows from the left table.

SQL Server Version SELECTI.PART_NO, DESCRIPTION, SUPPLIER_NO, PRICE FROMINVENTORY I, QUOTATIONS Q WHEREI.PART_NO *= Q.PART_NO ORDER BYI.PART_NO This is what makes it an outer join. Include all rows from the table closest to the * in *= Includes all rows from the left table.

Non-Solution: Right Outer Join SELECTI.PART_NO, DESCRIPTION, SUPPLIER_NO, PRICE FROM INVENTORY I, QUOTATIONS Q WHERE I.PART_NO (+)= Q.PART_NO ORDER BY I.PART_NO ; This query does not include all rows from the INVENTORY table. So, it doesn’t work. We could reverse the order of tables in the WHERE condition and the query would be OK

Right-Outer Join: SQL Server SELECTI.PART_NO, DESCRIPTION, SUPPLIER_NO, PRICE FROMINVENTORY I, QUOTATIONS Q WHEREI.PART_NO *= Q.PART_NO ORDER BYI.PART_NO

Null Values  Field values in a tuple are sometimes unknown (e.g., a rating has not been assigned) or inapplicable (e.g., no spouse’s name). SQL provides a special value null for such situations.  The presence of null complicates many issues. E.g.: Special operators needed to check if value is/is not null. Is rating>8 true or false when rating is equal to null? What about AND, OR and NOT connectives? We need a 3-valued logic (true, false and unknown). Meaning of constructs must be defined carefully. (e.g., WHERE clause eliminates rows that don’t evaluate to true.) New operators (in particular, outer joins) possible/needed.

Integrity Constraints (Review)  An IC describes conditions that every legal instance of a relation must satisfy. Inserts/deletes/updates that violate IC’s are disallowed. Can be used to ensure application semantics (e.g., sid is a key), or prevent inconsistencies (e.g., sname has to be a string, age must be < 200)  Types of IC’s: Domain constraints, primary key constraints, foreign key constraints, general constraints. Domain constraints: Field values must be of right type. Always enforced.

General Constraints  Useful when more general ICs than keys are involved.  Can use queries to express constraint.  Constraints can be named. CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ) CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid=bid)))

Constraints Over Multiple Relations CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S) + ( SELECT COUNT (B.bid) FROM Boats B) < 100 )  Awkward and wrong!  If Sailors is empty, the number of Boats tuples can be anything!  ASSERTION is the right solution; not associated with either table. CREATE ASSERTION smallClub CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S) + ( SELECT COUNT (B.bid) FROM Boats B) < 100 ) Number of boats plus number of sailors is < 100

Triggers  Trigger: procedure that starts automatically if specified changes occur to the DBMS  Three parts: Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs)

Triggers: Example (SQL:1999) CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS REFERENCING NEW TABLE NewSailors FOR EACH STATEMENT INSERT INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18

Some Useful Functions  ABS (n)  MOD (m,n) Returns the remainder of m/n  POWER (m,n)  ROUND(n[,m])  SIGN(n)  SQRT  TRUNC(15.79,1)

Character Functions  CONCAT(char1, char2) ||  LOWER/UPPER  LTRIM(char [,set]) RTRIM(char [,set]  SUBSTR(char, m [,n])  LENGTH(char)

Date Functions  ADD_MONTHS(d,n)  LAST_DAY(d)  MONTHS_BETWEEN(d1, d2)  ROUND(d[,fmt])  SYSDATE  TO_CHAR(d [, fmt [, 'nlsparams'] ])  TO_DATE(char [, fmt [, 'nlsparams'] ])

Data Dictionary Tables  DICTIONARY All tables and views that are available to the user This table contains several hundred rows  Useful Data Dictionary Views Use just like a table More useful (generally) than full tables Use DESCRIBE to see the columns in the view USER_TABLES USER_VIEWS USER_CONSTRAINTS USER_OBJECTS

Visit Me AT