1 Reminder We have covered: –Creating tables –Converting ER diagrams to table definitions Today we’ll talk about: –Altering tables –Inserting and deleting.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 1 R &G - Chapter 5 Life is just a bowl of queries. -Anon (not Forrest Gump)
Advertisements

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
Review Session ER and Relational –ER  Relational –Constraints, Weak Entities, Aggregation, ISA Relational Algebra  Relational Calculus –Selections/Projections/Joins/Division.
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
CS 166: Database Management Systems
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: 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
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 90 Database Systems I SQL Queries.
1 SQL (Simple Query Language). 2 Query Components A query can contain the following clauses –select –from –where –group by –having –order by Only select.
1 The Oracle Database System Building a Database Database Course The Hebrew University of Jerusalem.
FALL 2004CENG 351 File Structures and Data Management1 SQL: Structured Query Language Chapter 5.
1 Views and Null values. 2 What does this return? SELECT B.bid, COUNT(*) FROM Boats B, Reserves R WHERE R.bid=B.bid and B.color=‘red’ GROUP BY B.bid For.
Rutgers University SQL: Queries, Constraints, Triggers 198:541 Rutgers University.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation Adding columns Changing columns’ definition Dropping columns.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation –Adding columns –Changing columns’ definition –Dropping columns.
1 Views. 2 What are views good for?(1) Simplifying complex queries: we saw one example. Here is another example that allows the user to "pretend" that.
1 Rewriting Minus Queries Using Not In SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ MINUS.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 The Oracle Database System Querying the Data Database Course The Hebrew University of Jerusalem.
1 SQL: Structured Query Language Chapter 5. 2 SQL and Relational Calculus relationalcalculusAlthough relational algebra is useful in the analysis of query.
1 Rewriting Intersect Queries Using In SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ INTERSECT.
1 Advanced SQL. 2 Consider the following relations: –pupil (pupil_name, address, class, birthyear) –subject (subject_name, class, teacher) –grades (pupil_name,
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
Chapter 5.  Data Manipulation Language (DML): subset of SQL which allows users to create queries and to insert, delete and modify rows.  Data Definition.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L6_SQL(1) 1 SQL: Queries, Constraints, Triggers Chapter 5 – Part 1.
SQL Part I: Standard Queries. COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby debby lilly.
SQL Examples CS3754 Class Note 11 CS3754 Class Note 11, John Shieh,
Unit 5/COMP3300/ SQL: Queries, Programming, 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.
ICS 321 Fall 2009 SQL: Queries, Constraints, Triggers Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 9/8/20091Lipyeow.
1 Database Systems ( 資料庫系統 ) October 24, 2005 Lecture #5.
ICS 321 Spring 2011 The Database Language SQL (iii) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 3/14/20111Lipyeow.
Introduction to SQL ; Christoph F. Eick & R. Ramakrishnan and J. Gehrke 1 Using SQL as a Query Language COSC 6340.
The Oracle Database System. Connecting to the Database At the command line prompt, write: sqlplus In the beginning your password.
CMPT 258 Database Systems SQL Queries (Chapter 5).
1 SQL: The Query Language (Part II). 2 Expressions and Strings v Illustrates use of arithmetic expressions and string pattern matching: Find triples (of.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
SQL: The Query Language Part 1 R &G - Chapter 5 The important thing is not to stop questioning. Albert Einstein.
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.
SQL CS 186, Spring 2007, Lecture 7 R&G, Chapter 5 Mary Roth   The important thing is not to stop questioning. Albert Einstein Life is just a bowl of.
SQL: The Query Language Part 1 R&G - Chapter 5 1.
SQL. Internet technologies – Ohad © Database  A database is a collection of data  A database management system (DBMS) is software designed to assist.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries.
1 CS122A: Introduction to Data Management Lecture 9 SQL II: Nested Queries, Aggregation, Grouping Instructor: Chen Li.
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.
1 CS122A: Introduction to Data Management Lecture 8 Introduction to SQL Instructor: Chen Li.
1 SQL Structured Query Language. Query Language SQL is a query language Used to examine data in the database SQL queries do not change the contents of.
Basic SQL Queries Go over example queries, like 10 > ALL.
COP Introduction to Database Structures
© פרופ' יהושע שגיב, האוניברסיטה העברית
Structured Query Language
01/31/11 SQL Examples Edited by John Shieh CS3754 Classnote #10.
SQL The Query Language R & G - Chapter 5
Database Systems October 14, 2009 Lecture #5.
DB Review.
Basic SQL Lecture 6 Fall
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
CS 405G: Introduction to Database Systems
SQL: The Query Language Part 1
CS4222 Principles of Database System
SQL: Structured Query Language
Presentation transcript:

1 Reminder We have covered: –Creating tables –Converting ER diagrams to table definitions Today we’ll talk about: –Altering tables –Inserting and deleting data from tables –Querying tables

2 Table Alteration

3 Altering Tables Table definitions can be altered after their creation –Adding columns –Changing columns’ definition –Dropping columns –Adding or dropping constraints –And more… Use the reserved word ALTER

4 Altering Tables (cont.) Adding a column: ALTER TABLE Employee ADD ( Mname VARCHAR2(20), Birthday DATE ); Changing columns ’ definition: ALTER TABLE Emplyee Modify ( Mname VARCHAR2(10) ); Cannot be NOT NULL unless the table is empty

5 Altering Tables (cont.) Dropping columns: ALTER TABLE Employee DROP COLUMN Mname; Dropping multiple columns: ALTER TABLE Employee DROP (Mname, Birthday); Adding constraints: ALTER TABLE Department ADD( FOREIGN KEY (ManagerId) REFERENCES Employee(SSN));

6 Inserting, deleting, and updating data in a table

7 The Employee Table > Describe Employee Name Null? Type SSN NUMBER FNAME VARCHAR2(20) LNAME VARCHAR2(20) GENDER CHAR(1) SALARY NOT NULL NUMBER(5)

8 Inserting a Row To insert a row into the Employee table: INSERT INTO Employee(SSN, Fname, Lname, Salary) VALUES(121, ‘Sara’, ‘Cohen’,10000); The remaining columns get default values (or NULL) When will this fail?

9 Some More Details… The fields don’t have to be specified if values are specified for all columns and in the order defined by the table Example: INSERT INTO Employee VALUES(121, ‘Sara’, ‘Cohen’, `F’, 1000);

10 Deleting Rows General format: DELETE FROM Table WHERE Cond; Deletes all rows satisfying Cond from Table For example, to remove the employee with SSN 121 from the Employee table: DELETE FROM Employee WHERE SSN = 121;

11 Deleting Rows (cont.) To remove all male employees having a salary greater than 150,000 shekels: DELETE FROM Employee WHERE Salary > ;

12 Updating Rows We can update rows in a table General format: UPDATE Table SET Field1=value1,,,FieldN=valueN WHERE Cond Now we can reduce salaries instead of firing employees: UPDATE Employee SET Salary = WHERE Salary > ;

13 The ORACLE Bulk Loader A tool that provides easy insertion of large amounts of rows into tables. The idea: the values of the inserted rows are kept in a compact file: the Data file. We define the structure of the Data file, in the Control file. Here we enter the data we want to insert (employees) myData.dat Here we specify the structure of the data file myCtrl.ctl

14 The Control File For example, we can load 3 employees from the file myEmp.dat that contains the following lines: Shaquile|Oneil|121 Magic|Johnson|134 Doron|Sheffer|156 A simple control file: LOAD DATA INFILE [APPEND] INTO TABLE FIELDS TERMINATED BY ' ‘ ( )

15 The Control File (cont.) : The name of the data file : The name of the table into which the data will be loaded (appended if APPEND is specified, or else the table must be empty) : A string that separates two field values of a row The attributes are separated by commas and enclosed in parentheses

16 The Control File (cont.) Example: –When the control file is run, this will insert the 3 employees into the employees table –The attributes that are unspecified will be set to NULL (or default values if they are specified) LOAD DATA INFILE myEmployees.dat INTO TABLE Employees FIELDS TERMINATED BY '|' (Fname, Lname, SSN) Moshe|Cohen|334 Miri|Levi|998 Alon|Hazan|998 myEmployees.dat myControl.ctl

17 The Data File The Bulk Loader considers every single line to represent one row in the table –Even an empty line! (which will usually result in an error) Spaces are not ignored in the data file! – thus the rows sara| cohen|121 and sara|cohen|121 define different functionalities The NULL value is implied by the NULL keyword or the empty string

18 The Data File (continued) The control and the data files can be combined into one.ctl file using the following format: LOAD DATA INFILE * INTO TABLE Employees FIELDS TERMINATED BY '|' (Fname, Lname, SSN) BEGINDATA Sara|Cohen|121 Benny|Kimelfeld|134 Yaron|Kanza|156

19 The Bulk Invocation To invoke the bulk loader, issue the following command directly from the Unix shell: Sqlldr Erroneous lines in the data file are ignored and written into.bad, and any other relevant information is written into.log. The tables you fill using the Bulk Loader should be created prior to the loader invocation Before invoking the Bulk Loader you have to make sure that no SqlPlus sessions are open.

20 SQL Queries

21 Query Components A query can contain the following clauses –select –from –where –group by –having –order by Only select and from are required Order of clauses is always as above

22 Very Basic SQL Query SELECT [Distinct] Attributes FROM relation Attributes: A list of attributes onto which the query projects (For example: Eid, Ename). Relation: A relation to perform the query on. DISTINCT: Optional keyword to delete duplicates Example: Select studentID, studentName From students

23 StudentIDStudentDept.StudentNameStudentAge 1123MathMoshe ComputersMickey MathMenahem29 Select studentID, studentName From students Result: StudentIDStudentName 1123Moshe 2245Mickey 55611Menahem

24 Basic SQL Query SELECT [Distinct] Attributes FROM relation WHERE condition Attributes: A list of fields onto which the query projects (For example: Eid, Ename). relation: A relation to perform the query on condition: A Boolean condition (For example: Eid>21, or Ename=‘Yuval’ ) DISTINCT: Optional keyword to delete duplicates

25 StudentIDStudentDept.StudentNameStudentAge 1123MathMoshe ComputersMickey MathMenahem29 Select studentID, studentName From students Where StudentDept= ‘ Math ’ Result: StudentIDStudentName 1123Moshe 55611Menahem

26 Basic SQL Query SELECT [Distinct] attributes FROM relation WHERE condition; Notice! The "SELECT" clause defines the operation of projection from the relational model. Selection is defined by the WHERE clause.

27 SQL and relational algebra SELECT Distinct A 1,…,A n FROM R 1,…,R m WHERE C;  A 1,…,A n (  C (R 1 x…x R m ))

28 Basic SQL Query SELECT [Distinct] Attributes FROM relationsList WHERE condition relationsList: A list of relations. The query is performed on the product of these relations (AxBxC…).

29 Basic SQL Query SELECT [Distinct] attributes FROM relations WHERE condition; Important! The evaluation order is: 1.Compute the cross product of the tables in relations. 2.Delete all rows that do not satisfy condition. 3.Delete all columns that do not appear in attributes. 4.If Distinct is specified eliminate duplicate rows.

30 Example Tables Used Reserves sidbidday /10/96 11/12/96 Sailors sidsnameratingage Dustin Lubber Rusty Boats bidbnamecolor Nancy Gloria red green

31 What does this compute? Select sname from sailors, reserves Where sailors.sid=reserves.sid Reserves sidbidday /10/96 11/12/96 Sailors sidsnameratingage Dustin Lubber Rusty

32 SailorsReserves sidsnameratingagesidbidday 22Dustin /10/96 22Dustin /12/96 31Lubber /10/96 31Lubber /12/96 58Rusty /10/96 58Rusty /12/96 Stage 1: Sailors x Reserves

33 SailorsReserves sidsnameratingagesidbidday 22Dustin /10/96 22Dustin /12/96 31Lubber /10/96 31Lubber /12/96 58Rusty /10/96 58Rusty /12/96 Stage 2: “where sailors.sid=reserves.sid”

34 SailorsReserves sidsnameratingagesidbidday 22Dustin /10/96 58Rusty /12/96 Stage 2: “where sailors.sid=reserves.sid”

35 SailorsReserves sidsnameratingagesidbidday 22Dustin /10/96 58Rusty /12/96 Stage 3: “select sname”

36 Sailors sname Dustin Rusty Stage 3: “select sname” Final answer

37 Example Query SELECT DISTINCT sname, age FROM Sailors WHERE rating>7; Q: What does this compute? A: Distinct names and ages of sailors with rating >7. Q: Write it in algebra A:  sname, age (  rating>7 (Sailors))

38 Example Query SELECT DISTINCT sname FROM Sailors, Reserves WHERE Sailors.sid = Reserves.sid and bid = 103; Q: What does this compute? A: names of sailors who reserved boat 103 Q: Write it in relational algebra  sname (  Sailors.sid = Reserves.sid  bid = 103 (Sailors x Reserves))

39 SailorsReserves sidsnameratingagesidbidday 22Dustin /10/96 22Dustin /12/96 31Lubber /10/96 31Lubber /12/96 58Rusty /10/96 58Rusty /12/96  Sailors.sid = Reserves.sid  bid = 103

40 SailorsReserves sidsnameratingagesidbidday 22Dustin /10/96 22Dustin /12/96 31Lubber /10/96 31Lubber /12/96 58Rusty /10/96 58Rusty /12/96 Sailors x Reserves  sname

41 Range Variables SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid and R.bid = 103; Range variables are good style. They are necessary if the same relation appears twice in the FROM clause Similar to Renaming in Relational Algebra

42 Example Query SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid and R.bid != 103; Q: What does this return? A: Names of sailors who reserved a boat other than boat 103 Notice: sailors who reserved both boat 103 and a different boat will appear!

43 A Few SELECT Options Select all columns: SELECT * FROM Sailors; Rename selected columns: SELECT S.sname AS Sailors_Name FROM Sailors S; Applying functions (e.g., Mathematical manipulations) SELECT (age-5)*2 FROM Sailors S;

44 Select operators The aggregate operators available in SQL are: –COUNT(*) –COUNT([DISTINCT] A) –SUM([DISTINCT] A) –AVG([DISTINCT] A) –MAX(A) –MIN(A) NULL values are ignored

45 Examples SELECT Avg(S.age) FROM Sailors S, Reserves R WHERE S.sid = R.sid and R.bid=112 SELECT count(distinct S.sid) FROM Sailors S, Reserves R WHERE S.sid = R.sid SELECT Max(S.age) FROM Sailors S

46 The WHERE Clause Numerical and string comparison: !=,<>,=,, >=, <=, between(val1 AND val2) Logical components: AND, OR Null verification: IS NULL, IS NOT NULL Checking against a list with IN, NOT IN.

47 Examples SELECT sname FROM Sailors WHERE age>=40 AND rating IS NOT NULL ; SELECT sid, sname FROM sailors WHERE sid IN (1223, 2334, 3344) or sname between(‘George’ and ‘Paul’);

48 User’s Table List ORACLE holds tables with some general information about the tables in your database Such Tables are: –Cat, user_objects To see the list of all your tables print: SELECT * FROM Cat; To see the list of all your objects print: SELECT object_name, timestamp, object_type FROM user_objects;

49 The LIKE Operator A pattern matching operator (regular expression) Basic format: colname LIKE pattern –Example: _ is a single character % is 0 or more characters SELECT sid FROM Sailors WHERE sname LIKE ‘R_%y’;

50 SQL query SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid; When would adding DISTINCT give a different result?

51 Are any of these the same? SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid; SELECT DISTINCT R.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid; SELECT R.sid FROM Reserves R Sailors sidsnameratingage Reserves sidbidday

52 Example Query SELECT S.sname FROM Sailors S, Reserves R1, Reserves R2. WHERE S.sid = R1.sid and R1.sid=R2.sid and R1.bid!=R2.bid; How would you query sailors who have reserved more than one boat?

53 SQL query SELECT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid and R.bid = B.bid and B.color = 'red' Q: What does this return? A: Names of sailors who have reserved a red boat.

54 SQL query SELECT distinct B.color FROM Sailors S, Reserves R, Boats B WHERE S.sname = ‘Bob’ and S.sid = R.sid and R.bid = B.bid Q: How would you query the colors of boats reserved by Bob? A:

55 Order Of the Result The ORDER BY clause can be used to sort results by one or more columns The default sorting is in ascending order Can specify ASC or DESC

56 Example SELECT sname, rating, age FROM Sailors S WHERE age > 50 ORDER BY rating ASC, age DESC

57 Other Relational Algebra Operators So far, we have seen selection, projection and Cartesian product How do we do operators UNION and MINUS?

58 Three SET Operators [Query] UNION [Query] [Query] MINUS [Query] [Query] INTERSECT [QUERY] Note: The operators remove duplicates by default! How would you express intersect in Relational Algebra?

59 What does this return? SELECT DISTINCT S.sname FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid and R.bid = B.bid and (B.color = 'red' or B.color='green') What would happen if we replaced or by and ? Then how can we query sailors who have reserved both a green and a red boat?

60 Sailors who’ve reserved red or green boat SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘red’ UNION SELECT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid = R.sid and R.bid = B.bid and B.color = ‘green’; Would INTERSECT here give us sailors who reserved both red and green boats?

61 Sailors who’ve reserved red and green boats SELECT S.sname FROM Sailors S, Reserves R1, Reserves R2 Boats B1, Boats B2 WHERE S.sid = R1.sid and R1.bid = B1.bid and B1.color = ‘red’ and S.sid = R2.sid and R2.bid = B2.bid and B2.color = ‘green’;

62 Multiset (Bag) Operators Union without removing duplicates: UNION ALL SELECT DISTINCT sname FROM Sailors S UNION ALL SELECT DISTINCT sname FROM Sailors S

63 Nested Queries

64 Nested queries in WHERE Equality nested query: Select R.bid From Sailors S, Reserves R Where sid = (select sid from S where sname=‘George’); When would this work? When wouldn’t it?

65 Nested queries in WHERE SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid = 103); Subqueries with multiple results: Names of sailors who’ve reserved boat 103 What would happen if we wrote NOT IN?

66 What does this produce? SELECT S.sname FROM Sailors S WHERE S.sid NOT IN (SELECT R.sid FROM Reserves R WHERE R.bid IN (SELECT B.bid FROM Boats B WHERE B.color='red'))

67 Set-Comparison Queries SELECT * FROM Sailors S1 WHERE S1.age > ANY (SELECT S2.age FROM Sailors S2); Sailors who are not the youngest: We can also use op ALL (op is >, =, ).

68 Correlated Nested Queries SELECT S.sid FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid = 103 and S.sid = R.sid); Names of sailors who’ve reserved boat 103: What would happen if we wrote NOT EXISTS? S not in subquery, refers to outer loop

69 Exists and Not Exists Differs from In and Not In by not matching attributes. Exists: For every tuple in the outer loop, the inner loop is tested. If the inner loop produces a result, the outer tuple is added to the result.