-- Introduction to database principles Maoying Wu March 11, 2013 Chapter 3: Basic SQL.

Slides:



Advertisements
Similar presentations
Ver 1,12/09/2012Kode :CCs 111,Sistem basis DataFASILKOM Chapter 3: SQL Bambang Irawan Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan.
Advertisements

1 Today’s Class  Relational Model  SQL CS F212 Database Systems.
E-R Diagram for a Banking Enterprise
SQL Sangeeta Devadiga CS157A, Fall Outline Background Data Definition Basic Structure Set Operation.
SQL.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Ordering the Display of Tuples List in alphabetic order the names of all customers having.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
SQL Structured Query Language Meizhen Huang. Content (4.1 – 4.4) Background Parts of SQL Basic Structure Set Operations Aggregate Functions.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Modification of the Database – Deletion Delete all account records at the Perryridge branch.
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL Database Management Systems I Alex Coman, Winter 2006.
1 CMSC424, Spring 2005 CMSC424: Database Design Lecture 7.
Database Design and Implementation (including SQL) Also see MS Access notes: Access: Part1, Part2, Part3, Part4Part1Part2Part3Part4.
©Silberschatz, Korth and Sudarshan1.1Database System Concepts - 5 th Edition, May 23, 2005 Introduction to Database System Concepts.
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Aandachtspunten Deadlines – alles op tijd inleveren! n Lees goed wat van je verwacht wordt!
MySQL Tutorial (2) Introduction to Database. Banking Example branch (branch-name, branch-city, assets) customer (customer-name, customer-street, customer-city)
SQL Lecture 3 SQL Lecture 3. 2 SQL SQL Data Definition Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Complex.
MySQL Tutorial Introduction to Database. Learning Objectives  Read and write Data Definition grammar of SQL  Read and write data modification statements.
CIS552SQL1 Data Definition Language Insertions Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations.
Dr. Kalpakis CMSC 461, Database Management Systems URL: SQL.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
Database System Concepts, 5th Ed. Bin Mu at Tongji University Chapter 3: SQL.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
3.1 Chapter 3: SQL. 3.2 Chapter 3: SQL Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Complex Queries Views Modification.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Null Values It is possible for tuples to have a null value for some of their attributes The.
Lecture 6 Structured Query Language SQL Lecture 6 Structured Query Language SQL Instructor: Haya Sammaneh.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
3.1 Chapter 3: SQL Schema used in examples p (omit 3.8.2, , 3.11)
Basic Structure Given sets A 1, A 2,..., A n a relation r is a subset of A 1 x A 2 x... x A n Thus a relation is a set of n-tuples (a 1, a 2,..., a n )
Structured Query Language 2 Presented by: Annisa, M.Kom. Source: Database System Concepts 5 th edition.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts (Schema) Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested.
Chapter 3: SQL. 3.2Unite International CollegeDatabase Management Systems Chapter 3: SQL Data Definition Basic Query Structure Set Operations Aggregate.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Modification of the Database – Deletion Delete all tuples from the loan relation. delete.
Chapter 3: SQL. 3.2Unite International CollegeDatabase Management Systems Chapter 3: SQL Data Definition Basic Query Structure Set Operations Aggregate.
Computing & Information Sciences Kansas State University Monday, 08 Sep 2008CIS 560: Database System Concepts Lecture 5 of 42 Monday, 08 September 2008.
Database System Concepts, 5 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Relational Model.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts, 5 th Edition, Oct 5, 2006 SQL Data Definition Basic Query Structure Set Operations Aggregate.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com ICOM 5016 – Introduction.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
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.
Chapter 4: SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined Relations.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts Extended Relational-Algebra-Operations Generalized Projection Aggregate Functions Outer Join.
Computing & Information Sciences Kansas State University Friday, 08 Sep 2006CIS 560: Database System Concepts Lecture 07 of 42 Tuesday, 30 January 2007.
MySQL Tutorial Introduction to Database. Introduction of MySQL  MySQL is an SQL (Structured Query Language) based relational database management system.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Source: Database System Concepts, Silberschatz etc Edited: Wei-Pang Yang, IM.NDHU 3-1 Introduction to Database CHAPTER 3 SQL Data Definition Basic.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL Bambang.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
Chapter 5: SQL. Data Definition Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Complex Queries Views Modification.
Database System Concepts ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
SQL and Relational Algebra
Chapter 3: SQL.
Module 4: SQL.
Chapter 3: SQL.
Structured Query Language (SQL)
Chapter 3: SQL.
Chapter 3: SQL.
Introduction to Database
Presentation transcript:

-- Introduction to database principles Maoying Wu March 11, 2013 Chapter 3: Basic SQL

Outline Data Definition Language (DDL) Basic Query Structure Set Operations Aggregate functions Null values Nested subqueries Complex queries Views Modification of the Database Join Operations

Data definition language (DDL) The schema for each relation ( 关系模式 ) The domain of values associated with each attribute ( 列类型 ) Integrity constraints ( 完整性约束 ) The set of indices to be maintained for each relation ( 索引 ) Security and authorization information for each relation ( 权 限 ) The physical storage structure for each relation ( 存储引擎 )

Data Types in SQL char(n): Fixed length character string, with user-specified length n varchar(n): Variable length character string with user-specified maximum length n int: Integer (a finite subset of the integers that is machine-dependent) smallint: Small integer (a machine-dependent subset of the integer domain type) numeric(p, d): Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point real, double precision: floating point and double-precision floating point number, with machine-dependent precision float(n): Floating point number, with user-specified precision of at least n digits To get more details, see the help page for data types in MySQL

Create table CREATE TABLE r(A 1 D 1, A 2 D 2, …, A n D n, [integrity-constraint 1], … [integrity-constraint k]); r is the name of the relation each A i is an attribute name in the schema for relation r D i is the data type for the domain for attribute A i

Integrity constraints NOT NULL PRIMARY KEY (A 1, …, A k )

DROP TABLE DROP TABLE r; Delete all information for relation r from the database

ALTER TABLE ALTER TABLE r ADD A k D k ; Add attributes to an existing relation All tuples in the relation are assigned null as the values for the added attribute ALTER TABLE r DROP A; Drop attributes of a relation not supported by many DBMS

Basic Queries SQL is based on set and relational operations with certain modifications and enhancements A typical SQL query has the form: SELECT A 1, A 2, …, A n FROM r 1, r 2, …, r m WHERE P; This query is equivalent to the relational algebra expression:

The SELECT Clause The SELECT clause lists the attributes for the result of a query Projection operation in relational algebra Keyword DISTINCT can be used to eliminate the duplicate records SELECT DISTINCT loan_number FROM loan; Keyword ALL can be used to preserve all the duplicate records SELECT ALL loan_number FROM loan;

SELECT Clause (Cont.) “*”means “all attributes”: SELECT * FROM loan; Arithmetic expressions (+,-,*,/) can be involved in the expression following SELECT SELECT loan_number, amount*100 FROM loan;

The WHERE Clause WHERE clause specifies conditions the result must satisfy corresponding to the selection predicate of the relation algebra Logical operations like AND, OR and NOT can be used to combine multiple conditional expressions SELECT loan_number FROM loan WHERE branch_name=‘Shanghai’ AND amount>1200;

WHERE Clause BETWEEN can be used to specified the range SELECT loan_number FROM loan WHERE amount BETWEEN AND ; SELECT loan_number FROM loan WHERE (amount > 90000) AND (amount > );

FROM Clause FROM specifies the relations involved in the query corresponding to the Cartesian product operations of the relational algebra SELECT * FROM borrower, loan; Find the name, loan_number and loan amount of all customers having a loan at Shanghai branch: SELECT customer_name, borrower.loan_number, amount FROM borrower, loan WHERE borrower.loan_number = loan.loan_number and branch_name=‘Shanghai’;

AS Clause Synopsis: old_name AS new_name corresponding to the renaming operation in relational algebra: SELECT customer_name, borrower.loan_number AS loan_id, amount FROM borrower, loan WHERE borrower.loan_number = loan.loan_number; SELECT customer_name, T.loan_number, S.amount FROM borrower AS T, loan AS S WHERE T.loan_number = S.loan_number;

string operations SQL includes a string-matching operator for comparisons on character string: LIKE %: matches any string _: matches any character Find the names of all customers whose street includes the substring “Main”: SELECT customer_name FROM customer WHERE customer_street LIKE ‘%MAIN%’; If a percentage sign is included in a string, escape character can be used: LIKE ‘MAIN\%’; NOTE: Many more functions can be used in string operations.

ORDER BY: Ordering the results SELECT DISTINCT customer_name FROM borrower, loan WHERE borrower.loan_number = loan.loan_number AND branch_name=‘Shanghai’ ORDER BY customer_name; The default ordering rule is ascending, but we can also use ‘DESC’ to specify the descending order: ORDER BY customer_name DESC;

Set Operations Set operations UNION, INTERSECT and EXCEPT correspond to the relational algebra, ∩,and -. In MySQL, NO INTERSECT and EXCEPT but we can use IN and NOT IN as an alternative.

Set operations Find all customers with a loan, an account, or both: (SELECT customer_name FROM depositor) UNION (SELECT customer_name FROM borrower); Find all customers who have both loan and account (SELECT customer_name FROM depositor) INTERSECT (SELECT customer_name FROM borrower); Find all customers who have an account but no loan (SELECT customer_name FROM depositor) INTERSECT (SELECT customer_name FROM borrower);

Aggregate functions AVG: average value MIN: minimum value MAX: maximum value SUM: sum of values COUNT: number of values

Aggregate functions: examples Find the average account balance at the Shanghai branch: SELECT avg(balance) FROM account WHERE branch_name = ‘Shanghai’; Find the number of tuples in the customer relation SELECT count(*) FROM customer; Find the number of depositors in the bank SELECT count(distinct customer_name) FROM depositor;

Aggregate: GROUP BY Find the number of depositors for each branch: SELECT branch_name, count(distinct customer_name) FROM depositor, account WHERE depositor.account_number=account.account_number GROUP BY branch_name; NOTE : The attribute names after the GROUP BY should appear after SELECT, while outside the aggregate functions.

HAVING Qualifying Results by Categories Find the names of all branches where the average account balance is more than 1200 SELECT branch_name, avg(balance) FROM account GROUP BY branch_name HAVING avg(balance) > 1200; Distinctions between HAVING and WHERE Predicates in HAVING are applied after forming GROUPS, while predicates in WHERE are applied before forming GROUPS.

NULL values NULL signifies an unknown value or a value that does not exist. The predicate IS NULL can be used to check for NULL values. SELECT loan_number FROM loan WHERE amount IS NULL; The result of any arithmetic expression involving NULL is NULL 1+NULL returns NULL Many aggregate functions ignore NULL values

NULL (cont.) Any comparison with NULL returns UNKNOWN LOGIC involving UNKNOWN: OR (UNKNOWN OR true) = true, (UNKNOWN OR false) = UNKNOWN, (UNKNOWN OR UNKNOWN) = UNKNOWN AND (true AND UNKNOWN) = UNKNOWN, (false AND UNKNOWN) = false, (UNKNOWN AND UNKNOWN) = UNKNOWN NOT (NOT UNKNOWN) = UNKNOWN Any UNKNOWN in WHERE is treated as false IS UNKNOWN is used to evaluate if the expression is UNKNOWN.

NULL value in aggregate Get the total all loan amounts: SELECT SUM(amount) FROM loan; Above statement ignores all NULL amounts Result is NULL is all is NULL. All aggregate operation except count(*) ignore tuples with NULL values on the aggregated attributes.

Nested subqueries SQL provides a mechanism for the nesting of subqueries A subquery is a SELECT-FROM-WHERE expression that is nested within another query A common use of subqueries is to perform tests for set membership, set comparison, and set cardinality

Example subqueries Find all customers who have both an account and a loan at the bank. SELECT distinct customer_name FROM borrower WHERE customer_name in (SELECT customer_name FROM depositor); Find all customers who have a loan at the bank but do not have an account at the bank SELECT distinct customer_name FROM borrower WHERE customer_name NOT IN (SELECT customer_name FROM depositor);

Example subqueries Find all customers who have both an account and a loan at the Shanghai branch SELECT distinct customer_name FROM borrower, loan WHERE borrower.loan_number = loan.loan_number AND branch_name = ‘Shanghai' and (branch_name, customer_name ) IN (SELECT branch_name, customer_name FROM depositor, account WHERE depositor.account_number = account.account_number ); NOTE: The formulation above is simply to illustrate SQL features.

Set comparisons SOME ( 至少存在其中之一 ) Find all branches that have more assets than some branch located in Beijing SELECT distinct T.branch_name FROM branch as T, branch as S WHERE T.assets > S.assets and S.branch_city = 'Beijing' ; Same query SELECT branch_name FROM branch WHERE assets > SOME(SELECT assets FROM branch WHERE branch_city = 'Beijing') ;

Set comparisons ALL ( 所有的都 ) Find all branches that have more assets than all branch located in Beijing SELECT branch_name FROM branch WHERE assets > ALL (SELECT assets FROM branch WHERE branch_city = 'Beijing') ;

Test for empty results EXISTS returns true if the argument subquery is non-empty EXISTS(select-clause) NOT EXISTS(select-clause)

Example query Find all customers who have an account at all branches located in Beijing. SELECT DISTINCT S.customer_name FROM depositor as S WHERE NOT EXISTS ( (SELECT branch_name FROM branch WHERE branch_city = 'Beijing') and branch_name NOT IN(SELECT R.branch_name FROM depositor as T, account as R WHERE T.account_number = R.account_number and S.customer_name = T.customer_name )); Note that

WITH Clause The WITH clause provides a way of defining a temporary view whose definition is available only to the query in which the WITH clause occurs. Find all accounts with the maximum balance WITH max_balance (value) AS SELECT max(balance) FROM account SELECT account_number FROM account, max_balance WHERE account.balance = max_balance.value;

Views ( 视图 ) Consider a person who needs to know a customer’s name, loan number and branch name, but has no need to see the loan amount. This person should see a relation described, in SQL, by (SELECT customer_name, borrower.loan_number, branch_name FROM borrower, loan WHERE borrower.loan_number = loan.loan_number ) A view provides a mechanism to hide certain data from the view of certain users. Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view

Views: Definition A view is defined using the CREATE VIEW statement which has the form CREATE VIEW v AS is any legal SQL expression. Once a view is defined, the view name can be used to refer to the virtual relation that the view generates. When a view is created, the query expression is stored in the database; the expression is substituted into queries using the view.

Example using view A view consisting of branches and their customers: CREATE VIEW all_customer AS (select branch_name, customer_name from depositor, account where depositor.account_number = account.account_number ) union (select branch_name, customer_name from borrower, loan where borrower.loan_number = loan.loan_number ); Find all customers of the Shanghai branch from view select customer_name from all_customer where branch_name = ‘Shanghai' ;

DELETE Delete all accounts at the Guangzhou branch DELETE FROM account WHERE branch_name = ‘Guangzhou’; Delete all accounts at every branch located in Shanghai. DELETE FROM account WHERE branch_name in (SELECT branch_name FROM branch WHERE branch_city=‘Shanghai’);

INSERT Add a new account INSERT INTO account VALUES (‘A-9732’,’Minhang’, 12500); INSERT INTO account(branch_name, balance, account_number) VAlUES (‘Minhang’, 12500, ‘A-9732’); INSERT INTO account VAlUES (‘A-777’, ‘Minhang’, NULL);

INSERT: Example Gifts for customers INSERT INTO account select loan_number, branch_name, 200 from loan where branch_name = ‘Jiaoda‘; INSERT INTO depositor select customer_name, loan_number from loan, borrower where branch_name = ‘Jiaoda' and loan.account_number = borrower.account_number;

UPDATE Increase all accounts with balances over 10,000 by 6%, all other accounts receive 5% increase UPDATE account SET balance = balance * 1.06 WHERE balance > 10000; UPDATE account SET balance = balance * 1.05 WHERE balance <= 10000; The order is important Better using the CASE…WHEN statement

UPDATE (Cont.) CASE WHEN…THEN statement UPDATE account SET balance = CASE WHEN balance <= THEN balance*1.05 ELSE balance*1.06 END;

JOIN INNER JOIN LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN

Relations: borrower and loan loan borrower borrower information missing for L-260; Loan information missing for L-155

JOIN: Examples (1) loan inner join borrower on loan.loan_number = borrower.loan_number loan left outer join borrower on loan.loan_number = borrower.loan_number;

JOIN: Examples (2) loan natural inner join borrower loan natural right outer join borrower

JOIN: Examples (3) loan full outer join borrower using (loan_number) Find all customers who have either an account or a loan (but not both) at the bank: SELECT customer_name FROM (depositor natural full outer join borrower) WHERE account_number is NULL or loan_number is NULL;

bank: schema

Tables: loan and borrower

Table: customer, account, depositor