Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Language Review SELECT Statements Instructions for modifying data

Similar presentations


Presentation on theme: "SQL Language Review SELECT Statements Instructions for modifying data"— Presentation transcript:

1 SQL Language Review SELECT Statements Instructions for modifying data
Other Commands and Functions

2 Structured Query Language (SQL)
In 1969, Dr Edgar Codd published an IBM Research Report with the catchy title Derivability, Redundancy, and Consistency of Relations Stored in Large Data Banks. Codd revised the concepts and published them in a 1970 article named "A Relational Model of Data for Large Shared Data Banks" in the Journal of the Association of Computer Machinery. The relational model described by Codd was used in a prototype relational database management system (RDBMS) called System R in 1974. Describing the system’s query language in a November 1976 article in the IBM Journal of R&D, IBM used the name Structured English QUEry Language (SEQUEL).

3 Structured Query Language (SQL)
The first commercially available version of SQL was released in 1979 by Oracle Corporation (although the company's name was Relational Software, Inc. at the time). In 1986, the American National Standards Institute (ANSI) stepped in and published a formal SQL standard, which it identified as ANSI X The International Standards Organization (ISO) picked up this standard the following year and published it as ISO The specification was expanded in 1992, and then again in The current specification is in five parts, named ANSI/ISO/IEC through

4 Interactive and Embedded SQL
Most SQL products allow SQL statements to be executed both: interactively - (i.e., directly from an online terminal). Results are presented directly to the user in a way determined by DBMS. SQL does not contain input/output instructions embedded - as part of an application program (i.e., the SQL statements can be embedded, meaning they can be intermixed with the programming language statements of such a program). In the embedded case, moreover, the application program can typically be written in a variety of host languages; the SQL standard includes support for Ada, C, COBOL, Fortran, Java, Pascal, and PL/I.

5 Components of SQL Basic instructions (“core SQL"'):
SQL = Data Definition Language (DDL) + Data Manipulation Language (DML) Data Control Language (DCL) Basic instructions (“core SQL"'): The Data Definition Language (DDL) commands are used to define how you want your data to be stored; DDL DML DCL CREATE TABLE CREATE VIEW CREATE INDEX ALTER TABLE DROP TABLE DROP VIEW DROP INDEX SELECT INSERT UPDATE DELETE GRANT REVOKE The Data Manipulation Language (DML) commands enable you to work with your data; . The Data Control Language (DCL) commands control who can do what within the database, with object privileges controlling access to individual database objects and system privileges providing global privileges across the entire database

6 CREATE TABLE Types of data: (SQL - 89)
CREATE TABLE <table name > (< column name > < data type > [options] [ < column name > < data type > [options]. ..) [ UNIQUE (< column name >. (< column name >])]...); Aim: Create a new table in database. The user should determine: table name (unique in database), column name (unique in the table), type of data of each column. Types of data: (SQL - 89) INTEGER, SMALLINT – integer number (range depends on DBMS). DECIMAL [(m [, n ])], NUMERIC ((m [, n ])) - real number with m digits before decimal place and n fractional digits. FLOAT [(m)] - real number of m digits REAL - the same as DECIMAL. DOUBLE PRECISION - the same as FLOAT. CHARACTER( n) – string of n characters. DATE - date (usually in format: mm / dd / yy) LOGICAL logic values: yes / NO, true / false.

7 CREATE TABLE Other data types : (SOL -92)
VARCHAR. DATETIME. MONEY. TEXT, IMAGE, BLOB. CLOB.... (details - in DBMS documentation) Options (examples-): NOT NULL [ UNIOUE ] - value in column has to be, if UNIQUE - to unique. UNIOUE (< column > [,< kolumns >]...) - value in column (columns) has to be unique. Every column has to be defined with the option NOT NULL. [NOT] CASE-SENSITIYE – determines when comparing values in char column if the size of letters (lower case and upper case) has to be taken into consideration. COLUMN - LABEL string - the label ( the headline) of the column with tabular display LABEL string - the label of column with free display DEFAULT – initial value - default value of the column. AUTOINCREMENT - causes automatic incrementing by system the values in columns when adding new row to the table. PRIMARY KEY - defines a column as a primary key. REFERENCES [ table name] - defines a column as a foreign key. Details of these options can be found in description CREATE TABLE command in the concrete DBMS.

8 CREATE TABLE - Examples
Command to create a table in database – School CREATE TABLE Teachers (Tno CHAR(3),) NOT NULL UNIQUE, Tname CHAR(12), Title CHAR(6), City CHAR(8), SupNo CHAR(3)); CREATE TABLE Students (Sno CHAR(3) NOT NULL UNIQUE, Sname CHAR(12), Sdate DATE, City CHAR(8)); CREATE TABLE TS (Tno CHAR(3) NOT NULL, Sno CHAR(3) NOT NULL, hours INT, UNIQUE(Tno. Sno));

9 CREATE TABLE - Examples
Using options defining primary keys and foreign keys CREATE TABLE Teachers (Tno CHAR(3) PRIMARY KEY Tname CHAR(12) , Title CHAR(6), City CHAR(8), SupNo CHAR(3) REFERENCES Teachers); CREATE TABLE Students (Sno CHAR(3) PRIMARY KEY, Sname CHAR(12), Sdale DATE, City CHAR(8)); CREATE TABLE TS (Tno CHAR(3) REFERENCES Teachers, Sno CHAR(3) REFERENCES Students, Hours INT, PRIMARY KEY Tno, Sno));

10 Modify the table Examples Aim:
ALTER TABLE <table name> { ADD COLUMN <column> <data type > [options] | DROP COLUMN <column> | ALTER COLUMN <column> {options] } Aim: Adding new column to existing table. New column accepts null values (NULL) Deleting a column from existing table. Changing data in existing column (but not the type of data) Examples ALTER TABLE Students ADD COLUMN PhoneNo Char(13); ALTER TABLE Teachers DROP COLUMN City; ALTER TABLE Teachers ALTER COLUMN Tname LABEL "Name of Teacher";

11 Inserting data into the table
INSERT INTO <table name> [( <list of columns> )] VALUES (< list of values>) Aim: Inserting a new row into the table on basis of some given values. If it has not < the list of columns > then one should give all values, in the same order that columns have in the table. Examples INSERT INTO Teachers VALUES (“T6“, "Taylor“, "Prof.”, "New York", "T1”); INSERT INTO Teachers (TNo.TName, City) VALUES ("T7“, “James”, "Paris");

12 SELECT - SELECT [DISTINCT] <list of columns/expressions>
FROM <list of tables> [ WHERE <condition>] [ GROUP BY <list of columns> ] [HAVING <condition> ] [ UNION <SELECT statement> ] [ ORDER BY <list of columns/numbers> ] the SELECT clause is actually used to do projection, whereas selections in the relational algebra sense are expressed using the WHERE clause! This mismatch between the naming of the selection and projection operators in relational algebra and the syntax of SQL is an unfortunate historical accident. The select-list is a list of (expressions involving) column names of tables named in the from-list. Column names can be prefixed by a range variable. The from-list in the FROM clause is a list of table names. A table name can be followed by a range variable; a range variable is particularly useful when the same table name appears more than once in the from-list.

13 SELECT - The qualification in the WHERE clause is a boolean combination (i.e., an expression using the logical connectives AND, OR, and NOT) of conditions of the form “expression op expression”, where op is one of the comparison operators {<,< = ,= , <>, >=, >}. An expression is a column name, a constant, or an (arithmetic or string) expression. DISTINCT keyword is optional. It indicates that the table computed as an answer to this query should not contain duplicates, that is, two copies of the same row. The default is that duplicates are not eliminated. UNION - Finds the sum of results of two statements SELECT, eliminating duplicates ORDER BY - orders the resulting rows ascending or descending according to the value in specified columns/ expressions

14 SELECT – Simple queries
SELECT [DISTINCT] < list of columns / expressions > FROM < table name > [ WHERE < condition >] Simple query carries out the combination of projection and selection (if the phrase WHERE exists) in relation to one table. Note: < list of columns > can take the form of * (which means choice of all columns). Examples: 1. Find identifiers and names of all teachers. SELECT TNo, TName FROM Teachers; 2. Find names of all cities, where students have come from. SELECT DISTINCT City FROM Students; Attention: Without DISTINCT clause, the names of cities could be duplicated

15 SELECT – Simple queries (cont.)
3 Find information about lectures that lasted over 95 hours. SELECT * FROM TS WHERE Hours > 95 4. Find identifiers and names of teachers from LONDON SELECT TNo, TName FROM Teachers WHERE city = “London”; 5. Find identifiers, titles and names of teachers who has a superior SELECT TNo, Title, TName FROM Teachers WHERE SupNo IS NOT NULL;

16 SELECT – Simple queries (cont.)
Find average number of hours per week for each student who had lectures with the teacher T3 SELECT Sno, Hours/15, “hour per week” FROM TS WHERE Tno = “T3” Result SNO EXP1 EXP2 S1 S2 S3 S4 2.13 2.40 4.00 4.80 hour per week Hour per week

17 Expressions Arithmetic Operators Logic Operators:
Operators in SQL language can be used in expressions of SELECT statements, and other statements like WHERE, INSERT INTO, DELETE,… Arithmetic Operators ** ^ raising to a power * / multiplication, division addition, subtraction Logic Operators: NOT AND OR Special Operators IN BETWEEN LIKE MATCHES Comparison Operators with null value IS NULL IS NOT NULL

18 Expressions (cont.) Aggregation Functions
COUNT() - returns the number of rows chosen in query AVG() - counts arithmetic average in numeric column SUM() adds up the values in numeric column MIN() finds minimum value in column of char, numeric or date type MAX() - finds maximum value, in column of char, numeric or date type Functions Dependent on DBMS Functions operating on dates / hours, strings, text fields, binary objects,...

19 Special Operators IN Checks if the value in column is equal to one of specified (given in the query) values or being the result of the SELECT statement Examples: 1. WHERE City = "London" OR City = “Davos" the OR City = "Bristol“ it is equivalent to WHERE City IN (“London", "Davos", "Bristol") SELECT * FROM Teachers WHERE City IN (SELECT CITY FROM Students); Result: The teachers from the relation Teachers, who are from cities listed in the relation Students.

20 1 . WHERE Hours >= 96 AND Hours <= 126 It is equivalent to
BETWEEN It checks if the value in a given column is contained in some interval of values in this column Examples WHERE Hours >= 96 AND Hours <= 126 It is equivalent to WHERE Hours BETWEEN 96 AND SELECT * FROM Teachers WHERE TName BETWEEN “A” AND “C”; RESULT TNO TNAME TITLE CITY SUPNO Tl T5 Blake Adams Prof MSc London Bristol NULL T4 Where “Clark” > “C”

21 Special Operators Like conditions EXAMPLE
Like conditions are intended for simple pattern matching on character strings- that is, testing a given character string to see whether it conforms to some prescribed pattern. Characters within <pattern> are: Underscore character “_” stands for any single character Percent character “%” stands for any sequence of n characters (where n can be zero) All other characters stand for themselves EXAMPLE 1. Find all students whose surnames begin with "J": SELECT SName FROM Students WHERE SName LIKE "J %"; Result: SNAME Jones Johnson Attention: Operator MATCHES acts similar to LIKE, however MATCHES permits to apply considerably more complicated patterns than LIKE. Details - in documentations of DBMS

22 Special Operators CONTAINS
It checks if a character string contains specified string Example: Find all students whose surname contains string “Ahmad“ SELECT SName FROM Students WHERE SName CONTAINS “Ahmad” Attention: String used in operator CONTAINS can contain special operators like “OR and AND”. Details in documentation of DBMS. Example (Progress): SELECT SName FROM Students WHERE SName CONTAINS “(Ahmad) | (Ahmed)”

23 Special Operators COUNT ()
1. COUNT (*) returns the number of rows in a resulting table 2. COUNT (DISTINCT) < column name> returns the number of different rows in a specified column Examples 1. How many different cities, that students have come from? SELECT COUNT (DISTINCT CITY) FROM Students; Wynik: COUNT1 5 2. How many teachers are from London? SELECT COUNT(*) FROM Teachers WHERE CITY = “London”;

24 Special Operators Aggregation Functions
SUM([DISTINCT] <column name>) MIN([DISTINCT] <column name>) MAX([DISTINCT] <column name>) AVG ([DISTINCT] <column name>) Return correspondingly: sum, minimum, maximum, average of values given from a column. For SUM() and AVG(), column must be numeric, and for MIN() and MAX() column may be numeric, char or date. Examples 1. Find the sum of hours for student S5 SELECT SUM(Hours) FROM TS WHERE SNo=“S5” Result SUM1 168.00 2. Find minimum, maximum and average of hours for the teacher T3 SELECT MIN(Hours), Max(Hours), AVG(Hours) FROM TS WHERE TNo =“T3”; Result MIN1 MAX2 AVG3

25 SELECT – ORDER BY ORDER BY works (effectively) by sorting tuples into some specified sequence. ORDER BY is not a relational operator, since what it returns is not a relation. ORDER BY is also not a function, since there are many possible outputs for a given input, in general. Without ORDER BY clause, results of query are with unspecified order, typically in the order of introducing them into the table. ORDER BY [, <column name/number> [ASC/DESC] [, <column name/number> [ASC/DESC]... ] Note: The number of column in ORDER BY clause represents position of the column mentioned in the statement SELECT. It should be used if we order according to the values of expression. Significantly, the order ASC is accepted as default Find data (in alphabet order) about teachers (names, identifiers and titles.) SELECT TName, TNo,Title FROM Teachers OREDER BY Tname; TNAME TNO TITLE Adams T5 MSc Blake T1 Prof. Clark T4 PhD Jones Smith 73 Prof T2 Result

26 SELECT – ORDER BY Example.
Find data (ident.-student, hours, ident-teacher) about subjects of students S1, S2 and S3, order the result ASC according to identifier of students and DESC according to number of hours. SELECT SNo. Hours, TNo FROM TS WHERE SNo IN (“S1”, “S2”,”S3”) ORDER BY SNo, Hours DESC;    SNO HOURS TNO S1 96 T4 S1 64 T1 S1 32 T3 S2 100 T2 S2 64 T1 S2 36 T3 S3 120 T2 S3 96 T4 S3 60 T3 RESULT

27 SELECT – GROUP BY GROUP BY <COLUMN NAME>
HAVING <condition> This clause is used when we want to group together rows resulting in SELECT statement, where these grouped rows have the same value in column specified in GROUP BY clause. Then every group is reduced to a single row. This row contains: columns presented in GROUP BY clause, as well as, columns being results of aggregation functions. These aggregation functions operate on each group seperately. Then will be eliminated all rows that do not fulfill HAVING condition. Note: Each column appears in GROUP BY clause, must be presented in SELECT statement, and vice versa. Aggregation functions can be used in HAVING condition, but they can not be used in WHERE condition.

28 GROUP BY - Example Find how many students , every teacher has taught?
SELECT Tno, COUNT (*) FROM TS GROUP BY Tno; Tno COUNT1 T1 T2 T3 T4 T5 2 3 4 1 RESULT

29 GROUP BY - Example SNO SUM1 S3 276 S2 196 S1 192
For each student, find SUM of Hours. Find only Ident.Student for students whose SUM of hours exceeds 160h. Put the Result in DESC order according to SUM of Hours SELECT SNo, SUM(Hours) FROM TS Group by SNO Having SUM (Hours) >160 ORDER By 2 DESC; SNO SUM1 S S S

30 SELECT – JOINING MORE TABLES
If From clause contains more than one table then SELECT statement will execute a cross-product (operator TIMES) of these tables. Moreover, if a WHERE CLAUSE exists in this statement then the relational JOIN operator will be executed. EXAMPLE 1 Find information about all lectures of the teacher T4. Show identifiers and names of students and number of hours. Put the result in ascending order according to names of students. SELECT SName, TS.SNo, Hours FROM TS, Students WHERE TS.SNo = Students.SNo AND TNo = "T4" ORDER BY SName; Result STUDENTS. SNAME TS.SNO TS HOURS Ford S5 96 Henry S1 Johnson S3

31 SELECT – JOINING MORE TABLES
EXAMPLE 2 Find all pairs (teacher, student), such that teacher and student are from the same city. Show identifiers and names of students and teachers. Put the result in order according to names of cities then according to names of teachers and students. SELECT T.City, TName, TNo, SName, SNo FROM Teachers T, Students S  WHERE T.City = S.City ORDER BY T.City, TName, SName; T.CITY T.TNAME T.TNO S. SNAME S.SNO Bristol London Adams T5 Ford S5 Blake Jonem Jones T1 T3 Henry Higgins Henry Higgins S1 S4

32 SELECT – JOINING MORE TABLES
Example 3 For every teacher find his name, identifier and sum of hours. Put the result in order according to their names SELECT TName, TS.TNo. SUM(Hours) FROM Teachers T, TS WHERE T.TNo = TS.TNo GROUP BY TName, TS.TNo ORDER BY TName; T.TNAME TSTNO SUM1 Adams T5 32.00 Blakc T1 128.00 Clark T4 288.00 Jones T3 200.00 Smith T2 340.00 Result

33 SELECT – JOINING MORE TABLES
Joining a table with itself is called “self-joining”. Self-joining enables us to relate information contained in different rows of one table. We must use alias when we have self-joining. Example 4 For every teacher find all other teachers who are his subordinate. Put the result in order according to names of superiors then according to names of subordinates. SELECT Over.TName, Over.TNo, “is superior for“, Under.TName, Under.TNo FROM Teachers Under, Teachers Over, WHERE Under.SupNo = Over.TNo ORDER BY Over.TName, Under.TName; Result OVER.TNAME OVER.TNO EXP1 UNDER.TNAME UNDER.TNO Blake Clark Jones T1 T4 T3 Is superior for Smith Adams T2 T5

34 SELECT - Subqueries In subqueries, SELECT statement is nested in WHERE or HAVING clauses. The nested SELECT statement (called also inner query) delivers the values to WHERE or HAVING conditions. The SELECT statement containing subquery is outer query. Example 1. Find information about lectures of teachers who are from London SELECT * FROM TS WHERE TNo IN (SELECT TNo FROM Teachers WHERE City = 'London'); 2. Find identifiers and names of teachers who had at least one lecture that lasted more than 64 hours SELECT TNo, TName FROM Teachers WHERE TNo IN (SELECT TNo FROM TS WHERE Hours > 64);

35 SELECT - Subqueries 3- Find identifiers and names of teachers who taught at least one subject that lasted more than average of hours per a subject. SELECT TNo. TName FROM Teachers WHERE TNo IN (SELECT TNo FROM TS WHERE Hours > (SELECT AVG(Hours) FROM TS));

36 SELECT - Subqueries 4- Find names, identifiers and titles of teachers for whom sum of hours exceeds 200 h. Put the result in alphabet order. SELECT TName, TNo, Title FROM Teachers WHERE TNo IN (SELECT TNo FROM TS GROUP BY TNo HAVING SUM(Hours) > 200) ORDER BY TName;

37 SELECT - Subqueries 5- Find information about lectures, where teacher or student is from London. Put the result in alphabet order according to teachers’ names then according to students’ names. SELECT * FROM TS WHERE TNo IN (SELECT TNo FROM Teachers WHERE City = "London") OR SNo IN (SELECT SNo FROM Students WHERE City = "London") ORDER BY TNo, SNo;

38 SELECT - Subqueries In WHERE condition, may be used operator EXISTS.
Operator EXIXTS returns TRUE value if the subquery returns at least one row. Operator EXIXTS returns FALSE value if the subquery returns zero rows. Example 6. Find information about teachers, who taught student S1. SELECT * FROM Teachers WHERE EXISTS (SELECT * FROM TS WHERE Teachers.TNo = TS.TNo AND TS.SNo = "S1”); 7. Find information (Identifiers and names) of students, who have not been taught by teacher T3. SELECT SNo, SName FROM Students WHERE NOT EXISTS (SELECT * FROM TS WHERE Students.SNo = TS.SNo AND TS.TNo = “T3");

39 SELECT - Subqueries 8. Find information (identifiers, names and titles) of teachers, who have taught all students. SELECT TNo, TName, Title FROM Teachers WHERE NOT EXISTS (SELECT * FROM Students WHERE NOT EXISTS (SELECT * FROM TS WHERE Teachers.TNo = TS.Tno AND Students.SNo = TS.SNo));

40 SELECT - Subqueries {T1:S3, S4, S5, S6 T2:S1, S5, S6 T4:S2, S4, S6
T5: S1, S2, S3, S4, S5} = = TNO SNO HOURS T1 S1 64 S2 T2 100 S3 120 S4 T3 32 36 60 70 S5 S6 72 85 T4 96 T5 TNO TNAME TITLE CITY SUPNO T1 Blake Prof London Null T2 Smith PhD Glasgow T3 Jones T4 Clark Liverpool T5 Adams MSc Bristol SNO SNAME SYEAR CITY S1 Henry 1975 London S2 Jones 1980 Davos S3 Johnson 1983 Dublin S4 Higgins 1984 S5 Ford 1990 Bristol S6 Hopkins Adelaide

41 SELECT - Subqueries TS2 TS1
Find identifiers of teachers, who have taught more than one student. SELECT DISTINCT TS1.TNo FROM TS TS1 WHERE EXISTS (SELECT * FROM TS TS2 WHERE TS1.TNo = TS2.TNo AND TS1.SNo <> TS2.SNo); TNO SNO HOURS T1 S1 64 S2 T2 100 S3 120 S4 T3 32 36 60 S5 72 T4 96 T5 S6 TNO SNO HOURS T1 S1 64 S2 T2 100 S3 120 S4 T3 32 36 60 S5 72 T4 96 T5 S6

42 SELECT - Subqueries OVER UNDER
10. Find names and identifiers of teachers, who are superiors SELECT Over.TName, Over.TNo FROM Teachers Over WHERE EXISTS (SELECT * FROM Teachers Under WHERE Over.TNo = Under.SupNo); The same result can be achieved joining tables (SELECT - example 4) OVER UNDER TNO TNAME TITLE CITY SUPNO T1 Blake Prof London Null T2 Smith PhD Glasgow T3 Jones T4 Clark Liverpool T5 Adams MSc Bristol TNO TNAME TITLE CITY SUPNO T1 Blake Prof London Null T2 Smith PhD Glasgow T3 Jones T4 Clark Liverpool T5 Adams MSc Bristol

43 Inserting data from other tables
INSERT INTO [(<LIST OF COLUMNS>)] <SELECT statement> Aim : Inserting to one table rows from one or more tables Example Suppose that table Students1 has the same structure as the table Students. INSERT INTO STUDENTS SELECT * FROM Students1 WHERE Syear > 1990; This query inserts into the table Students all rows from the table Students1 related to students who have started studies after 1990.

44 Saving results of queries
Some DBMS allow saving results of SELECT statement in a temporary table, by using a clause such as: INTO TEMP < name of table> (< list of columns>) Temporary table is created using SELECT command according to data types mentioned before in SELECT statement. This table is automatically closed after closing the database by the user. Temporary table can be used in FROM clause. In this way we can break complicated queries in several stages.

45 Saving results of queries
Example Find names, identifiers and titles of teachers, who had sum of hours more than average of hours per one teacher. Put the result in alphabet order according to names. SELECT TNo, SUM(Hours) FROM TS GROUP BY TNo INTO TEMP Tsum(TNo, HSum); SELECT TNAME, TNO, TITLE FROM Teachers WHERE TNo IN (SELECT TNo FROM Tsum WHERE Hsum> (SELECT AVG(Hsum) FROM Tsum)) ORDER BY Tname; Table TSum contains sum of hours for every teacher. In the second query, we choose only those teachers for whom sum of hours from the table Tsum exceeds the average of this sum TSUM TNO HSUM T1 120 T2 340 T3 200 T4 228 T5 32

46 Saving results of queries
Some DBMS have not possibility of saving results from SELECT statements in temporary tables, because they haven’t INTO TEMP clause. In this situation we have to create a new table with INSERT INTO clause. CREATE TABLE Tab1 (col1 type1, col2 type2,……); INSERT INTO Tab1 SELECT ….. FROM…….. WHERE….; SELECT………. FROM………… ………. INTO TEMP Tab1 (col1, col2,…. Example SELECT TNo, Tname FROM Teachers WHERE Title = “Prof.” INTO TEMP Profes(PNo, PName); CREATE TABLE Profes (PNo Char(4), PName Char(12)); INSERT INTO Profes SELECT TNo, TName FROM Teachers WHERE Title = “Prof.”;

47 Actualizing Data UPDATE <name of table> SET <name of column> = <Expression> [,<name of column> = <Expression>…] [WHERE <condition>] Aim: Changing values in columns of one or more rows in the table. Example 1. Prof. Blake (ident. T1) changed his place of work from London to Birmingham. UPDATE Teachers SET City = “Birmingham” WHERE TNo = “T1”; 2. Mr. Jone (ident. T3) has more 8 hours with every student. We have to actualize this new situation. UPDATE TS SET Hours = Hours + 8 WHERE TNo = “T3”; 3. We have done some mistakes during introducing data about student S3. Change values in some columns UPDATE STUDENTS SET Sname = “Johnsone”, Syear = 1984, City = “Diblan” WHERE SNo = “S3”;

48 DELETE FROM <name of table> [WHERE < condition>]
Deleting data DELETE FROM <name of table> [WHERE < condition>] Aim: Deleting from a table one or more rows Example 1. Prof. Blake (ident. T1) has changed his place of work. We have to remove data about him from the table Teachers, where we keep only data about actual working teachers. Data about Prof. Blake will be kept in the table Teachers1 that have the same structure as the table Teachers. INSERT INTO Teachers1 SELECT * FROM Teachers WHERE TNo = “T1”; DELETE FROM Teachers WHERE TNo = “T1”; 2. At the end of the year we keep all data of table TS to the table TS1 that stands as an archive for data from TS. Then we clear the table TS. INSERT INTO TS1 SELECT * FROM TS; DELETE FROM TS;

49 SELECT – Joining data from two tables
<SELECT statement> UNION <SELECT statement> Aim: Realization of UNION operator in relational algebra related to tables being results of SELECT statements. Tables must be compatible. Note that: Duplicated rows are removed from the resulting table If names of columns are different, then the resulting table accept name of column from the first table. If we use ORDER BY after UNION, then in ORDER BY should be used only numbers of columns instead of their names. Example Find all cities where teachers or students have come from. Put the result in ASC order. SELECT CITY FROM Teachers UNION SELECT CITY FROM Students ORDER BY 1;

50 Views View (virtual table) Benefits from applying views:
It is a combination of rows and columns chosen from one or more tables. After creating a view it is possible to execute on it SELECTstatements in the same way as on usual table. In database (in database dictionary) the only definition of view will be stored. Benefits from applying views: The same data can be seen in different ways by different users. Views allow to concentrate on essential data and ignore unimportant or other data. Views introduce additional level of data independence: If something has been changed in schema of database, it will suffice often to modify the definition of view, without modifying the program. Views are also useful for enforcing security, because they allow to limit the columns and rows returned to the user. Differences between views and tables: Views do not contain data; they just contain information how to collect -when we need- these data ( from which tables, from which columns). We can not index views ( but we can index tables that are components of views) In general, it is not possible to actualize data using views.

51 Creating views CREATE VIEW < name of view >
[ < list of columns >. ] As< SELECT statement > [WITH CHECK OPTION] Aim: Creating view (virtual table). Optional <list of columns > defines names of columns in the view If there is no <list of columns> then names of columns will be the same that are in the SELECT statement of view. the WITH CHECK OPTION - Guarantee, that all updates of view (if the view has been updated) fulfill conditions being in WHERE clause of SELECT statement. Example 1 (updated view) CREATE VIEW TopTeachers As SELECT TNo, TName, Title FROM Teachers WHERE Title <> “MSc” WITH CHECK OPTION; SELECT * FROM TopTeachers. TNO TNAME TITLE T1 Blake Prof. T2 Smith PhD T3 Jones T4 Clark

52 Creating views Example 2 Result CREATE VIEW TSJoined
(TeachNo, TeachName, StudNo, StudName, TeachHours) AS SELECT Teachers.TNo, Teachers.TName, Students.SNo, Students.SName, TS.Hours FROM TS, Teachers, Students WHERE TS.TNo = Teachers.TNo AND TS.SNo = Students.Sno ; SELECT * FROM TSJoined WHERE TeachHours >= 90 ; TEACHNO TEACHNAME STUDNO STUDNAME TEACHHOURS T2 Smilh S2 Jones 100 Srnith S3 Johnson 120 T4 Sinilh Clark S4 S1 Higgins Henry 96 S5 Ford Result

53 Updating views Examples of limitations (depend on DBMS):
View TSJoined (example 2.) it can be not actualized. This depends on limitations on actualizing views put on by concrete DBMS Examples of limitations (depend on DBMS): SELECT statement does not contain DISTINCT clause, GROUP BY, HAVING. SELECT statement does not contain expressions nor aggregation functions. In FROM clause only one table may be used. In WHERE clause subquries may be not allowed. On list of columns of view may step out Primary key of the table mentioned in FROM clause. Details - in documentation of concrete DBMS.

54 Creating Index Examples: CREATE UNIQUE INDEX TeachInd
CREATE [UNIQUE] INDEX <name of index> ON <name of table> (name of column> [ASC/DESC] [,<name of column>[ASC/DESC]…]) Aim: creating index on definite columns, called “ keys of index”. Default, index is increasing (ASC) . UNIQUE clause means that the columns of index contain unique values. Examples: CREATE UNIQUE INDEX TeachInd ON Teachers (Tno ); CREATE UNIQUE INDEX TSInd ON TS (Tno, SNo); CREATE INDEX Hrslnd ON Students (Sno, Hours DESC);

55 Creating index What is Index?
It is a table that contains in one column values of the key, and in the second the addresses of row in indexed table, which contain these values. What can it be used for? 1. Index allows to enlarge efficiency of processing data access in the table (SELECT statement). 2. Sort rows of the table in definite order. 3. Eliminate duplicating values in rows of the table. When create Index? 1. When table is frequently processed in sequence according to values of some column (ASC or DESC). 2. When it is necessary to keep the values in column(s) unique. 3. When access to the table is frequently realized according to values of some given column(s). What is the cost? 1. Cost in memory - (More additional data have to be saved in memory). 2. timing cost { the necessity of updating index when actualizing the table (the statements INSERT. the UPDATE, DELETE).

56 CREATE INDEX Example CREATE INDEX TSHours ON TS (Hours DESC) TSHours
RecNo TNO SNO HOURS 120 4 T1 S1 64 1 5 S2 2 100 3 T2 96 10 S3 11 S4 12 T3 32 6 72 9 36 7 60 8 S5 T4 13 T5 S6

57 Creating Index - Examples
CREATE INDEX StudHrs ON TS (Sno, Hours); StudHrs TS SNo+Hours RecNo TNo SNo Hours S1 + 32 6 T1 S1 64 1 S1 + 64 Tl S2 2 S1 + 96 10 T2 100 3 S2 + 36 7 S3 120 4 S2 + 64 S4 5 S T3 32 S3 + 60 8 36 S3 + 96 11 60 S3+ 120 S5 72 9 S4+ 120 T4 96 S5+ 72 S5+ 96 12 S6 + 32 13 T5 S6

58 Deleting tables, indexes and views DROP TABLE <name of table>
Aim: Deleting existing table. All data in the table will be deleted. All indexes and views also will be deleted. Example: DROP TABLE Books DROP INDEX <name of the index> Aim: Deleting existing index. No effect on the indexed table. DROP INDEX Hours DROP VIEW <name of view> Aim: Deleting existing view. No effect on the table that step out in the definition of the view. DROP VIEW MyView

59 OUTER JOIN In inner (regular) join, in the result will appear all tuples from both tables (left and right). Tuples in one table having no couterpart in the other table, will be ignored. In any outer join, all tuples in the inner join will appear the outer join. Moreover: In left outer join - For every tuple chosen from the left table, having no counterpart in the right table, will step out a tuple with null values. In other words: All tuples from the left table will appear in the result even if they haven’t counterpart in the right table. In right outer join - For every tuple chosen from the right table, having no counterpart in the left table, will step out a tuple with null values. In other words: All tuples from the right table will appear in the result even if they haven’t counterpart in the left table. Full outer join – the result will be sum results of left and right outer join. That is the result of UNION operation of left and right outer join. Note that: DBMS may have different limitations on outer join. Details in documentations of DBMS.

60 OUTER JOIN - Examples Left outer join table1 table2 Result SQL
C11 C12 1 2 5 6 4 7 9 C21 C22 1 2 3 6 5 9 Left Outer Join On C11 = C21 Result C11 C12 C21 C22 1 2 5 6 4 7 9 ? SQL SELECT * FROM table1 LEFT JOIN table2 ON C11 = C21 SELECT * FROM table1 LEFT JOIN table2 WHERE C11 = C21

61 OUTER JOIN - Examples Right outer join table1 table2 Result SQL
C11 C12 1 2 5 6 4 7 9 C21 C22 1 2 3 6 5 9 Right Outer Join On C11 = C21 Result C11 C12 C21 C22 1 2 ? 4 3 6 5 9 SQL SELECT * FROM table1 RIGHT JOIN table2 ON C11 = C21 SELECT * FROM table1 RIGHT JOIN table2 WHERE C11 = C21

62 OUTER JOIN - Examples Example
SELECT T.City, TName, TNo, SName, SNo FROM Teachers T LEFT JOIN Students S ON T.City = S.City WHERE Title <> ‘MSc’ Result T.CITY TNAME TNO SNAME SNO London Glasgow Liverpool Blake Jones Smith Clark T1 T3 T2 T4 Henry Higgins ? S1 S4

63 Relational Completeness
Definition Query language is said to be relationally complete if it is at least as powerful as the algebra – that is, if its expressions permit the definition of every relation that can be defined by means of expressions of the relational algebra. SQL is relationally complete Let R and S be relations with the following attributes,, A1,A2,…An and B1,B2,…Bn, correspondingly. Moreover, we suppose that for operators UNION and MINUS relations R and S are compatible. Relational algebra SQL R UNION S SELECT * FROM R UNION FROM S

64 Relational Completeness (cont.)
Relational algebra SQL R MINUS S R TIMES S SELECT R WHERE condition PROJECT R OVER Ai, Aj,… SELECT * FROM R WHERE NOT EXISTS (SELECT * FROM S WHERE R.A1 = S.B1 AND R.A2 = S.B2 AND… R.An = S.Bn FROM R, S WHERE condition SELECT Ai, Aj,…


Download ppt "SQL Language Review SELECT Statements Instructions for modifying data"

Similar presentations


Ads by Google