SQL. 1.SQL is a high-level language, in which the programmer is able to avoid specifying a lot of data-manipulation details that would be necessary in.

Slides:



Advertisements
Similar presentations
SQL Query Examples Database Management COP4540, SCS, FIU.
Advertisements

SQL Queries Principal form: SELECT desired attributes FROM tuple variables –– range over relations WHERE condition about tuple variables; Running example.
Oracle Labs ECS 242, 342, 360 –You can connect from home to the machines in the lab. –E.g.: ssh u-knoppix.csc.uvic.ca Execute “sh” to use the proper shell.
SQL This presentation will cover: A Brief History of DBMS View in database MySQL installation.
Database Modifications CIS 4301 Lecture Notes Lecture /30/2006.
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.
Algebraic and Logical Query Languages Spring 2011 Instructor: Hassan Khosravi.
1 Database Systems Relations as Bags Grouping and Aggregation Database Modification.
Midterm Review II. Redundancy. –Information may be repeated unnecessarily in several tuples. –E.g. length and filmType. Update anomalies. –We may change.
Subqueries Example Find the name of the producer of ‘Star Wars’.
Indexes. An index on an attribute A of a relation is a data structure that makes it efficient to find those tuples that have a fixed value for attribute.
Query Compiler By:Payal Gupta Roll No:106(225) Professor :Tsau Young Lin.
IS698: Database Management Min Song IS NJIT. Overview  Query processing  Query Optmization  SQL.
Relational Algebra on Bags A bag is like a set, but an element may appear more than once. –Multiset is another name for “bag.” Example: {1,2,1,3} is a.
CMSC424: Database Design Instructor: Amol Deshpande
CMSC424: Database Design Instructor: Amol Deshpande
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #3.
SQL SQL 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.
Database Modifications A modification command does not return a result as a query does, but it changes the database in some way. There are three kinds.
Joins Natural join is obtained by: R NATURAL JOIN S; Example SELECT * FROM MovieStar NATURAL JOIN MovieExec; Theta join is obtained by: R JOIN S ON Example.
SQL By: Toan Nguyen. Download Download the software at During the installation –Skip sign up for fast installation.
Chapter 6 The database Language SQL Spring 2011 Instructor: Hassan Khosravi.
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.
Dr. T. Y. Lin | SJSU | CS 157A | Fall 2011 Chapter 6 THE DATABASE LANGUAGE SQL 1.
Relational Algebra CIS 4301 Lecture Notes Lecture /28/2006.
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.
Databases : SQL-Introduction 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes.
CS 255: Database System Principles slides: From Parse Trees to Logical Query Plans By:- Arunesh Joshi Id:
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Introduction to Data Manipulation in SQL CIS 4301 Lecture Notes Lecture /03/2006.
Introduction to Indexes. Indexes An index on an attribute A of a relation is a data structure that makes it efficient to find those tuples that have a.
THE DATABASE LANGUAGE SQL
Databases 1 Second lecture.
1 More SQL uDatabase Modification uDefining a Database Schema uViews.
Referential Integrity checks, Triggers and Assertions Examples from Chapter 7 of Database Systems: the Complete Book Garcia-Molina, Ullman, & Widom.
© D. Wong Normalization  Purpose: process to eliminate redundancy in relations due to functional or multi-valued dependencies.  Decompose relation.
More Relation Operations 2014, Fall Pusan National University Ki-Joune Li.
1 Algebra of Queries Classical Relational Algebra It is a collection of operations on relations. Each operation takes one or two relations as its operand(s)
1 CSCE Database Systems Anxiao (Andrew) Jiang The Database Language SQL.
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.
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.
1 Chapter 6 More SQL uDatabase Modification uDefining a Database Schema uViews.
SQL Exercises – Part I April
The Relational Model of Data Prof. Yin-Fu Huang CSIE, NYUST Chapter 2.
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.
The Database Language SQL Prof. Yin-Fu Huang CSIE, NYUST Chapter 6.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Relational Algebra Chapter 4, Part A.
Databases : SQL Multi-Relations 2007, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman.
1 SQL: Concept and Usage. 2 SQL: an Overview SQL (Structured Query Language) –Also be pronounced as “sequel” –A relational database language –Consists.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
Subqueries CIS 4301 Lecture Notes Lecture /23/2006.
Select-From-Where Statements Multirelation Queries Subqueries
CPSC-310 Database Systems
Computational Biology
Chap 5. The DB Language (SQL)
THE DATABASE LANGUAGE SQL
Introduction to Structured Query Language (SQL)
THE RELATIONAL MODEL OF DATA
Chap 2. The Relational Model of Data
Introduction to Database Systems, CS420
CPSC-608 Database Systems
SQL: Concept and Usage.
2018, Fall Pusan National University Ki-Joune Li
SQL This presentation will cover: View in database MySQL installation
CS4433 Database Systems SQL - Basics.
CPSC-608 Database Systems
Query Compiler By:Payal Gupta Shirali Choksi Professor :Tsau Young Lin.
Select-From-Where Statements Multirelation Queries Subqueries
Presentation transcript:

SQL

1.SQL is a 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++. 2.What makes SQL viable is that its queries are “optimized” quite well, yielding efficient query executions.

Select-From-Where Statements Principal form of a query is: SELECT desired attributes FROM one or more tables WHERE condition about tuples of the tables 1.Begin with the relation in the FROM clause. 2.Apply the selection indicated by the WHERE clause. 3.Apply the extended projection indicated by the SELECT clause.

Running Example Our SQL queries will be based on the following database schema. Movie(title, year, length, inColor, studioName, producerC) StarsIn(movieTitle, movieYear, starName) MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, netWorth) Studio(name, address, cert#, netWorth) Example: Find all movies produced by Disney in SELECT * FROM Movie WHERE studioName = 'Disney' AND year = 1990;

(Extended) Projection in SQL SELECT title, length FROM Movie WHERE studioName = 'Disney' AND year = 1990; SELECT title AS name, length AS duration FROM Movie WHERE studioName = 'Disney' AND year = 1990; SELECT title AS name, length* AS lenghtInHours FROM Movie WHERE studioName = 'Disney' AND year = 1990; SELECT title AS name, length/60 AS length, 'hrs.' AS inHours FROM Movie WHERE studioName = 'Disney' AND year = 1990;

Selection in SQL The selection of the relational algebra is expressed through the WHERE clause of SQL. We may build expressions by using the operators: =, <>,, = String constants are surrounded by single quotes. –studioName = 'Disney' Numeric constants are for e.g.: , 1.23E45 Boolean operators are: AND, OR, NOT. Example Which movies are made after 1970 and aren't in color? SELECT title FROM Movie WHERE (year > 1970) AND NOT (inColor='C');

Selection in SQL (Cont.) Which Disney movies are after 1970 or have length greater than 90 mins? SELECT title FROM Movie WHERE (year > 1970 OR length < 90) AND studioName='Disney'; Parenthesis are needed because the precedence of OR is less than that of AND.

Comparison of strings Strings can be compared (lexicographically) with the same operators: = <> < > <= >= For instance ‘fodder’<‘foo’ ‘bar’ < ‘bargain’

Patterns WHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches. General form: LIKE or NOT LIKE is a quoted string which may contain % = meaning “any string” _ = meaning “any character.” Example. Suppose we remember a movie “Star something”. SELECT title FROM Movie WHERE title LIKE 'Star %'; Apostrophes. Two consecutive apostrophes represent one apostrophe and not the end of the string. E.g. SELECT title FROM Movie WHERE title LIKE '%''s%';

Patterns (Continued) What if the pattern we wish to use in a LIKE expression involves the characters % or _? –We should “escape” their special meaning proceeding them by some escape character. –In UNIX and C we use backslash \ as the escape character. –SQL allows us to use any character we like. s LIKE 'x%x%' ESCAPE 'x' –x will be the escape character. –A string that is matched by this pattern is for example: %aaaa% Example SELECT title FROM Movie WHERE title LIKE 'x%x%' ESCAPE 'x';

Ordering the Input We may ask the tuples produced by a query to be presented in sorted order. ORDER BY Example. Find the Disney movies of List them by length, shortest first, and among movies of equal length, sort alphabetically –Movie(title, year, length, inColor, studioName, producerC#) SELECT * FROM Movie WHERE studioName = 'Disney' ORDER BY length, title; Remarks Ordering is ascending, unless you specify the DESC keyword after an attribute. Ties are broken by the second attribute on the ORDER BY list, etc.

NULL Values Tuples in relations can have NULL as a value for one or more components. Meaning depends on context. Two common cases: –Missing value: e.g., we know the length has some value, but we don’t know what it is. –Inapplicable: e.g., the value of attribute spouse for an unmarried person.

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

Three-Valued Logic To understand how AND, OR, and NOT work in 3- valued logic, think of –TRUE = 1, FALSE = 0, and UNKNOWN = ½. –AND = MIN –OR = MAX –NOT(x) = 1-x Example: TRUE AND (FALSE OR NOT(UNKNOWN)) = MIN(1, MAX(0, (1 - ½ ))) = MIN(1, MAX(0, ½ )) = MIN(1, ½ ) = ½.

Surprising Example SELECT * FROM Movie WHERE length 120; Suppose that we have some NULL values in the length. What’s the result?

Products and Joins in SQL SQL has a simple way to couple relations in one query: list each relation in the FROM clause. –All the relations in the FROM clause are coupled through Cartesian product –Then we can put conditions in the WHERE clause in order to get the various kinds of join. Example. We want to know the name of the producer of Star Wars. To answer we need the information from both: –Movie(title, year, length, inColor, studioName, producerC) –MovieExec(name, address, cert, netWorth) SELECT name FROM Movie, MovieExec WHERE title = 'Star Wars' AND producerC = cert;

Disambiguating Attributes When we involve two or more relations in a query, we can have attributes with the same name among these relations. –Solution: Disambiguate by putting the name of the relation followed by a dot and then the name of the attribute. Example. Find pairs (star, movie executive) living in the same address. –MovieStar(name, address, gender, birthdate) –MovieExec(name, address, cert, netWorth) SELECT MovieStar.name, MovieExec.name FROM MovieStar, MovieExec WHERE MovieStar.address = MovieExec.address;

Aliases Sometimes we need to ask a query that combines a relation with itself. –We may list a relation R as many times we want in the from clause but we need a way to refer to each occurrence of R. –SQL allows us to define, for each occurrence in the FROM clause, an alias (which is called “tuple variable”). Example. We like to know about two stars who share an address. –MovieStar(name, address, gender, birthdate) SELECT Star1.name, Star2.name FROM MovieStar AS Star1, MovieStar AS Star2 WHERE Star1.address = Star2.address AND Star1.name < Star2.name; Remark: Don’t put ‘AS’ in Oracle. Why not use <> instead?

Joins Natural join is obtained by: R NATURAL JOIN S; Example SELECT * FROM MovieStar NATURAL JOIN MovieExec; Theta join is obtained by: R JOIN S ON Example SELECT * FROM MovieStar JOIN MovieExec ON moviestar.name = movieexec.name; In ORACLE it is used in FROM

Outerjoins SELECT * FROM moviestar NATURAL FULL OUTER JOIN movieexec; SELECT * FROM moviestar NATURAL LEFT OUTER JOIN movieexec; SELECT * FROM moviestar NATURAL RIGHT OUTER JOIN movieexec; One of LEFT, RIGHT, or FULL before OUTER (but not missing). uLEFT = pad dangling tuples of R only. uRIGHT = pad dangling tuples of S only. uFULL = pad both.

Remark If we had used <> then we would have produced pairs of married stars twice, like: Star1.name Star2.name Alec BaldwinKim Basinger Kim BasingerAlec Baldwin

Connection with Relational Algebra 1.Start with the relations in the FROM clause and take their Cartesian Product. 2.Having created the product, apply a selection to it by converting the WHERE clause to a selection condition. 3.Finally with the list of attributes in the SELECT clause do a projection.

An Unintuitive Consequence of SQL semantics Suppose R, S, T are relations each having attribute A alone. We wish to compute R  (S  T), which is (R  S)  (R  T). We might expect the following SQL query to do the job. SELECT R.A FROM R, S, T WHERE R.A = S.A OR R.A = T.A However, consider the situation in which T is empty. –Since R.A = T.A can never be satisfied, we might expect the query to produce exactly R  T. But using the Relational Algebra interpretation the result is empty. –Cartesian product R x S x T is .

Union, Intersection, and Difference of Queries If two SQL queries produce relations with the same set of attributes then we can combine the queries using the set operations: UNION, INTERSECT and EXCEPT. Example. Find the names and addresses of all female movie stars who are also movie executives with a net worth over $1,000,000. –MovieStar(name, address, gender, birthdate) –MovieExec(name, address, cert, netWorth) (SELECT name, address FROM MovieStar WHERE gender = 'F') INTERSECT (SELECT name, address FROM MovieExec WHERE netWorth > );

Union, Intersection, and Difference of Queries (Continued) Example. Give the names and addresses of movie stars who are not also movie executives. (SELECT name, address FROM MovieStar) EXCEPT (SELECT name, address FROM MovieExec); Example. We want all the titles and years of movies that appeared in either the Movie or StarsIn relation. (SELECT title, year FROM Movie) UNION (SELECT title, year FROM StarsIn); In ORACLE use MINUS.