SQL Winter 2006Ron McFadyen 92.39021 Outline: SQL DDL - creating schemas - modifying schemas DML - select-from-where clause - group by, having, order by.

Slides:



Advertisements
Similar presentations
Fundamentals of Database Systems Fourth Edition El Masri & Navathe
Advertisements

SQL DESIGN AND IMPLEMENTATION CONTENT SOURCES: ELAMSARI AND NAVATHE, FUNDAMENTALS OF DATABASE MANAGEMENT SYSTEMSELAMSARI AND NAVATHE, FUNDAMENTALS OF.
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
Basic Queries. 2 Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the.
Database technology Lecture 2: Relational databases and SQL
Data Definition Languages Atif Farid Mohammad UNCC.
FEN More about SELECT, Nested selects GROUP BY, HAVING, ORDER BY Other joins Aggregate functions Views More about SQL.
Database Design -- Basic SQL
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
1 CSE 480: Database Systems Lecture 10: SQL - DML Reference: Read Chapter 4 of the textbook.
SQL Sept. 2014Yangjun Chen ACS Outline: SQL DDL - creating schemas - modifying schemas DML - select-from-where clause - group by, having, order by.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
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)
View Sen Zhang. Views are very common in business systems users view of data is simplified a form of security - user sees only the data he/she needs to.
Database Systems More SQL Database Design -- More SQL1.
SQL Jan. 2012Yangjun Chen ACS Outline: SQL Chapter 8 – 3rd ed. (Chap. 8 – 4 th, 5 th ed.; Chap. 4, 5, 6 th ed.) DDL - creating schemas - modifying.
Database: Review Sept. 2009Yangjun Chen ACS Database Introduction system architecture, Basic concepts, ER-model, Data modeling, B+-tree Hashing Relational.
SQL The relational DB Standard CS-450 Dr. Ali Obaidi.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1 CREATE/DROP/ALTER TABLE Data types : char, varchar, decimal, date CREATE TABLE DEPARTMENT.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
SQL Chapters 4, 5 (ed. 7 Chaps. 6,7). SQL or SEQUEL (Structured English Query Language) Based on relational algebra First called ‘Square’ Developed in.
SQL: Schema Definition, Constraints, & Queries and Views.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Lecture # 11 July 12,2012 More SQL: Complex Queries, Triggers,
Relational Algebra - Chapter (7th ed )
Onsdag The concepts in a relation data model SQL DDL DML.
CS 380 Introduction to Database Systems (Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Announcements Written Homework 1 due Friday –If you have fourth edition make sure you do the right problems Program 3 out today, due next Friday Nov 10.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
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.
CSCI DBMS Environment1 The Database System Environment Dr. Awad Khalil Computer Science Department AUC.
莊裕澤資料庫基本概念 1 Yuh-Jzer Joung 莊 裕 澤 Dept. of Information Management National Taiwan University February, 2002 資料庫管理與資訊科技.
NOEA/IT - FEN: Databases/SQL1 SQL – part 1 SQL: DDL and DML.
DatabaseDatabase cs453 Lab5 1 Ins.Ebtesam AL-Etowi.
SQL Chapter 8. SQL or SEQUEL - (Structured English Query Language) Based on relational algebra Developed in 1970's released in early 1980's Standardized.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
Prince Sultan University Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Announcements Written Homework 1 due Nov 2 –See course web page –Exercises 5.12, 5.15, 6.17, 6.20, 6.22 (a,c,f only). Today –continue with SQL (chapter.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Introduction to Database Systems
FEN Introduction to the database field:  SQL: Structured Query Language Seminar: Introduction to relational databases.
1 Database Systems Basic SQL. 2Outline  SQL Data Definition and Data Types  Specifying Constraints in SQL  Basic Retrieval Queries in SQL  INSERT,
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)
1 COMP 1100 Basic SQL David J. Stucki. Outline SQL Overview Retrievals Schema creation Table creation Constraints Inserts Updates 2.
SQL- Updates, Assertions and Views. Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations)
1 Chapter (8) SQL The Relational Database Standard Objectives Presenting the main features of SQL SQL is the Structured Query Language SQL commands SQL.
More SQL: Complex Queries,
The SQL Database Grammar
SQL: SchemaDefinition, Constraints, and Queries and Views
Chapter 4 Basic SQL.
6/22/2018.
CS580 Advanced Database Topics
Outline: SQL DDL - creating schemas - modifying schemas DML
Subject Name: DATA BASE MANAGEMENT SYSTEM Subject Code: 10cs54
376a. Database Design Dept. of Computer Science Vassar College
11/9/2018.
Joining Tables ضم الجداول وإستخراج مناظر views منها الهدف : 1- استخراج المعلومات من جدولين أو اكثر بالإستفادة من الرابط بينهما وبإستخدام SQL 2- شروط قواعد.
لغة قواعد البيانات STRUCTURED QUERY LANGUAGE SQL))
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL-99: Schema Definition, Constraints, and Queries and Views
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
OLTP Will be talking about On Line Transaction Processing OLTP for most of this course Operational databases As opposed to OLAP On Line Analytical Processing.
Presentation transcript:

SQL Winter 2006Ron McFadyen Outline: SQL DDL - creating schemas - modifying schemas DML - select-from-where clause - group by, having, order by - update - view

SQL Winter 2006Ron McFadyen Structured Query Language declarative ( non-procedural) DDL for data definition DML for query, update, view facility for security, integrity constraints, transactions, embedding into other 3GLs such as Cobol, C, … SQL89, SQL92, SQL99 Also referred to as SQL2 Also referred to as SQL3

SQL Winter 2006Ron McFadyen DDL - creating schemas Create schema schemaname authorization user; Create table tablename … constraints: primary keys foreign keys on delete set null|cascade|set default on update set null|cascade|set default on insert set null|cascade|set default uniqueness for secondary keys Create domain domainname …

SQL Winter 2006Ron McFadyen DDL - Examples: Create schema: Create schema COMPANY authorization JSMITH; Create table: Create table EMPLOYEE (FNAMEVARCHAR(15)NOT NULL, MINITCHAR, LNAMEVARCHAR(15)NOT NULL, SSNCHAR(9)NOT NULL, BDATEDATE, ADDRESSVARCHAR(30), SEXCHAR, SALARYDECIMAL(10, 2), SUPERSSNCHAR(9), DNOINTNOT NULL, PRIMARY KEY(SSN), FOREIGN KEY(SUPERSSN) REFERENCES EMPLOYEE(SSN), FOREIGN KEY(DNO) REFERENCES DEPARTMENT(DNUMBER)); Use (Books Online) help to see the Create Schema statement in MS SQL Server

SQL Winter 2006Ron McFadyen DDL - Examples: Specifying constraints: Create table EMPLOYEE (…, DNOINTNOT NULL DEFAULT 1, CONSTRAINT EMPPK PRIMARY KEY(SSN), CONSTRAINT EMPSUPERFK FOREIGN KEY(SUPERSSN) REFERENCES EMPLOYEE(SSN) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT EMPDEPTFK FOREIGN KEY(DNO) REFERENCES DEPARTMENT(DNUMBER) ON DELETE SET DEFAULT ON UPDATE CASCADE); Create domain: CREATE DOMAIN SSN_TYPE AS CHAR(9); Use help to see the Create Table statement in MS SQL Server

SQL Winter 2006Ron McFadyen DDL - modifying schemas drop schema schemaname cascade|restrict drop table tablename cascade|restrict alter table tablename add|drop attributename cascade|restrict drop constraint... Right-click on a table in MS SQL Server  select All Tasks  select Generate Script … preview

SQL Winter 2006Ron McFadyen DDL - Examples: drop schema DROP SCHEMA CAMPANY CASCADE; DROP SCHEMA CAMPANY RESTRICT; drop table DROP TABLE DEPENDENT CASCADE; DROP TABLE DEPENDENT RESTRICT; alter table ALTER TABLE COMPANY.EMPLOYEE ADD JOB VARCHAR(12); ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS CASCADE;

SQL Winter 2006Ron McFadyen DDL - Examples: alter table (continue) ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN DROP DEFAULT; ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN SET DEFAULT “ ”; drop constraints ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK CASCADE;

SQL Winter 2006Ron McFadyen DML - Queries (the Select statement) select attribute list from table list where condition group by expression having expression order by expression ; Select salary from employee; Select fname, salary from employee where salary > 30000; Use MS SQL Server … right- click on a table  select Open Table  select Query … Notice the 4 panes for working on a query

SQL Winter 2006Ron McFadyen Select salary from employee;Salary Select fname, salary from employee where salary > 30000; FnameSalary Franklin40000 Jennifer43000 Ramesh38000 James55000 Duplicates are possible!

SQL Winter 2006Ron McFadyen Select distinct salary from employee;Salary Select average(salary) from employee;Average(Salary) Select average(distinct salary) from employee; Average(distinct Salary) Select Distinct suppresses duplicates; Select All does not - select all is the default

SQL Winter 2006Ron McFadyen Select d.dnumber, dname, dlocation from department d, dept_locations l where d.dnumber=l.dnumber; d.dnumber dname location 1 Headquarters Houston 4 Administration Stafford 5 Research Bellaire 5 Research Sugarland 5 Research Houston aliasing basic join condition 3 departments, 5 locations, 5 rows in the result

SQL Winter 2006Ron McFadyen Select s.ssn, s.lname, r.lname from employee s, employee r where s.ssn=r.superssn; s.ssns.lnamer.lname Wong Smith BorgWong WallaceZelaya BorgWallace Wong Nanayan Wong English WallaceJabbar Recursive or self join - same relation - aliases required Try this on the Employees table in Northwind using the ReportsTo attribute.

SQL Winter 2006Ron McFadyen Ordering the result set: Select s.ssn, s.lname, r.lname from employee s, employee r where s.ssn=r.superssn order by s.lname, r.lname; s.ssns.lnamer.lname BorgWallace BorgWong WallaceJabbar WallaceZelaya Wong English Wong Nanayan Wong Smith

SQL Winter 2006Ron McFadyen Summarizing underlying rows: Select s.ssn, s.lname, count(r.lname) from employee s, employee r where s.ssn=r.superssn group by s.ssn, s.lname; s.ssns.lnamer.lname Borg Wong Wallace2

SQL Winter 2006Ron McFadyen Eliminating Groups from the result: Select s.ssn, s.lname, count(r.lname) from employee s, employee r where s.ssn=r.superssn group by s.ssn, s.lname having count(r.lname) < 3; s.ssns.lnamecount(r.lname) Borg Wallace2

SQL Winter 2006Ron McFadyen Use of *: select * from dept_locations; select count(*) from dept_locations; select count(*) from dept_locations where dlocation=‘Houston’; dnumberdlocation 1Houston 4Stafford 5Bellaire 5Sugarland 5Houston Count(*) 5 Count(*) 2

SQL Winter 2006Ron McFadyen Use of Like and Between: select * from dept_locations where dlocation like ‘%o%’; dnumberdlocation 1Houston 4Stafford 5Houston Select fname, salary from employee where salary between and 50000; fnamesalary Franklin40000 Jennifer43000 Ramesh38000

SQL Winter 2006Ron McFadyen Subqueries: select ssn, fname from employee where ssn in (select essn from dependent); ssnfname Franklin Jennifer John select ssn, fname from employee where ssn = any (select essn from dependent); The above is a special case of a comparison operator followed by any/some: Other possibilities: > any >= any any

SQL Winter 2006Ron McFadyen Subqueries: ssnfnamesalary James55000 Select ssn, fname, salary from employee where salary > all (select salary from employee where dno=4); comparison operator can be followed by all: Note that the inner query needs only to be executed once Are there other ways to express this query?

SQL Winter 2006Ron McFadyen Correlated Subqueries: dnossnfname James Jennifer Franklin Select dno, ssn, fname from employee e where salary >= all (select salary from employee x where x.dno=e.dno); The inner and outer query are related. Conceptually, the subquery is executed once for each row of the outer query:

SQL Winter 2006Ron McFadyen Correlated Subqueries: dnossnfname James Jennifer Franklin Select dno, ssn, fname from employee e where salary = (select max(salary) from employee x where x.dno=e.dno); The inner and outer query are related. Conceptually, the subquery is executed once for each row of the outer query:

SQL Winter 2006Ron McFadyen Correlated Subquery example: Suppose we want to find out who is working on a project that is not located where their department is located. Note that the Employee table has the department number for an employee, and that Dept_locations has the locations for the department Note that the Project table has the location for the project Note that the Works_on relates employees to projects We’ll do this in two parts: a join that relates employees and projects (via works_on) a subquery that obtains the department locations for a given employee

SQL Winter 2006Ron McFadyen Correlated Subqueries: A 3-way join to bring related employee and project data together: SELECT employee.ssn, employee.fname, employee.lname, project.pnumber, project.plocation FROM employee, project, works_on WHERE employee.ssn = works_on.essn and project.pnumber = works_on.pno A 3-way join

SQL Winter 2006Ron McFadyen Correlated Subqueries: Now we incorporate a correlated subquery to restrict the result to those employees working on a project that is not where their department is located: SELECT employee.ssn, employee.fname, employee.lname, project.pnumber, project.plocation FROM employee, project, works_on WHERE employee.ssn = works_on.essn and project.pnumber = works_on.pno and plocation NOT IN (SELECT dlocation FROM dept_locations WHERE dnumber=employee.dno);

SQL Winter 2006Ron McFadyen Subqueries with Exists and Not Exists: Who has dependents? SELECT fname, lname FROM employee WHERE EXISTS (SELECT * FROM dependent where essn=ssn); Who does not have dependents? SELECT fname, lname FROM employee WHERE NOT EXISTS (SELECT * FROM dependent where essn=ssn);

SQL Winter 2006Ron McFadyen Subqueries with Exists and Not Exists: Who is working on every project? SELECT e.ssn, e.fname, e.lname FROM employee AS e WHERE NOT EXISTS (SELECT * FROM project AS p WHERE NOT EXISTS (SELECT * FROM works_on AS w WHERE w.essn=e.ssn AND w.pno=p.pnumber)); There is no project that the employee does not work on. This is not a simple query!

SQL Winter 2006Ron McFadyen Renaming the result set: SELECT fname AS FirstName, lname AS Surname FROM employee;

SQL Winter 2006Ron McFadyen Aggregate functions: AVG, SUM, COUNT, MAX, MIN Select count(*) from employee Select count(superssn) from employee Select count(distinct superssn) from employee Number of employees - count number of rows Number of employees who have supervisors - count ignores nulls Number of employees who are supervisors - doesn’t work in Access!

SQL Winter 2006Ron McFadyen Nulls: Some fields are designed so that a value is not required In figure 8.1(a) on page 247, some fields have NOT NULL specified - these must be assigned a value on INSERT. Others do not have this specification - the default is Null, unless you override that Specific constructs are used to test for nulls: select fname, lname from employee where superssn is null; Who does not have a supervisor?

SQL Winter 2006Ron McFadyen Special joins: Outer join this example is a right outer join - lists every department regardless of whether or not it has a manager SELECT department.dnumber, department.dname, employee.fname, employee.lname FROM employee RIGHT OUTER JOIN department ON employee.ssn = department.mgrssn; What joins does MS SQL Server allow? Right-click on a join condition … select Properties

SQL Winter 2006Ron McFadyen Special joins: Inner join this example is an inner join - lists employees and their departments SELECT department.dnumber, department.dname, employee.fname, employee.lname FROM department INNER JOIN employee ON department.dnumber = employee.dno;

SQL Winter 2006Ron McFadyen Special joins: Inner join with a Where clause this example is an inner join - lists employees and their departments, but only for the Research department SELECT department.dnumber, department.dname, employee.fname, employee.lname FROM department INNER JOIN employee ON department.dnumber = employee.dno WHERE dname = 'Research';

SQL Winter 2006Ron McFadyen Update statements: Insert Update Delete INSERT INTO employee ( fname, lname, ssn, dno ) VALUES ( "Joe", "Smith", 909, 1); UPDATE employee SET salary = WHERE ssn=909; DELETE FROM employee WHERE ssn=909; Note that Access changes the above to read: INSERT INTO employee ( fname, lname, ssn, dno ) SELECT "Joe", "Smith", 909, 1; In MS SQL Server, notice the QueryType menu item … similar to MS Access

SQL Winter 2006Ron McFadyen Views: Use a Create View command essentially a select specifying the data that makes up the view Create View Enames as select lname, fname from employee CREATE VIEWEnames (lname, fname) AS SELECTLNAME, FNAME FROMEMPLOYEE In MS SQL Server, notice there are Views as well as tables … try creating a view … right click on Views

SQL Winter 2006Ron McFadyen CREATE VIEWDEPT_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) AS SELECTDNAME, COUNT(*), SUM(SALARY) FROMDEPARTMENT, EMPLOYEE WHEREDNUMBER = DNO GROUP BYDNAME;

SQL Winter 2006Ron McFadyen Views are very common in business systems users view of data is simplified a form of security - user sees only the data he/she needs to if the primary key is preserved, updates to a base table through a view is possible