Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Structured Query Language (SQL)

Similar presentations


Presentation on theme: "Introduction to Structured Query Language (SQL)"— Presentation transcript:

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

2 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, …

3 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) DATE and TIME Currency

4 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;

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

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

7 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’);

8 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);

9 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.

10 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.

11 Deleting Tables DROP Table R;

12 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;

13 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.

14 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

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

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

17 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;

18 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

19 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

20 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

21 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.

22 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

23 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#

24 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

25 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

26 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 > )

27 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.

28 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 )

29 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);

30 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’);

31 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

32 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’) );

33 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.

34 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)

35 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

36 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;

37 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;

38 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;

39 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

40 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.

41 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’;

42 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;

43 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’;

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


Download ppt "Introduction to Structured Query Language (SQL)"

Similar presentations


Ads by Google