SQL. A Short Note. November 14, where the part appears between [ and ] are optional. A (simple) description of components are given below:

Similar documents
Relational Algebra and SQL

Chapter 2: The Relational Algebra

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

Chapter 2: The Relational Algebra

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

Database Systems CSE 303. Outline. Lecture 06: SQL. What is Sub-query? Sub-query in WHERE clause Subquery

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

Chapter 4: SQL. Basic Structure

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

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

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

DATABASE TECHNOLOGY - 1MB025

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Relational Algebra and Calculus

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

DATABASE TECHNOLOGY - 1MB025

Relational Databases

Chapter 3: Introduction to SQL

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

Chapter 3: Introduction to SQL

Introduction to Databases, Fall 2005 IT University of Copenhagen. Lecture 2: Relations and SQL. September 5, Lecturer: Rasmus Pagh

Database Systems SQL SL03

DATABASTEKNIK - 1DL116

Relational Model, Relational Algebra, and SQL

Database Systems SQL SL03

CS 317/387. A Relation is a Table. Schemas. Towards SQL - Relational Algebra. name manf Winterbrew Pete s Bud Lite Anheuser-Busch Beers

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

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

DATABASE DESIGN I - 1DL300

Set Operations, Union

MTA Database Administrator Fundamentals Course

Querying Data with Transact SQL

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries

SQL Overview. CSCE 315, Fall 2017 Project 1, Part 3. Slides adapted from those used by Jeffrey Ullman, via Jennifer Welch

Relational Algebra and SQL. Basic Operations Algebra of Bags

Querying Data with Transact-SQL

Introduction to SQL SELECT-FROM-WHERE STATEMENTS SUBQUERIES DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

STIDistrict Query (Basic)

Database Management Systems,

QQ Group

Introduction to SQL. Select-From-Where Statements Multirelation Queries Subqueries. Slides are reused by the approval of Jeffrey Ullman s

DATABASE TECHNOLOGY. Spring An introduction to database systems

The SQL database language Parts of the SQL language

Relational Algebra and SQL

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

Information Systems Engineering. SQL Structured Query Language DML Data Manipulation (sub)language

SQL. The Basics Advanced Manipulation Constraints Authorization 1. 1

CS 327E Lecture 2. Shirley Cohen. January 27, 2016

Chapter 3: SQL. Chapter 3: SQL

HKTA TANG HIN MEMORIAL SECONDARY SCHOOL SECONDARY 3 COMPUTER LITERACY. Name: ( ) Class: Date: Databases and Microsoft Access

SQL Overview cont d. SQL Overview. ICOM 5016 Database Systems. SQL Data Types. A language higher-level than general purpose languages

Principles of Data Management

Final Examination Computer Science 420 Dr. St. John Lehman College City University of New York 21 May 2002

Part II Relational Databases Data as Tables

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

user specifies what is wanted, not how to find it

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

1) Introduction to SQL

SQL - Data Query language

Midterm Review. Winter Lecture 13

Relational Algebra BASIC OPERATIONS DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA

CSC Web Programming. Introduction to SQL

Unit Assessment Guide

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

Databases-1 Lecture-01. Introduction, Relational Algebra

Structured Query Language Continued. Rose-Hulman Institute of Technology Curt Clifton

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

T-SQL Training: T-SQL for SQL Server for Developers

Database Management Systems Paper Solution

Relational Algebra. Procedural language Six basic operators

Why SQL? SQL is a very-high-level language. Database management system figures out best way to execute query

Relational Algebra. ICOM 5016 Database Systems. Roadmap. R.A. Operators. Selection. Example: Selection. Relational Algebra. Fundamental Property

Relational Algebra. Spring 2012 Instructor: Hassan Khosravi

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

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

Chapter # 7 Introduction to Structured Query Language (SQL) Part II

Today s topics. Null Values. Nulls and Views in SQL. Standard Boolean 2-valued logic 9/5/17. 2-valued logic does not work for nulls

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

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

Introduction to SQL Part 2 by Michael Hahsler Based on slides for CS145 Introduction to Databases (Stanford)

From Relational Algebra to the Structured Query Language. Rose-Hulman Institute of Technology Curt Clifton

Language. f SQL. Larry Rockoff COURSE TECHNOLOGY. Kingdom United States. Course Technology PTR. A part ofcenqaqe Learninq

An Introduction to Structured Query Language

Basic SQL. Basic SQL. Basic SQL

Assignment #2. CS Spring 2015 Due on Friday, June 19, 2015, 9 AM For instructions on how to submit your assignment check the course website.

E-R diagrams and database schemas. Functional dependencies. Definition (tuple, attribute, value). A tuple has the form

Index. Bitmap Heap Scan, 156 Bitmap Index Scan, 156. Rahul Batra 2018 R. Batra, SQL Primer,

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

CSCB20 Week 4. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

An Introduction to Structured Query Language

Slides by: Ms. Shree Jaswal

Database Languages. A DBMS provides two types of languages: Language for accessing & manipulating the data. Language for defining a database schema

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

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

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream

The Extended Algebra. Duplicate Elimination. Sorting. Example: Duplicate Elimination

SQL (Structured Query Language)

Transcription:

SQL A Short Note November 14, 2002 1 Syntax SQL Queries have the generic form as follows: SELECT [DISTINCT] List_of_attributes FROM List_of_tables [ WHERE Condition] [ ORDER BY List_Of_Ordering_Attributes ] [ GROUP BY List_Of_Grouping_Attributes [HAVING Having_Condition] ] [ UNION [All] INTERSECT [All] EXCEPT [All] SUB_QUERY ] where the part appears between [ and ] are optional. A (simple) description of components are given below: 1. List Of Attributes: a list of (a) attribute name (e.g. maker) (b) attribute name AS new name (this is used for renaming) (c) aggregation expression (e.g SUM(price)) (d) arithmetic expression (e.g. price*2) which are separated by comma (* stands for ALL). This list specifies what attributes does the output relation have. 2. List Of Tables: a (separated by comma) list of relation names (or table names) (e.g. product, PC); this can also contain a subquery; This list specifies the sources of the information used for the query. 3. Condition: a Boolean expression built using 1

(a) attribute names, (b) logical operators: AND, OR, NOT (c) arithmetic operators (+,-,*,/) on numeric valued attributes (d) comparison operators (,,=, =, =) or special comparison operator (e.g. strings LIKE) for This condition specifies the tuples from the relations that the query specifier is interested in. In constructing the condition, special care needs to be made when working with NULL values which indicate unknown value (the price is unknown, the birthdate is unknown, etc.): Arithmetic operations with NULL as one of the arguments yield NULL result, e.g., 50 + NULL gives NULL, 10 * NULL gives NULL. Boolean operations with NULL might yield UNKNOWN truth: see table on threevalued logic in the book (table 6.2); for instance, A NULL gives UNKNOWN. 4. List Of Ordering Attributes: list of attributes which are used for ordering the output; this is similar to the list in the sorting operator of extended operator of relational algebra. 5. List Of Grouping Attributes: list of attributes which are used for grouping the data for aggregation operations; this is similar to the list of grouping attributes occurring in of the operator. 6. Having Condition: construction is similar to the condition in the where clause; the effect of this part is to select the groups that satisfy this condition. 7. SUB QUERY: another query. 8. DISTINCT: used to specify the set operation instead of the bag operation that is the default in SQL. 2 SQL queries and Relational Algebra Each relational agebra expression (in extended operators) can be translated in a SQL query that yields the same result (the output contains the same set of tuples). This will be demonstrated through examples in this section. We will use the running example of a database with the following relations: product(maker,model,type) pc(model,speed,ram,hd,cd,price) laptop(model,speed,ram,hd,screen,price) printer(model,color,type,price) 2

2.1 Projection/Selection The expression and the SQL query: SELECT A1,...,An FROM R will give the same answer. For example, "!#$ &%')(+*-,/.10 and SELECT maker FROM product will give the list of all producers in the database. The query SELECT DISTINCT maker FROM product will list the list of all producers without duplication. The expression 2345768:9&8&45/ and the SQL query: SELECT * FROM R WHERE Condition will give the same answer. For example, 2 "!#<;>=:=5?%'@(@*-,/.A0 and SELECT * FROM product where maker= A will give the list of all the products (model, type) produced by producer A. We can combine selection and projection as in relational algebra. Examples: select model from pc where speed>=200 and price < 2500 is equivalent to 4B6<!5C5 2DFEG!!56"H;IJJ <K6EA#B8&LM!ONIPJJ$ &%. Q select model from pc where cd like 8% is equivalent to 4B6<!5C5 2LM6O; =SR<T/= &%.7 where the U stands for any string; The following query uses the renaming and ordring features: select model, speed as megahertz, ram, hd as gigabytes from pc where price<2500 order by speed, ram 2.2 Join, Union, Difference, and Intersection The natural join between two relations and V, ẌW YZV can be specified in the WHERE clause (the condition) by having a condition of the form Ẍ[]\^`_aVb[]\^c\ZdfegẌ[]\`I^_aVb[]\`Ih\Zdfe [K[K[. For example, to join the relations product and laptop and get the maker who produces laptop with the hard disk larger than 0.3 gb, we write select maker, speed from product, laptop where product.model=laptop.model and hd>= 0.3 3

which is equivalent to "!#B DiE1!5! 6$ 2j16"H;JQ k+?%')(+*-,l.a01w YnmoK%0O(A%/. To list the price and model of PC produced by maker B we write: select product.model, price from pc,product where maker= B and product.model=pc.model which is the same as 4B6<!5C& E1#58&LM!7 M2bO"!#<;>=&p=B?%'@(@*-,/.A01W Yc%. Q NOTE: In SQL queries, we use the notation tablename.attributename to disambiguate attributes when relations involving in the query have the same attribute name. For instance, product.model specifies that the value should be taken from the attribute model of the relation product To get the list of products and their price produced by maker B we uses UNION: select product.model,price from pc,product where maker= B and product.model=pc.model union select product.model,price from laptop,product where maker= B and product.model = laptop.model union select product.model, price from printer, product where maker= B and printer.model=product.model This is equivalent to b456o! C? EA#B8:L! M2bO"! #;>=&p= &%'@(@*-,/.101W Yq%. Q r 4B6<!5C& E1#58&LM!7 M2bO"!#<;>=&p=B?%'@(@*-,/.A01W Ỳ mmok%0o(a%/q r 4B6<!5C& E1#58&LM!7 M2bO"!#<;>=&p=B?%'@(@*-,/.A01W Yc%'+s5t/0OuK'v. To get the list of producer who produces both PC and laptop we uses INTERSECTION (INTER- SECT in SQL): select maker from pc,product where product.model=pc.model intersect select maker from laptop,product where product.model=laptop.model This is equivalent to bo"!#$?%')(+*-,l.a01w Yq%.7 rwbo"! #x?%'@(+*y,/.a01w YZmMoK%0O(A%/. To get the list of producer who produces PC but do not produce laptop we uses SET DIFFERENCE (EXCEPT in SQL): select maker from pc,product where product.model=pc.model except select maker from laptop,product where product.model=laptop.model This is equivalent to bo"!#$?%')(+*-,l.a01w Yq%.7 z{ "!#+?%')(+*-,l.a01w YnmoK%0O(A%/. If we want to have a bag (keep the duplications) in the above operations, we should write ALL after union, intersect, or except, respectively. 4

2.3 Aggregation and Grouping Aggregation operators: SUM, AVG, MIN, MAX, COUNT. Relational algebral expression involving these operators can be translated in into a SQL query whose List Of Attributes as L as follows: into the list of grouping attributes of the corre- put all the grouping attributes occuring in sponding SQL query, for example, j16" }l~:die1!5! 6O &%. is translated into select hd, AVG(speed) from pc group by hd Find the maker(s) of PC(s) with the fastest processor among all those PC s that have the smallest amount of RAM select maker, pc.model, price, speed, ram from pc, product where pc.model = product.model select maker, pc.model, price, speed, ram from pc, product where pc.model = product.model order by ram, speed select maker, pc.model, price, speed, ram from pc, product where pc.model = product.model and pc.speed = (select max(speed) from pc group by ram having ram = (select min(ram) from pc)) and pc.ram = (select min(ram) from pc) 3 Creating a Relation Schema in SQL 3.1 Data types The basic data type: 1. Character string: CHAR(n) (fixed length t ) or VARCHAR(n) (up to t characters) where t is an integer. 2. Bit string: BIT(n) (fixed length t ) or VARBIT(n) (up to t bits) where t is an integer. 3. BOOLEAN: TRUE, FALSE, or UNKNOWN. 4. INT or INTEGER: integer. 5. FLOAR or REAL or DECIMAL(n,d): real values. 6. DATE and TIME: date and time. 5

3.2 Simple Table Declaration Syntax: CREATE TABLE relation_name( attribute_name_1 attribute_name_2... attribute_name_m ); where the ov00<'@s5 1,0Ou t o- wu s and 0<ƒ$%u () respectively. For example, we use CREATE TABLE produce( maker varchar(1), model integer, type varchar(10) ); type_of_attribute_1, type_of_attribute_2, type_of_attribute_m ov00<'+sb A,0Ou s is the name and the type of the s 9?j attribute, to create the table product. We can specify a default for an attribute when creating the table by adding DEFAULT attribute value after the type specification of the attribute. For example, CREATE TABLE produce( maker varchar(1) default U, model integer, type varchar(10) ); specifies that the maker should have the value U if it was not specified by others. 3.3 Database Modifications This includes: insertion, deletion, and update the tuples of a relation. The SQL commands for these activities are: INSERT, DELETE, and UPDATE. Insertion. Syntax: INSERT INTO Relation_Name (att1,...,attn) VALUES (v1,...vn) where 1. Relation Name: the name of the relation that will be inserted a new tuple 2. (att1,...,attn): the (might be incomplete) list of attribues of Relation Name 3. (v1,...vn): the list of values assigned to the attributes in the attribute list (att1,...,attn); the value vi is assigned to the attribute atti. 6

Example: to insert the tuple ( A,1000, pc ) into the table product, we write INSERT INTO product (maker,model,type) VALUES ( A,1000, pc ) this can be shorten to INSERT INTO product VALUES ( A,1000, pc ) If we write INSERT INTO product (model,type) VALUES (1000, pc ) then a new tuple is added in which maker has the NULL value or some default value that is specified when we create the table; We can get a set of tuples from a relation and insert them into another relation by using the following form INSERT INTO Relation_Name (att_list) QUERY where QUERY is a query described earlier, att list is the list of attributes from Relation Name; QUERY must return a relation (a set/bag of tuples) whose attributes have the same type as those occurring in att list. For example, we can create a relation maker with one attribute producer name by CREATE TABLE maker (producer_name varchar(1)) and insert into this table all the makers from the relation product by the command INSERT INTO maker (producer_name) SELECT DISTINCT maker FROM product Deletion. Syntax: DELETE FROM Relation_Name WHERE Condition where 1. Relation Name: the name of the relation from which tuples will be deleted; 2. Condition: specifies which tuples will be removed. Example: To delete all the products of maker B in the table product, we write DELETE FROM product WHERE maker = B Update. Syntax: UPDATE Relation_Name SET new_value_assignment WHERE Condition 7

where 1. Relation Name: the name of the relation from which information will be updated; 2. new value assignment: a list of formulas, each sets an attribute of the relation equal to the value of an expression or constant; 3. Condition: specifies which tuples will be updated. Example: To change all products of maker B into products of A, we write UPDATE product SET maker = A WHERE make= B 4 Views View a different presentation of a relation; does not exist physically (will not exist after the session is closed); defined by a query (expression); 4.1 Declaring/Querying Views CREATE VIEW View_Name AS View_Definition where 1. View Name: the name that will be used to refer to the view created by the command; 2. View Definition: the expression that specifies the tuple belonging to the view For example, we want to have the list of pc with ram 32 in a view, we write CREATE VIEW pcrammorethan32 AS SELECT * FROM PC WHERE ram > 32 After this command, we can use pcrammorethan32 like product, pc, etc. However, if we quit and reenter db2, the relation will no longer exist. For example, we can use pcrammorethan32 to find the fastest pc that has more than 32 Mb ram: SELECT model, speed, ram FROM pcrammorethan32 WHERE speed = max(speed) 8

4.2 Modifying View Only updatable views can be modified. When it is done, this is translated into an equivalent modification on a base table (the table stored physically). The important characters of updatable views are: 1. The view must be defined by a SELECT clause (not SELECT DISTINCT) that selects tuples from a relation ; 2. The WHERE clause must not involve the relation ; 3. The list in the SELECT clause must include enough attributes that for every tuple inserted into the view, we can fill other attributes out with NULL values or proper default and have a tuple of the base relation that will yield the inserted tuple of the view; Consider the view: CREATE VIEW pcmodelpricerammorethan32 AS SELECT model, price FROM PC WHERE ram > 32 This will give us a relation with two attributes model and price. This satisfies the first two conditions of an updatable view but not the third one. To see why, we can look at the command INSERT INTO pcmodelpricerammorethan32 VALUES (5000,4599) This command attempts to insert into the view pcmodelpricerammorethan32 a new tuple with model=5000 and price=4599. The problem is that ram is not an attribute of this view, and hence, the tuple that should be inserted into PC will have NULL value for ram, which does not meet the criteria that its ram is greater than 32. (NULL compares with 32!) However, the view pcrammorethan32 is an updatable view. We can do INSERT INTO pcrammorethan32 (model, price) VALUES (5000, 4599) and a new tuple will be inserted into pcrammorethan32 and the table pc. Deletions and updates can also be done on updateable views. They will be translated into a command that affects the base table as well. 9