1 Introduction to Structured Query Language (SQL).

Slides:



Advertisements
Similar presentations
CS411 Database Systems Kazuhiro Minami 06: SQL. SQL = Structured Query Language Standard language for querying and manipulating data Has similar capabilities.
Advertisements

1 Introduction to SQL Select-From-Where Statements Subqueries Grouping and Aggregation.
SQL Group Members: Shijun Shen Xia Tang Sixin Qiang.
1 Introduction to SQL Select-From-Where Statements Multirelation Queries Subqueries.
SQL Queries Principal form: SELECT desired attributes FROM tuple variables –– range over relations WHERE condition about tuple variables; Running example.
Winter 2002Arthur Keller – CS 1806–1 Schedule Today: Jan. 22 (T) u SQL Queries. u Read Sections Assignment 2 due. Jan. 24 (TH) u Subqueries, Grouping.
SQL CSET 3300.
1 Introduction to SQL Multirelation Queries Subqueries Slides are reused by the approval of Jeffrey Ullman’s.
IS698: Database Management Min Song IS NJIT. Overview  Query processing  Query Optmization  SQL.
1 More SQL Defining a Database Schema Views. 2 Defining a Database Schema uA database schema comprises declarations for the relations (“tables”) of the.
1 Constraints Foreign Keys Local and Global Constraints Triggers.
Fall 2001Arthur Keller – CS 1806–1 Schedule Today (TH) Bags and SQL Queries. u Read Sections Project Part 2 due. Oct. 16 (T) Duplicates, Aggregation,
CPSC-608 Database Systems Fall 2008 Instructor: Jianer Chen Office: HRBB 309B Phone: Notes #3.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #2.
Chapter 6 Notes. 6.1 Simple Queries in SQL SQL is not usually used as a stand-alone language In practice there are hosting programs in a high-level language.
SQL 2014, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes via his course web.
CSCE 520- Relational Data Model Lecture 2. Relational Data Model The following slides are reused by the permission of the author, J. Ullman, from the.
SCUHolliday6–1 Schedule Today: u SQL Queries. u Read Sections Next time u Subqueries, Grouping and Aggregation. u Read Sections And then.
Databases : SQL-Introduction 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes.
1 IT 244 Database Management System Lecture 11 SQL Select-From-Where Statements Meaning of queries Subqueries Ref : -A First Course in Database System.
1 Relational Algebra & SQL. 2 Why SQL & Relational Algebra? uSQL is a very-high-level language. wSay “what to do” rather than “how to do it.” wAvoid a.
Constraints on Relations Foreign Keys Local and Global Constraints Triggers Following lecture slides are modified from Jeff Ullman’s slides
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
1 Introduction to SQL. 2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details.
Onsdag The concepts in a relation data model SQL DDL DML.
RELATIONAL DATA MODEL 1. 2 What is a Data Model? 1.Mathematical representation of data. wExamples: relational model = tables; semistructured model = trees/graphs.
Computational Biology Dr. Jens Allmer Lecture Slides Week 6.
1 Introduction to SQL Select-From-Where Statements Multirelation Queries Subqueries Slides are reused by the approval of Jeffrey Ullman’s.
1 Relational Algebra Basic Operations Algebra of Bags.
1 Database Systems Defining Database Schema Views.
Databases 1 Second lecture.
1 More SQL uDatabase Modification uDefining a Database Schema uViews.
CSCE 520- Relational Data Model Lecture 2. Oracle login Login from the linux lab or ssh to one of the linux servers using your cse username and password.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
1 Introduction to SQL Database Systems. 2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation.
1 Introduction to SQL. 2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details.
Relational Algebra BASIC OPERATIONS 1 DATABASE SYSTEMS AND CONCEPTS, CSCI 3030U, UOIT, COURSE INSTRUCTOR: JAREK SZLICHTA.
Himanshu GuptaCSE 532-SQL-1 SQL. Himanshu GuptaCSE 532-SQL-2 Why SQL? SQL is a very-high-level language, in which the programmer is able to avoid specifying.
Introduction to SQL Elements and process: relations  database (with XAMPP) Select-From-Where Statements Grouping and Aggregation 1 Slides by Jeff Ullman.
1 Chapter 6 More SQL uDatabase Modification uDefining a Database Schema uViews.
603 Database Systems Senior Lecturer: Laurie Webster II, M.S.S.E.,M.S.E.E., M.S.BME, Ph.D., P.E. Lecture 18 A First Course in Database Systems.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
1 Introduction to Database Systems, CS420 SQL Constraints.
1 Introduction to Database Systems, CS420 Relational Algebra.
1 Introduction to SQL Select-From-Where Statements Subqueries Grouping and Aggregation.
1 Data Modification with SQL CREATE TABLE, INSERT, DELETE, UPDATE Slides from
1 Introduction to Database Systems, CS420 SQL JOIN, Aggregate, Grouping, HAVING and DML Clauses.
Select-From-Where Statements Multirelation Queries Subqueries
CPSC-310 Database Systems
Schedule Today: Jan. 28 (Mon) Jan. 30 (Wed) Next Week Assignments !!
CPSC-310 Database Systems
Computational Biology
Outerjoins, Grouping/Aggregation Insert/Delete/Update
Foreign Keys Local and Global Constraints Triggers
CPSC-310 Database Systems
Introduction to Database Systems, CS420
CPSC-608 Database Systems
CPSC-608 Database Systems
Database Models Relational Model
CPSC-310 Database Systems
CPSC-310 Database Systems
IT 244 Database Management System
CPSC-608 Database Systems
CPSC-608 Database Systems
CPSC-608 Database Systems
CPSC-608 Database Systems
CMSC-461 Database Management Systems
Instructor: Zhe He Department of Computer Science
Select-From-Where Statements Multirelation Queries Subqueries
Presentation transcript:

1 Introduction to Structured Query Language (SQL)

2 RA Exercise uSALESPERSON(SSN, Name, Start_Year, Dept_No) uTRIP(SSN, From_City, Departure_Date, Return_Date, Trip_ID) uEXPENSE(Trip_ID, Account#, Amount) wGive the details (all attributes of TRIP relation) for trips that exceeded $2000 in expense wPrint the SSN of salesman who took trips to Honolulu wSearch the Name & Dept_No of salesman who took trips from ‘Jakarta’ and expensed no more than $1000

3 Join Example Sells(barbeerprice )Bars(baraddr ) Joe’sBud2.50Joe’sMaple St. Joe’sMiller2.75Sue’sRiver Rd. Sue’sBud2.50 Sue’sCoors3.00 BarInfo := Sells JOIN Bars BarInfo(barbeerpriceaddr ) Joe’sBud2.50Maple St. Joe’sMilller2.75Maple St. Sue’sBud2.50River Rd. Sue’sCoors3.00River Rd.

4 Database

5 Why SQL? uSQL is a very-high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in languages like C++. uWhat makes SQL viable is that its queries are “optimized” quite well, yielding efficient query executions.

6 SQL Components uDDL – Data definition language wDefining the relational schema – relations, attributes, domains (the meta-data) wDropping/altering the relational schema u DML – Data manipulation language wDefining the queries against the schema wInserting, deleting and modifying data uOthers wIntegrity (allowable values/referential) wCatalog and dictionary facilities wTransaction control (long-duration and batch) wAuthorization (who can do what when)

7 Our Running Example uAll our SQL queries will be based on the following database schema. wUnderline indicates key attributes. SCHEMA BeerWorld Beers(name, manf) Bars(name, addr, license) Drinkers(name, addr, phone) Likes(drinker, beer) Sells(bar, beer, price) Frequents(drinker, bar)

8 Data Definition Language - DDL uA Pre-Defined set of Primitive Types wNumeric wCharacter-string wBit-string wAdditional Types uDefining Domains uDefining Schema uDefining Tables uDefining Views uNote: Each DBMS May have their Own DBMS Specific Data Types

9 Primitive Types uNumeric wINTEGER (or INT), SMALLINT wREAL, DOUBLE PRECISION wFLOAT(N) Floating Point with at Least N Digits wDECIMAL(P,D) (DEC(P,D) or NUMERIC(P,D)) have P Total Digits with D to Right of Decimal uNote that INTs and REALs are Machine Dependent (Based on Hardware/OS Platform)

10 Primitive Types uCharacter-String wCHAR(N) or CHARACTER(N) - Fixed wVARCHAR(N), CHAR VARYING(N), or CHARACTER VARYING(N) Variable with at Most N Characters uBit-Strings wBIT(N) Fixed wVARBIT(N) or BIT VARYING(N) Variable with at Most N Bits

11 Primitive Types uThese Specialized Primitive Types are Used to: wSimplify Modeling Process wInclude “Popular” Types wReduce Composite Attributes/Programming uDATE : YYYY-MM-DD uTIME: HH-MM-SS

12 What are Domains? uDomains are Similar in Concepts to Programming Language Type Definitions uA Domain can be Defined as Follows: CREATE DOMAIN DrinkerName CHAR(25) DEFAULT ‘Joe’; CREATE DOMAIN BeerName CHAR(20); uAdvantage of Using Domains wChanging a Domain Definition in One Place Changes it Consistently Everywhere it is Used wDefault Values Can Be Defined for Domains wConstraints Can Be Defined for Domains

13 Dropping a Domain uA Domain is Dropped As Follows: DROP DOMAIN DrinkerName RESTRICT; DROP DOMAIN BeerName CASCADE; uRestrict: wDrop Operation Fails If the Domain is Used in Column Definitions uCascade: wDrop Operation Causes Columns to be Defined Directly on the Underlying Data Type

14 What is a SQL Schema? uA Schema in SQL is the Major Meta-Data Construct uSupports the Definition of: wRelation - Table with Name wAttributes - Columns and their Types wIdentification - Primary Key wConstraints - Referential Integrity (FK) uTwo Part Definition wCREATE Schema - Named Database or Conceptually Related Tables wCREATE Table - Individual Tables of the Schema

15 Create/Drop Schema uFor schema BeerWorld SQL: CREATE SCHEMA BeerWorld Authorization Indra; uDrop schema BeerWorld SQL: DROP SCHEMA BeerWorld RESTRICT; DROP SCHEMA BeerWorld CASCADE; wRestrict: Drop Operation Fails If Schema is Not Empty wCascade: Drop Operation Removes Everything in the Schema

16 Create Table u Create table Drinkers Drinkers(name, addr, phone) CREATE TABLE Drinkers( nameVARCHAR(25), addrVARCHAR(40), phoneCHAR(10), PRIMARY KEY(name) );

17 Create Table uDefault value: gives the default value for a column/attribute Example: name VARCHAR(25) DEFAULT ‘Joe’ uConstraint: gives the constraint to the column/attribute. It can be used for: wSpecifying the primary key/foreign key wSpecifying column that can’t have the null value wPreserving the integrity of the database Deleting the record Modifying the value of primary key SET DEFAULT, SET NULL, CASCADE

18 Create Table uCreate table Drinkers(name, addr, phone) CREATE TABLE Drinkers( name VARCHAR(25) NOT NULL, …, CONSTRAINT pkDrinkers PRIMARY KEY(name) ); uCreate table Sells(bar, beer, price) CREATE TABLE Sells( barVARCHAR(25) NOT NULL, beer VARCHAR(25) NOT NULL, priceDECIMAL(10,2) NOT NULL, CONSTRAINT pkBar FOREIGN KEY(bar) REFERENCES Bars(name) ON UPDATE CASCADE, CONSTRAINT pkBeer FOREIGN KEY(beer) REFERENCES Beers(name) ON UPDATE CASCADE ); Constraint name

19 Drop Tables uCommand: DROP TABLE Drinkers RESTRICT; DROP TABLE Sells CASCADE; uRestrict: wDrop Operation fails if the Table is Referenced by View and/or Constraint Definitions uCascade: wDrop Operation Removes Referencing View and Constraint Definitions

20 Alter Table uChange the table structures: wAdding or dropping column wChanging column definition wAdding or dropping table constraint uAdding column “job” in table “Drinkers”: ALTER TABLE Drinkers ADD job VARCHAR(20); uDropping column “job” in table “Drinkers”: ALTER TABLE Drinkers DROP job CASCADE; ALTER TABLE Drinkers DROP job RESTRICT; wRestrict: Drop Operation Fails if Column is Referenced wCascade: Drop Operation Removes Referencing View and Constraint Definitions

21 Basic Query In SQL

22 Basic Query in SQL uThe principal form of a query is: SELECT desired attributes FROM one or more tables WHERE condition about tuples of the tables GROUP BY attribute list HAVING condition ORDER BY attribute list Basic Query

23 Example uUsing Beers(name, manf), what beers are made by Anheuser-Busch? SELECT name FROM Beers WHERE manf = ‘Anheuser-Busch’;

24 Result of Query name ‘Bud’ ‘Bud Lite’ ‘Michelob’ The answer is a relation with a single attribute, name, and tuples with the name of each beer by Anheuser-Busch, such as Bud.

25 Meaning of Single-Relation Query uBegin with the relation in the FROM clause. uApply the selection indicated by the WHERE clause. uApply the extended projection indicated by the SELECT clause.

26 Operational Semantics uTo implement this algorithm think of a tuple variable ranging over each tuple of the relation mentioned in FROM. uCheck if the “current” tuple satisfies the WHERE clause. uIf so, compute the attributes or expressions of the SELECT clause using the components of this tuple.

27 * In SELECT clauses uWhen there is one relation in the FROM clause, * in the SELECT clause stands for “all attributes of this relation.” uExample using Beers(name, manf): SELECT * FROM Beers WHERE manf = ‘ Anheuser-Busch ’;

28 Result of Query: namemanf ‘Bud’‘Anheuser-Busch’ ‘Bud Lite’‘Anheuser-Busch’ ‘Michelob’‘Anheuser-Busch’ Now, the result has each of the attributes of Beers.

29 Renaming Attributes uIf you want the result to have different attribute names, use “AS ” to rename an attribute. uExample based on Beers(name, manf): SELECT name AS beer, manf FROM Beers WHERE manf = ‘Anheuser-Busch’

30 Result of Query: beermanf ‘Bud’‘Anheuser-Busch’ ‘Bud Lite’‘Anheuser-Busch’ ‘Michelob’‘Anheuser-Busch’

31 Expressions in SELECT Clauses uAny expression that makes sense can appear as an element of a SELECT clause. uExample: from Sells(bar, beer, price): SELECT bar, beer, price*8000 AS prcInRupiah FROM Sells;

32 Result of Query barbeerprcInRupiah Joe’sBud40000 Sue’sMiller56000 … … …

33 Another Example: Constant Expressions uFrom Likes(drinker, beer): SELECT drinker, ‘likes Bud’ AS whoLikesBud FROM Likes WHERE beer = ‘Bud’;

34 Result of Query drinkerwhoLikesBud ‘Sally’‘likes Bud’ ‘Fred’‘likes Bud’ …

35 Complex Conditions in WHERE Clause uFrom Sells(bar, beer, price), find the price Joe’s Bar charges for Bud: SELECT price FROM Sells WHERE bar = ‘Joe’’s Bar’ AND beer = ‘Bud’;

36 Important Points uTwo single quotes inside a string represent the single-quote (apostrophe). uConditions in the WHERE clause can use AND, OR, NOT, and parentheses in the usual way boolean conditions are built. uSQL is case-insensitive. In general, upper and lower case characters are the same, except inside quoted strings.

37 Patterns uWHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches. uGeneral form: LIKE or NOT LIKE uPattern is a quoted string with % = “any string”; _ = “any character.”

38 Example uFrom Drinkers(name, addr, phone) find the drinkers with exchange 555: SELECT name FROM Drinkers WHERE phone LIKE ‘%555-_ _ _ _’;

39 NULL Values uTuples in SQL relations can have NULL as a value for one or more components. uMeaning depends on context. Two common cases: wMissing value : e.g., we know Joe’s Bar has some address, but we don’t know what it is. wInapplicable : e.g., the value of attribute spouse for an unmarried person.

40 Comparing NULL’s to Values uThe logic of conditions in SQL is really 3- valued logic: TRUE, FALSE, UNKNOWN. uWhen any value is compared with NULL, the truth value is UNKNOWN. uBut a query only produces a tuple in the answer if its truth value for the WHERE clause is TRUE (not FALSE or UNKNOWN).

41 Surprising Example uFrom the following Sells relation: barbeerprice Joe’s BarBudNULL SELECT bar FROM Sells WHERE price = 2.00; UNKNOWN

42 Exercise uList the name of all drinkers uList the name of beers started by ‘Bin’ uIs the syntax of this query correct or not? Select 1 as tag, drinker From Likes Where beer <> ‘Anheuser-Busch’ Select name From Drinkers Select name From Beers Where name Like ‘Bin%’

43 Exercise uFind the name of bars selling ‘Anheuser- Busch’ with price less than $5 uFind the name of bars started with ‘Zanz’ selling ‘Bir Bintang’ Select bar From Sells Where beer = ‘Anheuser-Busch’ and price < 5 Select bar From Sells Where bar like ‘Zanz%’ and beer = ‘Bir Bintang’