COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

Similar documents
Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

ECE 650 Systems Programming & Engineering. Spring 2018

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries

Database design process

SQL. Copyright 2013 Ramez Elmasri and Shamkant B. Navathe

Chapter 8. Joined Relations. Joined Relations. SQL-99: Schema Definition, Basic Constraints, and Queries

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Slides by: Ms. Shree Jaswal

SQL STRUCTURED QUERY LANGUAGE

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Database Technology. Topic 3: SQL. Olaf Hartig.

Overview Relational data model

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL-99: Schema Definition, Basic Constraints, and Queries. Create, drop, alter Features Added in SQL2 and SQL-99

COSC344 Database Theory and Applications. σ a= c (P) S. Lecture 4 Relational algebra. π A, P X Q. COSC344 Lecture 4 1

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

CSIE30600 Database Systems Basic SQL 2. Outline

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig.

SQL: Advanced Queries, Assertions, Triggers, and Views. Copyright 2012 Ramez Elmasri and Shamkant B. Navathe

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

COSC Assignment 2

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Advanced Databases. Winter Term 2012/13. Prof. Dr. Dietmar Seipel University of Würzburg. Advanced Databases Winter Term 2012/13

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Data Definition Language (DDL)

Simple SQL Queries (contd.)

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

A taxonomy of SQL queries Learning Plan

ECE 650 Systems Programming & Engineering. Spring 2018

SQL Introduction. CS 377: Database Systems

CS 338 Basic SQL Part II

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

L130 - DATABASE MANAGEMENT SYSTEMS LAB CYCLE-1 1) Create a table STUDENT with appropriate data types and perform the following queries.

Structured Query Language (SQL)

Basic SQL II. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

CIS611 Lab Assignment 1 SS Chung

Ref1 for STUDENT RECORD DB: Ref2 for COMPANY DB:

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

Outline. Note 1. CSIE30600 Database Systems More SQL 2

Part 1 on Table Function

CSC 742 Database Management Systems

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

SQL- Updates, Asser0ons and Views

Session Active Databases (2+3 of 3)

More SQL: Complex Queries, Triggers, Views, and Schema Modification

DATABASE CONCEPTS. Dr. Awad Khalil Computer Science & Engineering Department AUC

CS 348 Introduction to Database Management Assignment 2

Some different database system architectures. (a) Shared nothing architecture.

More SQL: Complex Queries, Triggers, Views, and Schema Modification

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

DBMS LAB SESSION PAVANKUMAR MP

Announcement5 SQL5. Create%and%drop%table5. Basic%SFW%query5. Reading%a%table5. TDDD37%% Database%technology% SQL5

CS5300 Database Systems

COSC344 Database Theory and Applications. COSC344 Lecture 15 1

Query 2: Pnumber Dnum Lname Address Bdate 10 4 Wallace 291 Berry, Bellaire, TX Wallace 291 Berry, Bellaire, TX

CSEN 501 CSEN501 - Databases I

Data Manipulation Language (DML)

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Chapter 8: The Relational Algebra and The Relational Calculus

Basic SQL. Basic SQL. Basic SQL

Chapter 8: Relational Algebra

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

More SQL: Complex Queries, Triggers, Views, and Schema Modification

Guides for Installing MS SQL Server and Creating Your First Database. Please see more guidelines on installing procedure on the class webpage

Practical Project Report

Relational Algebra 1

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

Chapter 19 Query Optimization

Relational Calculus: 1

Chapter 6: RELATIONAL DATA MODEL AND RELATIONAL ALGEBRA

Relational Model. CS 377: Database Systems

Insertions, Deletions, and Updates

Chapter 3: Introduction to SQL

Algorithms for Query Processing and Optimization. 0. Introduction to Query Processing (1)

6.5 Integrity Contraints: SQL Statements:

Chapter 3. Algorithms for Query Processing and Optimization

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra

CS 377 Database Systems

UNIT-V SQL Explain insert, delete and update statements in SQL with example.

The Relational Algebra

Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 6 Outline. Unary Relational Operations: SELECT and

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Class Information. Textbooks. Grading. Final Project. Grading. CS 440: Database Management Systems. Instructor:

Relational Database Systems Part 01. Karine Reis Ferreira

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

The SQL data-definition language (DDL) allows defining :

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

Key Points. COSC 122 Computer Fluency. Databases. What is a database? Databases in the Real-World DBMS. Database System Approach

COSC344 Database Theory and Applications. Lecture 11 Triggers

STRUCTURED QUERY LANGUAGE (SQL)

Lab # 4. Data Definition Language (DDL)

Summary on Chapter 1. Databases and Database Users. 1. Introduction 1.1 Types of Database Applications. 1.2 Basic Definitions

Chapter 3: Introduction to SQL

Principles of Data Management

Relational Model History. COSC 416 NoSQL Databases. Relational Model (Review) Relation Example. Relational Model Definitions. Relational Integrity

The Relational Algebra and Calculus. Copyright 2013 Ramez Elmasri and Shamkant B. Navathe

Relational Algebra Part I. CS 377: Database Systems

Transcription:

COSC344 Database Theory and Applications Lecture 6 SQL Data Manipulation Language (1) COSC344 Lecture 56 1

Overview Last Lecture SQL - DDL This Lecture SQL - DML INSERT DELETE (simple) UPDATE (simple) Basic SELECT-FROM-WHERE Ambiguous attribute names & Aliases WHERE clause Removing duplicates Aggregate functions GROUP BY HAVING ORDER BY Source: Chapter 6.3 6.4 and Oracle documentation Next Lecture SQL - DML 2 (complex retrieval queries) Source: Chapter 7.1 and Oracle documentation COSC344 Lecture 56 2

INSERT Insert a tuple with values for all attributes The values should be listed in the same order as specified in the CREATE TABLE command INSERT INTO employee VALUES ( John, B, Smith, 123456789, TO_DATE( 09-01-1965, dd-mm-yyyy ), 731 Fondren, Houston,TX, M, 30000, 333445555, 5); Insert a tuple with values for a specified list of attributes Must include all attributes with NOT NULL specification and no default value INSERT INTO employee (Fname, Lname, Dno, Ssn) VALUES ( John, Smith, 5, 123456789 ); Must satisfy all integrity constraints specified in CREATE TABLE statement COSC344 Lecture 56 3

CREATE TABLE employee (fname VARCHAR2(15) NOT NULL, minit CHAR, lname VARCHAR2(15) NOT NULL, ssn CHAR(9) PRIMARY KEY, bdate DATE, address VARCHAR2(30), sex CHAR, salary NUMBER(6), superssn CHAR(9) CONSTRAINT superssn_cnst REFERENCES employee(ssn) DISABLE, dno INT NOT NULL DEFAULT 1 CONSTRAINT dno_cnst REFERENCES department(dnumber) DISABLE); ALTER TABLE employee ENABLE CONSTRAINT dno_cnst; ALTER TABLE employee ENABLE CONSTRAINT superssn_cnst; INSERT INTO employee VALUES * ERROR at line 1: ORA-02291: integrity constraint (HAIBO.SUPERSSN_CNST) violated - parent key not found COSC344 2012 Lecture 6 4

DELETE and UPDATE DELETE command removes tuples from a relation DELETE FROM employee WHERE lname = 'Brown'; DELETE FROM employee; UPDATE command modifies attribute values of one or more tuple in a relation UPDATE project SET plocation='bellaire, dnum=5 WHERE pnumber=10; UPDATE employee SET salary = salary * 1.1 WHERE Dno=5; COSC344 Lecture 56 5

Referential Integrity Constraints (Revisit) FOREIGN KEY clause: specifies referencing integrity Can be defined by following the attribute directly dnum INT NOT NULL REFERENCES department(dnumber), Can be defined using the FOREIGN KEY clause FOREIGN KEY (dnum) REFERENCES department(dnumber), Specify actions to deal with integrity violations SET NULL, CASCADE, SET DEFAULT FOREIGN KEY (super_ssn) REFERENCES employee(ssn) ON DELETE SET NULL, Oracle does not support cascade update, which can be implemented in other ways. DELETE and UPDATE may propagate to tuples in other relations if referential triggered actions are specified on the referential integrity constraints. COSC344 Lecture 56 6

SELECT The basic statement for retrieving data The SELECT statement is not the same as the SELECT operation in relational algebra Basic form of SELECT SELECT <attribute list> FROM <table list> WHERE <condition>; A simple example: SELECT bdate, address FROM employee WHERE fname='john' AND minit='b' AND lname='smith'; What is the result? What is the corresponding relational algebra statement? COSC344 Lecture 56 7

SELECT With Join Example: Retrieve the name and address of all employees who work for the 'Research' department. What is the corresponding relational algebra statement? SQL statement SELECT fname, lname, address FROM employee, department WHERE dname='research' AND dnumber=dno; Ambiguous Attribute Names Example: Retrieve the name and sex for all employees and the name of their dependents Both employee and dependent have an attribute named Sex. COSC344 Lecture 56 8

Solution to Ambiguous Attribute Names Qualify the attribute name with the relation name SELECT Fname, Lname, employee.sex, dependent_name FROM employee, dependent WHERE ssn=essn; Define alias as alternatives for relation names SELECT Fname, Lname, e.sex, dependent_name FROM employee e, dependent WHERE ssn=essn; A special Example: Retrieve the employee s first name and last name and the first and last name of his/her supervisor SELECT e.fname, e.lname, s.fname, s.lname FROM employee e, employee s WHERE e.superssn=s.ssn; COSC344 Lecture 56 9

The WHERE Clause A missing WHERE clause indicates no condition on tuple selection SELECT ssn FROM employee; The WHERE clause specifies the Boolean condition which must be true for any retrieved tuple. The condition in the WHERE clause can be a complex expression Comparison operators: =, >,>=,<,<=,<> Logical operators: AND, OR, NOT Special operators IN BETWEEN LIKE IS NULL COSC344 Lecture 56 10

Special Operators IN and BETWEEN IN operator syntax <attr> IN (<list of values>) SELECT pname FROM project WHERE plocation IN ('Bellaire', 'Stafford'); SELECT pname FROM project WHERE NOT plocation IN ('Bellaire', 'Stafford'); BETWEEN operator syntax <attr> BETWEEN <value1> AND <value2> SELECT * FROM employee WHERE salary BETWEEN 25000 AND 38000; (salary>=25000) AND (salary <=38000) Inclusive COSC344 Lecture 56 11

Special Operators - LIKE Used for substring matches for CHAR or VARCHAR2 attributes LIKE syntax <attr> LIKE <match string> Underscore (_) matches a single character Percent (%) matches a sequence of any number of characters (including zero characters) If an underscore or % is needed as a literal character in the match string, use the escape character (\) before them. SELECT pname FROM project WHERE pname LIKE 'P%'; SELECT fname FROM employee WHERE fname LIKE J ; 4 underscores COSC344 Lecture 56 12

Special Operators - IS NULL When NULL is compared to any value, even another NULL, the result is not true or false, but unknown, and Unknown behaves like false IS NULL syntax <attr> IS [NOT] NULL SELECT fname FROM employee WHERE superssn IS NULL; NEVER use OR WHERE superssn = NULL WHERE superssn <> NULL COSC344 Lecture 56 13

Duplicates An important distinction between SQL and the formal relational model: SQL allows a table to have two or more tuples that are identical. An SQL table is not a set of tuples a multiset (or bag) of tuples SELECT can yield relations with duplicate tuples DISTINCT option to remove duplicates SELECT DISTINCT... SELECT DISTINCT dnum FROM project; COSC344 Lecture 56 14

What to Project Specify a list of attributes Using asterisk (*) to stand for all the attributes SELECT * FROM employee; Aggregate functions Take groups of values from a field and reduce them to a single value. Used like attribute names in the SELECT part SUM(<attr>) MIN(<attr>) MAX(<attr>) AVG(<attr>) COUNT(*) COUNT(DISTINCT <attr>) SELECT AVG(salary) FROM employee; Generally used with the GROUP BY clause COSC344 Lecture 56 15

GROUP BY Clause Allows one to define a subset of the values of a particular field and to apply an aggregate function to the subsets GROUP BY applies the aggregate function independently to each subset Can have multiple attributes in the GROUP BY clause SELECT pno, MAX(hours) FROM works_on GROUP BY pno; PNO MAX(HOURS) ---------- ---------- 1 32.5 30 30 2 20 20 15 3 40 10 35 COSC344 Lecture 56 16

HAVING Clause May follow a GROUP BY clause and is used to restrict the groups to satisfy certain conditions. SELECT pno, MAX(hours) FROM works_on GROUP BY pno HAVING MAX(hours) > 21; PNO MAX(HOURS) ---------- ---------- 1 32.5 30 30 3 40 10 35 What is the difference between HAVING and WHERE? COSC344 Lecture 56 17

ORDER BY Clause Orders the output according to the values in one or more selected columns The default order is ascending ASC DESC SELECT * FROM works_on ORDER BY pno, hours; SELECT * FROM works_on ORDER BY pno, hours DESC; Can also be used with GROUP BY COSC344 Lecture 56 18

Summary of SQL Queries SELECT [ ALL DISTINCT ] <attribute and function list> FROM <table list> [ WHERE <condition> ] [ GROUP BY <grouping attribute(s)> ] [ HAVING <group condition> ] [ ORDER BY <attribute list> ]; COSC344 Lecture 56 19

UNION Operator Puts multiple queries together and combines their results Example - Find all the salespeople and customers located in London SELECT snum,sname FROM salespeople WHERE city='london' UNION SELECT cnum,cname FROM customer WHERE city='london'; Result: 1001 Peel 1004 Motika 2001 Hoffman 2006 Clemens COSC344 Lecture 56 20

UNION Operator (continued) No column headings are in the output. Duplicates are automatically eliminated. UNION ALL does not eliminate duplicates. The queries must be union compatible Same number of columns Each column must be data type compatible with its corresponding column Can follow with an ORDER BY clause to order the results. COSC344 Lecture 56 21

Lab for week 4 The Company database and the Sales database. Needed next week Compare the.sql files to create and populate these databases. The Company database has good examples of integrity constraints The Sales database is an example of how not to create tables. There are no constraints at all. COSC344 Lecture 56 22