1/2/20101 Lecture 4 on Structural Query Language To study Structural Query Language (SQL) as a non-procedural computer language to access relational database.

Slides:



Advertisements
Similar presentations
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Advertisements

Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Database Design -- Basic SQL
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Objective: To access a database from an application program (as opposed to interactive interfaces) Why? An interactive interface is convenient but not.
Introduction to Structured Query Language (SQL)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 9 Structured Query Language.
1 Query Languages: How to build or interrogate a relational database Structured Query Language (SQL)
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Concepts of Database Management Sixth Edition
Chapter 9 MORE SQL: Assertions, Views, and Programming Techniques Copyright © 2004 Pearson Education, Inc.
Microsoft Access 2010 Chapter 7 Using SQL.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
ASP.NET Programming with C# and SQL Server First Edition
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 9- 1 DATADABASE PROGRAMMING 2Chapter 13 from our text.
Database A collection of related data. Database Applications Banking: all transactions Airlines: reservations, schedules Universities: registration, grades.
Database Technical Session By: Prof. Adarsh Patel.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
BACS--485 SQL 11 BACS 485 Structured Query Language.
A Free sample background from © 2006 By Default! R.SARAVANA KUMAR S.NAVEEN Relational Database Model.
Concepts of Database Management Seventh Edition
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Relational Algebra CS420. Relation A relation is a two dimensional table that Rows contain data about an entity Columns contains data about attributes.
Chapter 9 Structured Query Language David M. Kroenke Database Processing © 2000 Prentice Hall.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
SQL “Structured Query Language; standard language for relational data manipulation” DB2, SQL/DS, Oracle, INGRES, SYBASE, SQL Server, dBase/Win, Paradox,
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.
Advanced SQL: Triggers & Assertions
Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
(C) 2000, The University of Michigan 1 Database Application Design Handout #5 February 4, 2000.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Query Processing – Implementing Set Operations and Joins Chap. 19.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
10/3/2017.
CH 9 SQL 9.1 Querying A Single Table 9.2 Querying Multiple Tables
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
CS 480: Database Systems Lecture 13 February 13,2013.
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
CS580 Advanced Database Topics
CS4222 Principles of Database System
Introduction to SQL Programming Techniques
Unit I-2.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Chapter 8 Advanced SQL.
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
Presentation transcript:

1/2/20101 Lecture 4 on Structural Query Language To study Structural Query Language (SQL) as a non-procedural computer language to access relational database in data definitional language such as Create, Drop and Alter statements and in data manipulation language such as Insert, Update and Delete statements.

1/2/20102 Structural Query Language (SQL) SQL is a transform oriented relational language. SQL can be run as a query/update language by itself or SQL command can be embedded in application programs. SQL include commands for data definition, data manipulation and data control. It is non-procedural and includes no reference to access paths, links or navigation such that the user only need to specify what he wants to retrieve/update rather than how to do it. It has a high level of independence from physical data storage.

1/2/20103 SQL syntax SELECT [Distinct] select-list FROMfrom-list WHEREqualification GROUP BYgrouping-list HAVINGgroup-qualification ORDERattribute-list

1/2/20104 Where The Where clause limits the rows that are returned from Query: For example: Select * from users where userid = 2

1/2/20105 Order by This command can sort by any column type: alphabetical, chronological or numeric in either ascending or descending order by placing asc or desc: For example: Select * from users order by lname, fname

1/2/20106 Having The having predicate restricts the rows displayed by a group by (whereas the where clause restricts the rows that are used in the group by). For example: Select avg(contribution) as avg_contrib, state from contributions group by state having avg(contribution) > 500

1/2/20107 Sample database for SQL SIDNAMEMAJORGRADE _LEVEL AGE 100JONESHISTGR21 150PARKSACCTSO19 200BAKERMATHGR50 250GLASSHISTSN50 300BAKERACCTSN41 350RUSELLMATHJR20 400RYEACCTFR18 450JONESHISTSN24 Student Relation

1/2/20108 STUDENT_ NUMBER CLASS_NA ME POSITION_ NUMBER 100BD BA BD CS CS BA BF CS BA2003 Class_ NAME TIMEROOM BA200MF9SC110 BD445MWF3SC213 BF410MWF8SC213 CS150MWF3EA304 CS250MWF1 2 EB210 Class Relation Enrollment Relation

1/2/20109 SQL Projections The projection Student[Sid, Name, Major] is created by Select Sid, Name, Major from Student  100JonesHist 150ParksAcct 200BakerMath 250GlassHist 300BakerAcct 350RussellMath 400RyeAcct 450JonesHist

1/2/ Select statement with Unique: SelectUniqueMajor fromStudent =>Hist Acct Math Select statement with where clause: Select * from studentwhere Major = ‘Math’  200BakerMathGr50 350RussellMathJr20 Note: The * in the SQL statement means that all attributes of the relation are to be obtained.

1/2/ Select statement with several conditions: Select Name, Age from Student where Major = ‘Math’ and Age > 21  Baker50 Select statement with an In clause: Select Name from Student where Major in [‘Math’, ‘Acct’] =>Parks Baker Russell Rye Select statement with an Not In clause: Select Name from Student where Major not in [‘Math’, ‘Acct’] =>Jones Glass Jones

1/2/ Select statement with LIKE conditions Like operation allows a rich set of regular expressions to be used as patterns while searching text. For example, SELECT Age FROMstudent WHEREName = ‘R_%E’ The only such student is Rye and his age is 18.

1/2/ SQL Built-in functions Some standard built-in functions are available in SQL as follows: Count:computes the number of tuples in a relation Sum:totals numeric attributes Avg:computes the average value Max:obtain the maximum value of an attribute Min:obtain the minimum value of an attribute For example: Select Count(Major) from Student  8 Select Count(Unique Major) from Student  3 Select Sid, Name from Student where Age > Avg(Age)  200Baker 250Glass 300Baker

1/2/ Built-in functions and grouping Built-in functions can be applied to groups of tuples within a relation. Such groups are formed by collecting tuples together that have the same value of a specific attribute. The SQL keyword Group By instructs the DBMS to group tuples together that have the same value of an attribute. For example, the count function sums the number of tuples in each group/ Select Major, Count(*) from Student Group By Major =>Hist3 Acct3 Math2 For example, use SQL Having clause to identify the subset of groups we want to consider. Select Major, Avg(Age) from Student Group By Major Having Count(*)>2  Hist31.67 Acct26

1/2/ Union, Intersect, Except Union set operation is similar to “or” condition in where clause. Intersect set operation is similar to “and” condition in where clause. Except set operation is a difference set operation in relational algebra.

1/2/ Select Name from student where age 40 Can be rewritten as Select Name from student where age < 20 Union Select Name from student where age > 40 The answer is Rye, Baker, and Glass.

1/2/ Select Name from student where age < 20 and Grade = SN Can be rewritten as Select Name from student where age < 20 INTERSECT Select Name from student where Grade = SN The answer is Jones

1/2/ Select Name from student where Major not = ‘Hist’ Can be rewritten as Select name from student EXCEPT Select name from student where Major = ‘Hist’ The answer is: Parks, Baker, Rusell and Rye.

1/2/ Querying multiple relations by using Subquery Suppose we need to know the names of students enrolled in the class BD445. If we know that only students 100 and 200 are enrolled in this class, then the following will produce the correct names. Select Name from Student Where Sid in [100, 200] =>Jones Baker Select Student_number from Enrollment where Class_name = ‘BD445’ => By combining the above 2 SQL statements, the SQL subquery can be easier to understand as follows: Select Name from Student where Sid in Select Student_number from Enrollment where Class_name=‘BD445’ =>Jones Baker

1/2/ Suppose we want to know the names of the students enrolled in classes on Monday, Wednesday and Friday at 3o’clock. First, we need the name of classes that meet at that time. Select Class.Name from Class where Time=‘MWF3’ =>BD445 CS150 Now, what are the identifying numbers of relations in these classes? We can specify: Select Student_number from Enrollment where Enrollment.Class_name in Select Class_name from Class where Time = ‘MWF3’ => Now, to obtain the names of those students, we specify: Select Student.name from Student where Student.Sid in Select Enrollment.Student_number from Enrollment where Enrollment.Class_name in Select Class_name from Class where Time = ‘MWF3’ =>Jones Baker

1/2/ Querying multiple relations using Join A join is the combination of a product operation, followed by a selection and a projection. For example, the From statement expresses the product of Student and Enrollment. The Where statement expresses the selection. The projection of student number, name and class name is taken. Select Student.Sid, Student.Name, Enrollment.Class_Name From Student, Enrollment Where Student.Sid=Enrollment.Student_Number =>100JonesBD ParksBA BakerBD BakerCS BakerCS RyeBA RyeBF RyeCS JonesBA200 In this example, table Student and Enrollment are joined.

1/2/ Comparison of SQL Subquery and Join Join expressions can substitute for subquery expressions, the converse is not true. Subqueries cannot always be substituted for joins. When using a subquery, the displayed attributes can come from only the relation name in the from expression in the first select. For example, if we want to know the names of the students enrolled in classes on Monday, Wednesday, and Friday at 3 o’clock using Join. Select Student.Name from Student, Enrollment, Class Where Student.Sid = Enrollment.Student_Number and Enrollment.Class_Name = Class.Name and Class.Time = ‘MWF3’ If we want to know both the names of the classes and the grade levels of the undergraduate students, then we must use a join. A subquery will not suffice because the desired results arise from two different relations of Enrollment and Student.

1/2/ Exists and Not Exists Exists and Not Exists are logical operators; their value is either true or false depending on the presence of absence of tuples that fit qualifying conditions. For example, suppose we want to know the numbers of students enrolled in more than one class. The meaning of the subquery expression is “Find 2 tuples in enrollment having the same student number but different class names”. Select unique Student_number from Enrollment A where Exists Select * from Enrollment B where A.Student_number = B.Student_number and A.Class_name not = B.Class_name =>

1/2/ Another example is that we want to know the names of students taking all classes. An expression is to say we want the names of students such that there are no classes that the student did not take. Select Student.Name from Student where not exists Select * from Enrollment where not exists Select * from Class where Class.Name = Enrollment.Class_name and Enrollment.Student_number = Student.Sid Note: This query has three parts. In the bottom part, we try to find classes the student did not take. The middle part determines if any classes were found that the student did not take. If not, then the student is taking all classes, and the student’s name is displayed.

1/2/ Inserting data Tuples can be inserted into a relation one at a time or in groups To insert a single tuple, we state Insert into Enrollment [400, ‘BD445’, 44] Or if we do not know all of this data, we could say Insert into Enrollment (Student_number, Class_name) [400, ‘BD445’] Note: If the student’s information is not available, this insertion will cause an referential integrity problem such that a child relation’s tuple can only be inserted if its corresponding parent relation’s tuple exists.

1/2/ Deleting data Tuples can be deleted one at a time or in groups. For example, we want to delete the tuple for student number 100 Delete Student where Student.Sid = 100 Note: If student 100 is enrolled in classes, this deletion will cause an referential integrity problem such that a parent relation’s tuple can be deleted only if its corresponding child relation’s tuple has been deleted. Another example is to delete groups of tuples. Delete Enrollment where Enrollment.Student_number IN Select Student.Sid from Student where Student.Major = ‘ACCT’ Delete Student where Student.Major = ‘ACCT’ Note: The order of these two deletion is important. If the order were reversed, none of the Enrollment tuples would be deleted because the matching Student tuples have already been deleted.

1/2/ Modifying data Tuples can be modified one at a time or in groups. The keyword Set is used to change an attribute value. After Set, the name of the attribute to be changed is specified and then the new value or way of computing the new value. Update Enrollment Set Position_number = 44 where Student_number = 400 Update Enrollment Set Position_number = Max(Position_number) + 1 where Student_number = 400 Note: the value of the attribute will be calculated using the Max built-in function. Another example for mass update is to change a course from BD445 to BD564. In this case, to prevent referential integrity problem, we perform as follows: alter table Enrollment Add Constraint FK foreign key (Class_name) references Class(Class_name) on update cascade; Update Enrollment Set Class_name = ‘BD564’ where Class_name = ‘BD445’ Update Class Set Class_name = ‘BD564’ where Class_name = ‘BD445’

1/2/ Database Programming Approaches Embedded commands: –Database commands are embedded in a general-purpose programming language Library of database functions: –Available to the host language for database calls; known as an API API standards for Application Program Interface

1/2/ Embedded SQL in MS SQL Server Stored Procedure Stored Procedure: create proc integer as select * from course where course_no return Execution of Stored Procedure: execute show_course 4

1/2/ Embedded SQL Most SQL statements can be embedded in a general- purpose host programming language such as COBOL, C, Java An embedded SQL statement is distinguished from the host language statements by enclosing it between EXEC SQL or EXEC SQL BEGIN and a matching END-EXEC or EXEC SQL END (or semicolon) –Syntax may vary with language –Shared variables (used in both languages) usually prefixed with a colon (:) in SQL

1/2/ Example: Variable Declaration in Language C Variables inside DECLARE are shared and can appear (while prefixed by a colon) in SQL statements SQLCODE is used to communicate errors/exceptions between the database and the program int loop; EXEC SQL BEGIN DECLARE SECTION; varchar dname[16], fname[16], …; char ssn[10], bdate[11], …; int dno, dnumber, SQLCODE, …; EXEC SQL END DECLARE SECTION;

1/2/ Example for SQL Commands for Connecting to a Oracle Database In the “Microsoft ODBC for Oracle Setup” dialog, enter the following: Database Source Name: ora9i Description: Username: Server Name: w2ksc Start “Oracle -> OraHome90 -> Application Development -> SQL Plus User Name:grp## Password:abcd1234 Host String:w2ksc

1/2/ Example of a non-menu driven embedded SQL Stored Procedure to access an Oracle Database create procedure upd_per (in_id in integer) as begin update person set name = 'abc' where id_no = in_id; end; execute upd_per(1);

1/2/ Embedded SQL in C Programming Examples loop = 1; while (loop) { prompt (“Enter SSN: “, ssn); EXEC SQL select FNAME, LNAME, ADDRESS, SALARY into :fname, :lname, :address, :salary from EMPLOYEE where SSN == :ssn; if (SQLCODE == 0) printf(fname, …); else printf(“SSN does not exist: “, ssn); prompt(“More SSN? (1=yes, 0=no): “, loop); END-EXEC }

1/2/ Embedded SQL in C Programming Examples A cursor (iterator) is needed to process multiple tuples FETCH commands move the cursor to the next tuple CLOSE CURSOR indicates that the processing of query results has been completed

1/2/ Embedded SQL in C Programming Examples with Cursor Prompt (“Enter the Department Name:”, dname); EXEC SQL Select Dnumber into :dnumber from DEPARTMENT where Dname = :dname; EXEC SQL DECLARE EMP CURSOR FOR Selec Ssn, Fname, Minit, Lname, Salary from EMPLOYEE where Dno = :dnumber FOR UPDATE OF Salary; EXEC SQL OPEN EMP; EXEC SQL FETCH from EMP into :ssn, :fname, :minit, :lname, :salary; while (SQLCODE == 0) { printf (“Employee name is:”, Fname, Minit, Lname); prompt (“Enter the raise amount:”, raise); EXEC SQL update EMPLOYEE set Salary = Salary + :raise where CURRENT OF EMP; EXEC SQL FETCH from EMP into :ssn, :fname, :minit, :lname, :salary; } EXEC SQL CLOSE EMP;

1/2/ Lecture Summary SQL is a high level relational database language. It is much user friendly than other database languages, and becomes the most popular database language since 90’s. Nevertheless, it is not an end user language such as Natural language, and is subject to be changed by individual relational database vendors and academic committee.

1/2/ Review Question What are the difference between Query and Nested Query in SQL with respect to performance and why? How does Entity Integrity affect an Insert operation of SQL? How does Referential Integrity affect Insert and Update operations of SQL? What is the condition for using UNION, INTERSECT and EXCEPT clauses in SQL?

1/2/ Tutorial Question Given the following relations, write SQL statements to answer the questions below: Customer(Customer_id, Customer_name, Customer_Address) Order(Order_id, *Customer_id, Date, Cost) Payment(Payment_id, *Customer_id, Date, Amount) (a) List out all the customer names who paid more than $300 on the 15th March (i)without using sub-query(30%) (ii)using sub-query(30%) (b) Remove a customer with customer_id ######## from the customer list where ######## is unique student id in 8 digits (40%)

1/2/ Reading Assignment Chapter 8 SQL-99: Schema Definition, Constraints, Queries, and Views “Fundamentals of Database Systems” by Elmasri & Navathe fifth edition, Pearson, 2007.