Structured Query Language Review ISYS 650. Language Overview Three major components: –Data definition language, DDL Create, Drop and Alter Tables or Views.

Slides:



Advertisements
Similar presentations
BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands.
Advertisements

SQL Sub (or Nested ) Query. Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student.
Database Systems: Design, Implementation, and Management Tenth Edition
Introduction to Structured Query Language (SQL)
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
SQLPlus Commands. Oracle Account Server: libra.sfsu.edu Telnet: libra.sfsu.edu How to use Oracle: –
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Basic SQL Select Commands. Basic Relational Query Operations Selection Projection Natural Join Sorting Aggregation: Max, Min, Sum, Count, Avg –Total –Sub.
Querying Database ISYS 363. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy.
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.
Querying Database. Basic Query Language Operations Selection Projection Join Aggregates: Max, Min, Sum, Avg, Count –Totals and SubTotals –GroupBy Calculated.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Relational Operators, SQL, and Access Query ISYS 562.
Introduction to SQL J.-S. Chou Assistant Professor.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
Oracle Database Administration Lecture 2 SQL language.
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.
SQL (DDL & DML Commands)
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Advanced SQL for Decision Support ISYS 650. Set Operators Union Intersect Difference Cartesian product.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Structured Query Language. Group Functions What are group functions ? Group Functions Group functions operate on sets of rows to give one result per group.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Introduction to Access ISYS 363. Creating a New Database MS Office button/New –Blank database –New database name and location.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
DBSQL 5-1 Copyright © Genetic Computer School 2009 Chapter 5 Structured Query Language.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Relational Query Operators (Algebra). Relational Query Operators Set operations: Union, intersection, difference, Cartesian product Relational operations:
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
SQL advanced select using Oracle 1. 2 Select Simple –data from a single table Advanced –data from more tables join sub-queries.
Querying Database ISYS 363.
Introduction to Query Language and SQL. Basic Query Language Operators Selection Projection Join Aggregates –Sum, Count, Max, Min, Avg SubTotal Calculated.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Introduction to Access BUS 782. Creating a New Database MS Office button/New –Blank database –New database name and location.
Introduction to Access ISYS 363. Access Objects Tables –Open –Design –New –Wizard Queries Forms Reports Pages.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
SQL Miscellaneous Topics. Views A database view is: – a virtual or logical table based on a query. – a stored query. CREATE VIEW viewname AS query; –CREATE.
Introduction to Access ISYS 363. Access Objects Tables –Open a table: Double click the table name –Home/View: Datasheet view Design view Queries Forms.
Introduction to Database SEM I, AY Department of Information Technology Salalah College of Technology Chapter No.3 SQL.
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.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
SQL SQL Ayshah I. Almugahwi Maryam J. Alkhalifa
CHAPTER 7 DATABASE ACCESS THROUGH WEB
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Querying Database ISYS 363.
Index Note: A bolded number or letter refers to an entire lesson or appendix. A Adding Data Through a View ADD_MONTHS Function 03-22, 03-23,
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
Structured Query Language – The Basics
Presentation transcript:

Structured Query Language Review ISYS 650

Language Overview Three major components: –Data definition language, DDL Create, Drop and Alter Tables or Views –Data manipulation language, DML Updating database: –Insert, Delete, Update Query database: –Select –Data control language (DCL) Help DBA control the database: –Grant/revoke privileges to access the database, creating procedures, etc.

DDL Table structure: –Field name –Field data type –Primary key –Integrity constraints: Null Domain constraint Referential integrity Etc.

CREATE TABLE CREATE TABLE tableName(fields and data type separated by commas); Ex. –CREATE TABLE employee( eid CHAR(5), ename VARCHAR(40), sex CHAR, salary NUMERIC(9,2), hire_Date DATE);

Integrity Enhancement Feature Required data: NOT NULL –eid CHAR(5) NOT NULL, Default value:DEFAULT sex CHAR DEFAULT ‘M’, Field domain: CHECK(condition) –salary NUMERIC(9,2) CHECK (salary >= 100 AND salary <=10000), –sex CHAR DEFAULT ‘M’ CHECK (sex in (‘M’,’F”)), PRIMARY KEY –PRIMARY KEY(sid) –PRIMARY KEY(sid, cid) Unique – allow null value, the PRIMARY KEY constraint does not allow null. –ESSN CHAR(9) UNIQUE

Example –CREATE TABLE employee( eid CHAR(5) PRIMARY KEY, ename VARCHAR(40), sex CHAR DEFAULT ‘M’ CHECK (sex in (‘M’,’F’)), salary NUMERIC(9,2), hire_Date DATE);

Creating Table Through SubQuery CREATE TABLE tableName AS (Select query) Ex. –CREATE TABLE newEmp –AS (SELECT empid, ename,salary FROM emp);

SQL Insert Command INSERT INTO tableName VALUES (field values separated by commas); INSERT INTO tableName (Column names separated by commas)VALUES (field values separated by commas); Ex 1. Customer table with CID, CNAME, CITY, RATING. a. INSERT INTO CUSTOMER VALUES (‘C1’, ‘SMITH’, ‘SF’, ‘A’); b. INSERT INTO CUSTOMER (CID, CNAME,RATING) VALUES (‘C1’, ‘SMITH’, ‘A’);

Record with Date Field Oracle date format: –‘dd-mmm-yyyy’ Example: insert into orders values('O7','c2','s1','10-oct-2007');

Inserting records from an existing table (Append) INSERT INTO stu2 (select * from student);

SQL Delete Command DELETE FROM tableName [WHERE criteria]; Ex 1. Delete a record from the Customer table. DELETE FROM CUSTOMER WHERE CID = ‘C1’;

SQL Update Command UPDATE tableName SET field = new value [WHERE criteria]; Ex 1. UPDATE CUSTOMER SET RATING = ‘A’ WHERE CID=‘C1’; Ex 2. UPDATE CUSTOMER SET CITY = ‘SF’, RATING = ‘A’ WHERE CID=‘C1’;

Dealing with Null Null is a key word. We can use Null in the INSERT, UPDATE, and DELETE command. Use IS NULL (or IS NOT NULL) in a criteria. Examples: –INSERT INTO emp VALUES (‘e95’,’June’,’f’,NULL,5000); –UPDATE emp SET salary=null where empid=‘e99’; –SELECT * FROM emp WHERE salary IS NULL; –SELECT * FROM emp WHERE salary= NULL (not working);

Maintaining Referential Integrity FOREIGN KEY (field) REFREENCES parentable DROP TABLE parent; CREATE TABLE parent ( pid char(3) not null, pname varchar(20), PRIMARY KEY (pid) ); drop table child; CREATE TABLE child ( cid char(3) not null, cname varchar(20), pid char(3), PRIMARY KEY (cid), FOREIGN KEY (pid) REFERENCES parent ON DELETE SET NULL );

ON DELETE ON DELETE SET NULL ON DELETE CASCADE

Basic SQL Select Commands

Basic Relational Query Operations Selection Projection Natural Join Sorting Aggregation: Max, Min, Sum, Count, Avg –Total –Sub totals: Group By Calculated field Sub Queries

Examples University database: –Student: SID, Sname, Sex, Major, GPA, FID –Account: SID, Balance –Faculty: FID, Fname, Phone –Course: CID, Cname, Credits, FID –Registration: SID, CID Download the batch file OracleUniv.SQL to create the database.

Selection Selection operation works on a single relation and defines a relation that contains records that satisfy the criteria.

Selection Syntax SELECT * FROM tableName WHERE criteria; Criteria: –=, <>,, = –(), NOT, AND, OR –BETWEEN WHERE salary BETWEEN 1000 AND 10000; –LIKE, NOT LIKE: % WHERE ename LIKE ‘C%’ –Cannot say: WHERE ename = ‘C%’ –IN, NOT IN WHERE eid IN (‘e1’,’e3’) –IS NULL WHERE rating IS NULL –Arithmetic expression in criteria: WHERE salary*0.1 < 500

ROWNUM Field ROWNUM field is a pseudocolumn that applies to every table even though it is not displayed through a SELECT * command. SELECT ROWNUM, empid FROM emp; SELECT * FROM emp WHERE ROWNUM < = 3;

Projection Projection operation works on a single relation and defines a vertical subset of the relation, extracting the values of specified attributes.

Projection Syntax SELECT fields FROM tableName; –Ex: SELECT empID, ename FROM Employee; Alias: Ex: SELECT eid AS empID, ename AS empName FROM emp; Projection and Selection: –SELECT fields FROM tableName WHERE criteria;

Duplications due to Projection Registration file: SID CID s1 bics263 s1 acct101 s2 bics363 s2 bics464 s2 fin350 s3 bics263 SELECT sid FROM Registration; Note: What is the meaning of this result?

DISTINCT/UNIQUE SELECT DISTINCT fields FROM tableName WHERE criteria; –Ex. SELECT DISTINCT sid FROM Registration; UNIQUE –SELECT UNIQUET fields FROM tableName WHERE criteria; –Ex. SELECT UNIQUE sid FROM Registration;

Calculated Fields SELECT empid,ename,salary*0.1 AS tax FROM emp;

Oracle Functions Text functions: –UPPER, LOWER, INITCAP Ex. SELECT INITCAP(Fname) FROM Faculty; –SUBSTR(text,starting position, # of chars) –LPAD(text,length of text,padding symbol) LPAD(salary,10,’*”) –CONCAT(text1,text2) We can also use concatenation operator, || Date functions: –SYSDATE,NEXT_DAY Ex. NEXT_DAY(SYSDATE,’MONDAY’) –MONTHS_BETWEEN(date1,date2) Ex. SELECT Ename, MONTHS_BETWEEN(SYSDATE, Hire_Date) FROM Employee; –ADD_MONTHS(date,# of months added)

Using the SQL CASE Function SELECT sid, sname, CASE WHEN gpa < 2.0 THEN 'Poor' WHEN gpa < 3.0 THEN 'Good' ELSE 'Excellent' END AS GPAGroup FROM student;

Natural Join The two relations must have common attributes. Combines two relations to form a new relation where records of the two relations are combined if the common attributes have the same value. One occurrence of each common attribute is eliminated.

Natural Join Syntax SELECT * FROM table1 NATURAL JOIN table2; Example: –SELECT * FROM student NATURAL JOIN faculty; Note: What if the FID in the student table is named AdvisorID?

Standard Join Syntax SELECT * FROM table1, table2 WHERE table1.JoinAttribute = table2.JoinAttribute; –SELECT * FROM student, faculty –WHERE student.fid = faculty.fid; Table name alias: –SELECT * FROM student s, faculty f WHERE s.fid = f.fid; On: –SELECT * FROM student s JOIN faculty f ON s.fid=f.fid; Difference between natural join and standard join?

Self Join Recursive relationship: –Employee supervise Employee Ex: EmpFile: empID, empName, superID Find employees’ supervisor name: –SELECT e1.empid, e1.empname,e2.empname as sueprname –FROM empfile e1, empfile e2 –WHERE e1.superid=e2.empid;

Sorting ORDER BY fieldName [DESC] –SELECT * FROM student ORDER BY sname; –SELECT * FROM student ORDER BY sname DESC; More than one field: –SELECT * FROM student ORDER BY major, sname; Note 1: Don’t name a table “ORDER” because ORDER is a SQL keyword. Note 2: If there is a WHERE clause, then the ORDER BY clause should be placed after the WHERE clause.

Aggregates SELECT AVG(fieldName) FROM tableName; –COUNT(fieldName), COUNT(*) –COUNT(DISTINCT fieldName) –MAX(fieldName) –MIN(fieldName) –SUM(fieldName) More than one aggregate: SELECT AVG(fieldName), MAX(fieldName), MIN(fieldName) FROM tableName; With alias: –SELECT AVG(gpa) AS avggpa, COUNT(sid) AS scount FROM student;

GROUP BY GROUP By one field: –SELECT groupingFields, function(fieldname) FROM tablename GROUP BY groupingFields; –SELECT major, count(sid) FROM student GROUP BY major; GROUP BY more than one field: –SELECT sex, major, count(sid) FROM student GROUP BY sex, major; Compute more than one subtotals: –SELECT major, count(sid), avg(gpa) FROM student –GROUP BY major Note 1: All grouping fields in the SELECT clause must be included in the GROUP BY clause). Note 2:WHERE clause must come before the GROUP BY: –SELECT major, count(sid) FROM student WHERE GPA > 3.0 GROUP BY major;

Compute Subtotals from a Join Compute the number of courses taken by each student: –SELECT sid, sname, COUNT(cid) FROM student NATURAL JOIN registration GROUP BY sid, sname; Compute the number of students advised by each faculty advisor: –SELECT fid, fname, COUNT(sid) –FROM faculty NATURAL JOIN student –GROUP BY fid, fname;

Oracle’s Natural Join May Produce Incorrect Results select sid,sname,sum(units) from student natural join registration natural join course group by sid,sname; select sid,sname,sum(units) from (student natural join (registration natural join course)) group by sid,sname;

Adding a Criteria for the Sub Totals with HAVING Find majors that have at least 5 students: –SELECT major, count(sid) FROM student –GROUP BY major –HAVING count(sid) > 5; Sometime the aggregates are not required to display: –SELECT major FROM student –GROUP BY major –HAVING count(sid) > 5;

Nesting Aggregates SELECT MAX(AVG(gpa)) FROM student GROUP BY major;

University Database Questions Q1: Display College of Business students’ ID and name. Q2: Display students’ ID and name who owe university more than $2000. Q3: Display faculty’s name and phone if the student’s GPA is lower than 2.0. Q4: Display faculty’s name and phone if the faculty advises at least 2 student. Q5: Display students’ ID and name who are taking at least 2 course. Q6: Display students’ ID and name who are taking 464 and GPA < 2.0. Q7: Display CID, Cname and the number of students in each course. Q8: Display SID, Sname, TotalUnits

SQL Sub (or Nested ) Query

Examples Q: Find students whose GPA is below the average. –The criteria itself requires a SQL statement. –SELECT * FROM student WHERE gpa < (SELECT AVG(gpa) FROM student); Q: Find employees with higher than average salary.

Sub Query with IN SELECT sid, sname FROM student WHERE sid in (‘S1’, ‘S2’); Use a subquery to retrieve keys that meet criteria. Example: Display students’ ID, name who owe university more than $2000. (Note: not showing balance) SELECT sid,sname FROM student WHERE SID IN (SELECT SID FROM account WHERE balance > 2000); Example: Display students’ ID, name and Balance who owe university more than $2000.

Sub Query with IN, NOT IN Use a subquery to retrieve keys that meet criteria. Q: Display faculty’s ID and name if the faculty advises at least one student. –SELECT fid, fname FROM faculty –WHERE fid IN (SELECT DISTINCT fid FROM student); Q: Display faculty’s name and name if the faculty does not advise any student. –SELECT fid, fname FROM faculty –WHERE fid NOT IN (SELECT DISTINCT fid FROM student);

Subquery in the SELECT List SELECT eid,ename,salary,(select AVG(salary) from employee) as AvgSal FROM employee; SELECT eid,ename,salary-(select AVG(salary) from employee) as DeviateFromMean FROM employee;

Multiple Levels Subquery Find students who are taking one-unit courses and display their ID and name. Join: –Select sid, sname, cid from student natural join registration natural join course where units=1; Without Join: –Select sid, sname From Student –Where sid in (select sid from registration where cid in – (select cid from course where units=1));

Correlated SubQueries A correlated subquery references values of the main query. In a correlated subquery, the main query provides values which are used by subquery’s WHERE clause. The subquery is executed repeatedly, once for each row that might be selected by the main query.

Passing Values from Main Query to SubQuery Find students taking more than 2 courses: select * from student s where (select count(cid) from registration where sid=s.sid)>2 ;

EXISTS, NOT EXISTS Test whether a subquery returns any rows. It returns True/False

Find faculty who advise at least one student. 1. Subquery: –SELECT fid,fname FROM faculty –WHERE fid in (SELECT DISTINCT fid FROM student); 2. Correlated query: –SELECT fid,fname FROM faculty –WHERE EXISTS (SELECT * FROM student –WHERE fid = faculty.fid);

SELECT List Containing Nested Query SELECT sid, sname, (SELECT COUNT(cid) FROM registration WHERE sid=student.sid) AS courses FROM student;