SQL - Basics. SQL Overview

Similar documents
Database System Concepts, 5th Ed.! Silberschatz, Korth and Sudarshan See for conditions on re-use "

SQL. Lecture 4 SQL. Basic Structure. The select Clause. The select Clause (Cont.) The select Clause (Cont.) Basic Structure.

Chapter 4: SQL. Basic Structure

SQL Aggregation and Grouping. Outline

SQL Aggregation and Grouping. Davood Rafiei

Chapter 3: SQL. Database System Concepts, 5th Ed. Silberschatz, Korth and Sudarshan See for conditions on re-use

Chapter 3: SQL. Chapter 3: SQL

Silberschatz, Korth and Sudarshan See for conditions on re-use

DATABASE TECHNOLOGY - 1MB025

QQ Group

Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations Views Modification of the Database Data Definition

Relational Query Languages. Relational Algebra and SQL. What is an Algebra? Select Operator. The Role of Relational Algebra in a DBMS

Relational Algebra and SQL. Relational Query Languages

Updates - Insert. SQL Other Features and Commands. Updates Bulk Insert. Outline. Update commands Views: more details NULL values Constraints

Relational Query Languages. What is an Algebra? Roadmap. Relational Algebra. Chapter 5. The Role of Relational Algebra in a DBMS

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University

DATABASTEKNIK - 1DL116

Relational Algebra. Relational Query Languages

DATABASE TECHNOLOGY - 1MB025

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

Chapter 3: Introduction to SQL

CSE532 Relational Algebra and SQL

DATABASE TECHNOLOGY. Spring An introduction to database systems

Database Systems SQL SL03

DATABASE DESIGN I - 1DL300

Chapter 3: Introduction to SQL

Chapter 5. Relational Algebra and SQL

Database Systems SQL SL03

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

The SQL database language Parts of the SQL language

SQL (Structured Query Language)

The Relational Model Constraints and SQL DDL

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

CS 582 Database Management Systems II

CSIE30600 Database Systems Basic SQL 2. Outline

CMP-3440 Database Systems

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

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

Relational Model History. COSC 304 Introduction to Database Systems. Relational Model and Algebra. Relational Model Definitions.

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

Chapter 6: Formal Relational Query Languages

CS425 Fall 2017 Boris Glavic Chapter 4: Introduction to SQL

Explain in words what this relational algebra expression returns:

Relational Database: The Relational Data Model; Operations on Database Relations

CSEN 501 CSEN501 - Databases I

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Chapter 2: Relational Model

Midterm Review. Winter Lecture 13

Simple SQL. Peter Y. Wu. Dept of Computer and Information Systems Robert Morris University

Relational Algebra. Procedural language Six basic operators

Mahathma Gandhi University

Upon completion of this Unit, students will be introduced to the following

Principles of Data Management

Chapter 5: Other Relational Languages

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Chapter 8: Relational Algebra

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Relational Algebra for sets Introduction to relational algebra for bags

Database System Concepts

Overview of Query Processing and Optimization

Query Optimization. Query Optimization. Optimization considerations. Example. Interaction of algorithm choice and tree arrangement.

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

II. Structured Query Language (SQL)

CSCC43H: Introduction to Databases. Lecture 3

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

II. Structured Query Language (SQL)

Applied Databases. Sebastian Maneth. Lecture 7 Simple SQL Queries. University of Edinburgh - February 1 st, 2016

CIS 330: Applied Database Systems

Slides by: Ms. Shree Jaswal

4. SQL - the Relational Database Language Standard 4.3 Data Manipulation Language (DML)

SQL functions fit into two broad categories: Data definition language Data manipulation language

Chapter 3: Relational Model

Database System Concepts

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

Applied Databases. Sebastian Maneth. Lecture 7 Simple SQL Queries. University of Edinburgh - February 6 st, 2017

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

Oracle Database 10g: Introduction to SQL

Databases - 4. Other relational operations and DDL. How to write RA expressions for dummies

Relational Algebra and SQL

The SQL Query Language. Creating Relations in SQL. Adding and Deleting Tuples. Destroying and Alterating Relations. Conceptual Evaluation Strategy

SQL. SQL DDL Statements

The Relational Algebra

SQL Structured Query Language Introduction

SQL Part 2. Kathleen Durant PhD Northeastern University CS3200 Lesson 6

CSC Web Programming. Introduction to SQL

Query Processing: The Basics. External Sorting

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

Basant Group of Institution

Database System Concepts, 5 th Ed.! Silberschatz, Korth and Sudarshan See for conditions on re-use "

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Textbook: Chapter 6! CS425 Fall 2013 Boris Glavic! Chapter 3: Formal Relational Query. Relational Algebra! Select Operation Example! Select Operation!

Relational Model, Relational Algebra, and SQL

SQL: Queries, Programming, Triggers

Chapter 5: Other Relational Languages.! Query-by-Example (QBE)! Datalog

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

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

Databases. Relational Model, Algebra and operations. How do we model and manipulate complex data structures inside a computer system? Until

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

Transcription:

SQL - Basics Davood Rafiei 1 SQL Overview Structured Query Language standard query language for relational system. developed in IBM Almaden (system R) Some features Declarative: specify the properties that should hold in the result, not how to obtain the result Complex queries have procedural elements Set/Bag semantics International Standards SQL1 (1986) SQL2 (SQL-92) SQL3 (pieces have started to appear) 2

SQL Overview (cont) Data definition component CREATE TABLE table-name (col-defs, constraints) DROP TABLE table-name ALTER TABLE table-name action modifies the definition of a table where action is ADD (col-def) MODIFY (col-def) ADD costraint etc. Data update component INSERT INTO table-name DELETE table-name UPDATE table-name Query Language 3 Example Tables branch (bname, address, city, assets) customer(cname, street, city) deposit(accno, cname, bname, balance) loan(accno, cname, bname, amount) CREATE TABLE branch ( bname CHAR(20), address CHAR(30), city CHAR(15), asset NUMBER(38) ); Oracle command (in Oracle, a semicolon always marks the end of a SQL statement.) 4

Simple Queries branch (bname, address, city, assets) Find the names of all branches with assets greater than $2,500,000. SELECT bname branch WHERE assets > 2500000 Find the names of all branches in Edmonton with assets greater than $2,500,000. SELECT bname branch WHERE assets>2500000 AND city= Edmonton Simple predicates can be combined using AND, OR, NOT. 5 Querying two Relations customer(cname, street, city) deposit(accno, cname, bname, balance) List the name and the city of every customer who has an account with balance over $2,000. SELECT customer.cname, city customer, deposit WHERE balance > 2000 AND customer.cname = deposit.cname 6

Queries With Tuple Variables loan(accno, cname, bname, amount) deposit(accno, cname, bname, balance) Find customers who have both loans and deposits. SELECT WHERE loan.cname loan, deposit loan.cname = deposit.cname Equivalently using tuple variables: SELECT WHERE l.cname loan l, deposit d l.cname = d.cname Range variables are really needed if the same relation appears twice in the clause. 7 A Simple Evaluation Alg. SELECT R1 r1, R2 r2, WHERE C Tuple variables r1, r2, respectively range over rows of R1, R2,... Evaluation strategy: clause produces Cartesian product of listed tables WHERE clause produces table containing only rows satisfying condition SELECT clause retains listed columns for every tuple r1 in R1, r2 in R2, let r := r1, r2, if C(r) then output the desired columns 8

From SQL to Relational Algebra SELECT l.cname loan l, deposit d WHERE l.cname = d.cname Equivalent to: temp = loan deposit [a1,cn1,bn1,b1,a2,cn2,bn2,a2] π cn1 σ cn1 = cn2 (temp) This is a simple evaluation algorithm for SELECT. 9 Queries With Set/Bag Results Find all cities of customers. SELECT city customer Result? To get rid of duplicates, we need SELECT DISTINCT city customer 10

Duplicates Duplicate rows not allowed in a relation However, duplicate elimination from query result is costly and not automatically done; it must be explicitly requested: SELECT DISTINCT.... 11 Working with Strings Equality and comparison operators apply to strings (based on lexical ordering) WHERE cname < P Concatenate operator applies to strings WHERE bname -- address =. Expressions can also be used in SELECT clause: SELECT bname -- address AS NameAdd branch 12

Working with Strings (cont) customer(cname, street, city) Find every customer whose address starts with Computing Science. SELECT * customer WHERE address LIKE Computing Science% Expression: col-name [NOT] LIKE pattern Pattern may include wildcard characters % matching any string and _ (underscore) matching any single character. 13 Naming the Results deposit(accno, cname, bname, balance) For every deposit holder who has over $1000, find the customer name and the balance over $1000. SELECT cname, (balance - 1000)as bal deposit WHERE balance > 1000 14

Ordering the Results branch (bname, address, city, assets) Find the names and assets of all branches with assets greater than $2,500,000 and order the result in ascending order of asset values. SELECT bname, assets branch WHERE assets > 2500000 ORDER BY assets Default is ascending order; a descending order can be specified by the DESC keyword. 15 Queries Involving Set Operators set union : Q1 UNION Q2 the set of tuples in Q1 or Q2 set difference : Q1 MINUS Q2 the set of tuples in Q1 but not in Q2 set intersection : Q1 INTERSECT Q2 the set of tuples in both Q1 and Q2 Q1 and Q2 must be union-compatibles same number/types of attributes. 16

Queries With Set Operators List deposit-holders who have no loans. (SELECT cname deposits) MINUS (SELECT cname loan) List cities where there is either a customer or a branch. (SELECT city customer) UNION (SELECT city branch) 17 Queries With Set Operators Find all cities that have both customers and branches in. (SELECT city customer) INTERSECT (SELECT city branch) Find every city that has a branch but no customer. 18

Queries Over Multiple Relations branch (bname, address, city, assets) customer(cname, street, city) deposit(accno, cname, bname, balance) SELECT brach.bname, assets branch,customer,deposit WHERE customer.city = Jasper AND customer.cname = deposit.cname AND deposit.bname = branch.bname What does the query do? Find the names and assets of any branch which has deposit account holders living in Jasper. 19 Queries With Nested Structures Queries within the WHERE clause of an outer query SELECT WHERE OPERATOR(SELECT WHERE) There can be multiple levels of nesting Operators: IN, (NOT) EXISTS, < ALL, Avoid nesting as much as possible. 20

Nested Structures Using IN SELECT WHERE expr (expr list) IN (set of values) E.g. WHERE province IN ( AB, BC ) WHERE province NOT IN ( AB, BC ) WHERE (name,city) IN (( John Doe, Edmonton ), ( John Doe, New York )) 21 Example deposit(accno, cname, bname, balance) SELECT cname deposit WHERE bname IN (SELECT bname deposit WHERE cname = John Doe ) What does the query do? Find every customer who has a deposit in some branch at which John Doe has a deposit. 22

The Same Example Without Nesting deposit(accno, cname, bname, balance) SELECT WHERE AND d1.cname deposit d1, deposit d2 d2.cname = John Doe d1.bname = d2.bname NOTE: avoid nesting as much as possible. 23 Nested Structures Using < ALL, SELECT WHERE expr < ALL (set of values) Other forms: <= ALL, = ALL, >= ALL, > ALL Op ALL (set of values) evaluates to true iff the comparison evaluates to true for every value in the set. Op SOME (set of values) evaluates to true iff the the comparison evaluates to true for at least one value in the set. 24

Nested Structures Using >ALL, branch (bname, address, city, assets) Find branches that have assets greater than the assets of all branches in Calgary. SELECT WHERE bname branch assets > ALL (SELECT WHERE assets branch city = Calgary ) 25 Nested Structures Using EXISTS SELECT WHERE (NOT) EXISTS(SELECT ) EXISTS (SELECT ) evaluates to true iff the result of the subquery contains at least one row. The expression is evaluated for every iteration of the outer query. 26

EXISTS Construct Example branch (bname, address, city, assets) customer(cname, street, city) Find the names of customers who live in a city with no bank branches. SELECT cname customer WHERE NOT EXISTS (SELECT * branch WHERE customer.city=branch.city) Find the names of customers who live in a city which has a bank branch. Change NOT EXISTS to EXISTS. (can also write it using join) 27 Division Query type: Find the subset of items in one set that are related to all items in another set Example: Find customers who have deposits accounts in all branches. Contains row <c,b> if customer c has a deposit account in branch b cname bname bname All branch names π cname, bname (deposit) / π bname (branch) 28

Division Strategy for implementing division in SQL: Find set, A, of all branches in which a particular customer, c, has a deposit account. Find set, B, of all branches. Output c if A B, or, equivalently, if B A is empty 29 Division SQL Solution SELECT c.cname customer c WHERE NOT EXISTS (SELECT b.bname branch b MINUS SELECT d.bname ) branch (bname, address, city, assets) deposit(accno, cname, bname, balance) deposit d WHERE d.cname=c.cname -- set B of all branches -- set A of branches in which -- customer c has a deposit account -- global variable 30

Division 2 nd SQL Solution Find customers who have deposit accounts in all branches. Same as find all customers such that there is no branch where they do not have deposits in. Deposits of c in branch b SELECT c.cname customer c WHERE NOT EXISTS (SELECT bname branch b WHERE NOT EXISTS (SELECT * deposit WHERE b.bname=deposit.bname AND c.cname = deposit.cname)) branches where c has no deposits in 31 Division Another Example Find professors who have taught courses in all departments. Strategy for implementing division in SQL: Find set, A, of all departments in which a particular professor, p, has taught a course Find set, B, of all departments Output p if A B, or, equivalently, if B A is empty 32

Division SQL Solution Professor (Id, Name, DeptId) Department (DeptId, Name) Course (DeptId, CrsCode, CrsName, Descr) Teaching (ProfId, CrsCode, Semester) SELECT P.Id Professor P WHERE NOT EXISTS (SELECT D.DeptId -- set B of all dept Ids Department D MINUS SELECT C.DeptId -- set A of dept Ids of depts in -- which P has taught a course Teaching T, Course C WHERE T.ProfId=P.Id -- global variable AND T.CrsCode=C.CrsCode) 33 Oracle SQL and Oracle the first commercial relational database system. based on the system R prototype. Will be using Oracle V9i. Many supporting products: SQL Plus: interactive SQL interface SQL Precompilers (C, C++) SQL Loader: tool for mass loading of data PL/SQL: Oracle s Procedural Language extension JDBC support Oracle Forms: tool for creating forms interfaces Oracle Report Writer: report definition and formatting 34

Basic Data Types in Oracle NUMBER(m,n) DATE decimal number (precision, scale) (no parameters means floating point) century,year,month,day, hh.mm.ss CHAR(n) fixed-length char string (n <= 2000) VARCHAR2(n) var-length char string (n <= 4000) LONG var-length char string (up to 2 gigabytes) RAW(n) fixed-lengh raw binary data (n <= 2000) LONG RAW var-length raw binary data (max 2 gigs) 35 Other Data Types in Oracle VARCHAR(n) same as VARCHAR2(n) LONG VARCHAR(n) same as LONG DECIMAL(m,n) same as NUMBER(m,n) FLOAT same as NUMBER INTEGER same as NUMBER(38,0) SMALLINT same as NUMBER(38,0) REAL same as NUMBER DOUBLE PRECISION same as NUMBER 36