Introduction to Structured Query Language (SQL)

Slides:



Advertisements
Similar presentations
SQL Introduction Standard language for querying and manipulating data Structured Query Language Many standards out there: SQL92, SQL2, SQL3. Vendors support.
Advertisements

SQL Query Examples Database Management COP4540, SCS, FIU.
SQL This presentation will cover: A Brief History of DBMS View in database MySQL installation.
Database Modifications CIS 4301 Lecture Notes Lecture /30/2006.
SQL reviews. Stored Procedures Create Procedure Triggers.
Database Modifications, Data Types, Views. Database Modifications A modification command does not return a result as a query does, but it changes the.
Database Modifications, Data Types, Views. Database Modifications A modification command does not return a result as a query does, but it changes the.
Subqueries Example Find the name of the producer of ‘Star Wars’.
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.
CMSC424: Database Design Instructor: Amol Deshpande
Movies length titleyearfilmType Voices isa Cartoons isa MurderMystery weapon toStar Our Movie Example.
1 CMSC424, Spring 2005 CMSC424: Database Design Lecture 7.
CMSC424: Database Design Instructor: Amol Deshpande
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.
Correlated Queries SELECT title FROM Movie AS Old WHERE year < ANY (SELECT year FROM Movie WHERE title = Old.title); Movie (title, year, director, length)
SQL By: Toan Nguyen. Download Download the software at During the installation –Skip sign up for fast installation.
1 Relational Data Model CS 157B Nidhi Patel. 2 What is a Data Model? A notation for describing data or information A notation for describing data or information.
Chapter 6 The database Language SQL Spring 2011 Instructor: Hassan Khosravi.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Dr. T. Y. Lin | SJSU | CS 157A | Fall 2011 Chapter 6 THE DATABASE LANGUAGE SQL 1.
3.1 Chapter 3: SQL Schema used in examples p (omit 3.8.2, , 3.11)
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.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Relational Algebra Spring 2012 Instructor: Hassan Khosravi.
SQL 2015, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes via his course web.
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.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
THE DATABASE LANGUAGE SQL
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.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
© D. Wong Normalization  Purpose: process to eliminate redundancy in relations due to functional or multi-valued dependencies.  Decompose relation.
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 Chapter 6 More SQL uDatabase Modification uDefining a Database Schema uViews.
SQL Exercises – Part I April
Oracle & SQL. Oracle Data Types Character Data Types: Char(2) Varchar (20) Clob: large character string as long as 4GB Bolb and bfile: large amount of.
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.
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.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL Query Getting to the data ……..
Chapter 3 Introduction to SQL
Chap 5. The DB Language (SQL)
Introduction to SQL.
THE DATABASE LANGUAGE SQL
THE RELATIONAL MODEL OF DATA
Chap 2. The Relational Model of Data
SQL: Concept and Usage.
2018, Fall Pusan National University Ki-Joune Li
SQL This presentation will cover: View in database MySQL installation
Database systems Lecture 3 – SQL + CRUD
SQL Introduction Standard language for querying and manipulating data
Lecture 12: SQL Friday, October 20, 2000.
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
CS4433 Database Systems SQL - Basics.
SQL: Structured Query Language
SQL – Constraints & Triggers
Query Compiler By:Payal Gupta Shirali Choksi Professor :Tsau Young Lin.
CPSC 315 – Programming Studio Spring 2017 Project 1, Part 3
Presentation transcript:

Introduction to Structured Query Language (SQL) Chulsoon Park Industrial & Systems Engineering Changwon National Univ.

Components of SQL Have statements for Schema definition & update tables, indexes, views, … Data Manipulation query(selection), insertion, deletion, update, … Data integrity constraints, … System administration users, data security, performance tuning, … Application development procedures, transaction, embedded SQL, … …

Data Types (SQL Server 2000) String CHAR(n) : fixed-length string of n characters. - padding blanks VARCHAR(n): string of up to n characters. Integer: INT or INTEGER Floating points: FLOAT (REAL), DOUBLE PRECISION, DECIMAL(6,2) - 0123.45 DATE and TIME Currency …

Simple Table Creation CREATE TABLE MovieStar(name, address, gender, birthdate) Table Creation Use Course; CREATE TABLE MovieStar( name CHAR(30) Primary Key, address VARCHAR(255), gender CHAR(1), birthdate DATE ); Go;

Default Values CREATE TABLE MovieStar ( name CHAR(30) Primary Key, address VARCHAR(255), gender CHAR(1) DEFAULT ‘M’, birthdate DATE DEFAULT DATE ‘0000-00-00’ );

Database Modifications Insert tuples into a relation / table Delete certain tuples from a relation / table Update values in a table

Insertion 1 INSERT INTO R(A1,…,An) VALUES (V1,…,Vn); Ex) INSERT INTO StarsIn(movieTitle, movieYear, starName) VALUES(‘Return of the Jedi’, 1983, ‘Harrison Ford’); If we provide values for all attributes, INSERT INTO StarsIn VALUES (‘Return of the Jedi’, 1983, ‘Harrison Ford’);

Insertion 2 Using Subqueries: We want to add to relation Studio(name, address, presC#) all movie studios that are mentioned in Movie(.., studioName,..) INSERT INTO Studio(name) SELECT DISTINCT studioName FROM Movie WHERE studioName NOT IN (SELECT name FROM Studio);

Deletion DELETE FROM Relation WHERE <condition>; DELETE FROM StarsIn WHERE movieTitle = ‘Return of the Jedi’ AND movieYear = 1983 AND starName = ‘Harrison Ford’; DELETE FROM MovieExec WHERE netWorth < 10,000,000; Insertion: make duplicates Deletion: delete all duplicates if they should be deleted.

Updates UPDATE R SET <new-value assignments> WHERE <condition>; MovieExec(name, address, cert#, netWorth) Update all names of movie executives into ‘Pres. ____’ if they are presidents of certain studio!! UPDATE MovieExec SET name = ‘Pres. ’ || name WHERE cert# IN (SELECT presC# FROM Studio); || : concatenation operator.

Deleting Tables DROP Table R;

Modifying Relation Schemas MovieStar(name, address, gender, birthdate) ALTER TABLE MovieStar ADD phone CHAR(16); The value of phone for each existing tuple is set to ‘NULL’. ALTER TABLE MovieStar DROP COLUMN birthdate;

Simple Queries in SQL Asking for those tuples (records) of some one relation that satisfy a condition: “Selection” Example Movie(title, year, length, inColor, studioName, producerC#) “Select all movies produced by Disney in 1990”. SELECT * FROM Movie WHERE studioName = ‘Disney’ AND year = 1990; FROM: relation (table) name. WHERE: condition. SELECT: which attributes? ‘*’ means the entire tuple.

Projection in SQL - 1 Using ‘SELECT’ clause. SELECT title, length FROM Movie WHERE studioName = ‘Disney’ AND year = 1990; The result has two attributes title and length. SELECT title AS name, length AS duration

Projection in SQL - 2 Formula in ‘SELECT’ clause Constant as an item SELECT title AS name, length *0.016667 AS lengthInHours Constant as an item to put some useful words into the output that SQL displays. SELECT title, length*0.016667 AS length, ‘hrs.’ AS inHours FROM Movie WHERE studioName = ‘Disney’ AND year = 1990;

Case Insensitivity SELECT… FROM… WHERE… select … from … where … but, ‘RABBIT’ and ‘rabbit’ are different character strings.

Selection in SQL - 1 Expressions in WHERE clause Comparison operators: =, <>, <, >, <=, and >= Constants and attributes of the relations. Arithmetic operators: +, *, -, / Concatenation operator: + ‘foo’ + ‘bar’ => ‘foobar’ Logical operators: AND, OR, NOT String: surrounded by single quotes ‘ ‘ The result of a comparison: boolean value (TRUE or FALSE) Example Movies made after 1970 that are in black-and-white. SELECT title FROM Movie WHERE year > 1970 AND NOT inColor;

Selection in SQL - 2 Expressions in WHERE clause Example titles of movies made by MGM Studios that where either made after 1970 or where less than 90 minutes long. SELECT title FROM Movie WHERE (year > 1970 OR length < 90) AND studioName = ‘MGM’; Precedence of logical operators NOT > AND > OR

Comparisons of Strings Two strings are equal if they are the same sequence of characters. Note that the case is sensitive !!! Two types of strings fixed-length variable-length Comparison lexicographic order

Pattern comparison - LIKE LIKE operator % : any zero or more characters. _ : any single character. Examples SELECT title FROM Movie WHERE title LIKE ‘Star ____’ -> Star Wars and Star Trek WHERE title LIKE ‘%’’s%’ -> Logan’s Run or Alice’s Restaurant 4 _’s

Date and Times DATE ‘1948-05-14’ TIME ‘15:00:02’ TIME ‘23:35:40.5’ Comparison operators can be used to compare date and times.

Ordering the Output ORDER BY <list of attributes> DESC : descending ASC : ascending (by defaults) Movie(title, year, length, inColor, studioName, producerC#) SELECT * FROM Movie WHERE studioName = ‘Disney’ AND year = 1990 ORDER BY length, title ORDER BY 3, 1

Products and Joins in SQL List each relation (table) in the FROM clause SELECT and WHERE clause can refer to the attributes of any of the relations in the FROM clause 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 two or more attributes (in different relation) have the same name. MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, netWorth) Find pairs consisting of a star and an executive with the same address. SELECT MovieStar.name, MovieExec.name FROM MovieStar, MovieExec WHERE MovieStar.address = MovieExec.address

Intersection 1 Exists 사용 Select a.name from A a where exists (select name from B where id=a.id) Inner Join Query 사용 Select a.name from A a inner join B b on a.id = b.id where xxxx Question ? MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, netWorth) Find the names and addresses of all female movie stars who are also movie executives with a net worth over $10,000,000

Intersection 2 Answer MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, netWorth) Find the names and addresses of all female movie stars who are also movie executives with a net worth over $10,000,000 select name, address from MovieStar a where exists ( from MovieExec where a.name = name and a.address = address and a.gender = 'F' and netWorth > 1000000 )

Difference 1 Select a.name from A a where not exists (select name from B where id=a.id) Question MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, netWorth) Find the names and addresses of movie stars who are not also movie executives regardless of gender or net worth.

Difference 2 Answer MovieStar(name, address, gender, birthdate) MovieExec(name, address, cert#, netWorth) Find the names and addresses of movie stars who are not also movie executives regardless of gender or net worth. select name, address from MovieStar a where not exists ( from MovieExec where a.name = name and a.address = address )

Union Example Movie(title, year, length, inColor, studioName, producerC#) StarsIn(movieTitle, movieYear, starName) All movies mentioned in either relation (SELECT title, year FROM Movie) UNION (SELECT movieTitle AS title, movieYear AS year FROM StarsIn);

Subqueries Subquery: Expression that evaluates to a relation. Ex) SELECT-FROM-WHERE expression. Subqueries that produce scalar values Result is a single-value of single-attribute Movie(title, year, length, inColor, studioName, producerC#) MovieExec(name, address, cert#, netWorth) SELECT name FROM Movie, MovieExec WHERE title = ‘Star Wars’ AND producer C# = cert# FROM MovieExec WHERE cert# = (SELECT producerC# FROM Movie WHERE title = ‘Star Wars’);

Conditions Involving Relations SQL operators applying to a relation R and produce a Boolean result. EXISTS R : TRUE if and only if R is not empty. s In R : TRUE if and only if s is a value in R. R is a unary (one-attribute) relation. s > ALL R : TRUE if and only if s is greater than every value in unary relation R. s > ANY R : TRUE if and only if s is greater than at least one value in unary relation R. c.f.) s <> R s = ANY R NOT EXIST R NOT s > ALL R NOT s > ANY R

Conditions Involving Tuples Tuple in SQL: parenthesized list of scalar values. Ex) constants: (123,’foo’), attributes: (name, address, networth) Mixing of constants and attributes is allowed. Compare a tuple t and relation R: when t has the same # of components as R. Ex) t IN R, t <> ANY R SELECT name FROM MovieExec WHERE cert# IN (SELECT producerC# FROM Movie WHERE (title, year) IN (SELECT movieTitle, movieYear FROM StarsIn WHERE starName = ‘Harrison Ford’) );

Duplicates SQL basically permit duplicated tuples. Thus, SQL is not set-based but bag-based. Eliminating Duplicates Use “SELECT DISTINCT” Union, Intersection, Difference operations: normally eliminate duplicates. If we wish to preserve duplicates, use “UNION ALL”, “INTERSECTION ALL”, “EXCEPT ALL”. Duplicates elimination is very expensive. Relation must be sorted. Sorting time is usually greater than query time.

Aggregation Aggregation Operators Ex) SUM: the sum of the values in this column. AVG: the average of values in this column. MIN, MAX: the least, greatest value in the column. COUNT: the number of values (c.f.: COUNT DISTINCT) Ex) SELECT AVG(netWorth) FROM MovieExec; SELECT COUNT(*) SELECT COUNT(DISTINCT name)

Grouping - 1 We want generate the following table. SELECT studioName, SUM(length) FROM Movie GROUP BY studioName; SELECT studioName GROUP BY studioName Exactly same as above query: SELECT DISTINCT studioName

Grouping - 2 Grouping with several relations Sequence of steps Cartesian product (theta-join) GROUP BY Generate aggregation. Listing each producer’s total length of film produced. Movie(title, year, length, inColor, studioName, producerC#) MovieExec(name, address, cert#, netWorth) SELECT name, SUM(length) FROM MovieExec, Movie WHERE producer# = cert# GROUP BY name;

HAVING Clauses Sometimes, we want to choose our groups based on some aggregate property. Total film length for only those producers who made at least one film prior to 1930: SELECT name, SUM(length) FROM MovieExec, Movie WHERE producerC# = cert# GROUP BY name HAVING MIN(year) < 1930;

Domains CREATE DOMAIN <name> AS <type description>; CREATE DOMAIN MovieDomain AS VARCHAR(50) DEFAULT ‘unknown’; CREATE TABLE Movie ( title MovieDomain, …. ); ALTER DOMAIN MovieDomain Set DEFAULT ‘no such title’; DROP DOMAIN MovieDomain;

Indices Index on an attribute A Index Examples Data structure that makes it efficient to find those tuples that have a fixed value for attribute A Indices usually help with queries in which A is compared with a constant; ex) A = 3 or A <= 3 Helpful when a relation is very large SELECT * FROM Movie WHERE studioName = ‘Disney’; Index Examples CREATE INDEX YearIndex On Movie(year); CREATE INDEX KeyIndex ON Movie(title, year); Usually, key is used together or unused together. DROP INDEX YearIndex; Trade-off: Queries are speed-up, but insertion, deletion, updates become complex

View Table (by CREATE TABLE) View (by CREATE VIEW) Exists in a database. Saved as a file. Persistent. View (by CREATE VIEW) Do not exist physically. Defined by an expression much like a query. Views can be queried as if they existed physically Views can be modified.

Declaring Views CREATE VIEW <view-name> AS <view-definition>; Create a view: the titles and years of the movies made by Paramount Studios. Movie(title, year, length, inColor, studioName, producerC#) CREATE VIEW ParamountMovie AS SELECT title, year FROM Movie WHERE studioName = ‘Paramount’;

Querying Views - 1 Just as if the view where a stored table. SQL translate the “query to view” into “query to database”. Ex) SELECT title FROM ParamountMovie WHERE year = 1979; => FROM Movie WHERE studioName = ‘Paramount’ AND year = 1979;

Querying Views - 2 Queries involving both views and base table. SELECT DISTINCT starName FROM ParamountMovie, StarsIn WHERE title = movieTitle AND year = movieYear; More complicated example Movie(title, year, length, inColor, studioName, producerC#) MovieExec(name, address, cert#, netWorth) CREATE VIEW MovieProd AS SELECT title, name FROM Movie, MovieExec WHERE producerC# = cert#; SELECT name FROM MovieProd WHERE title = ‘Gone with the wind’; SELECT name FROM Movie, MovieExec WHERE producerC# = cert# AND title = ‘Gone with the wind’;

Renaming View Attributes CREATE VIEW MovieProd (movieTitle, prodName) AS SELECT title, name FROM Movie, MovieExec WHERE producerC# = cert#;