65
Structured Query Language (SQL)

Structured Query Language (SQL). A query is a statement requesting the retrieval of information The portion of a DML that involves information retrieval

Embed Size (px)

Citation preview

Page 1: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Structured Query Language(SQL)

Page 2: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

A query is a statement requesting the retrieval of informationThe portion of a DML that involves information retrieval is called a query languageSQL is the most widely used commercial relational database language

THE FORM OF A BASIC SQL QUERY

SELECT [DISTINCT ] select-list FROM from-list WHERE qualificationSELECT clause specifies columns to be retained in the resultFROM clause specifies a cross-product of tables

Page 3: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Sailors (sid number,sname varchar2(20),rating number,age

number(4,2));

Boats(bid number,bname varchar2(20),color varchar2(10));

Reserves (sid number, bid number,day date);

Page 4: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Optional WHERE clause specifies selection conditions on the tables mentioned in the FROM clause

Example

Fig 4.1 Sailors table

Attribute (or) Field

Record (or) Tuple

Page 5: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: Find the names and ages of all sailors

Query: SELECT DISTINCT sname, age FROM SailorsOutput:

Note: The DISTINCT keyword can be used to return only distinct (different) values

Page 6: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: Find the names and ages of all sailors

Query: SELECT sname, age FROM SailorsOutput:

Page 7: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: Find all sailors with a rating above 7

Query: SELECT sid, sname, rating, age FROM Sailors WHERE rating >7 (or) SELECT * FROM Sailors WHERE rating>7 Output:

Page 8: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

The SQL language has Three parts -Data Definition Language (DDL) -Data Manipulation Language (DML) -Data Control Language(DCL)Data Definition Language (DDL): DDL supports the creation, deletion, and modification of definitions for tables and views

Integrity constraints can be defined on tables, either when the table is created or later

The DDL also provides commands for specifying access rights or privileges to tables and views

It also provide commands for creating and deleting indexes

Page 9: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Data Manipulation Language (DML): DML allows users to pose queries and to insert, delete, and modify rows

Data Control Language (DCL): DCL controls a database, including administrative privileges and saving data

Page 10: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Data typeSpecifies the kind of data that a field stores

Character data types

VARCHAR2Stores variable-length character data up to a maximum of 4,000 charactersValues in different records can have a different number of characters

VARCHARSame as VARCHAR2, but it is in ANSI standard

Syntax: Fieldname VARCHAR2(maximum-size)

Page 11: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

CHARFixed-length character data up to a maximum size of 2,000 charactersData values for different records all have the same number of charactersDBMS adds trailing blank spaces to the end of the entry to make the entry fill the maximum size valueData longer than maximum size causes an errorSyntax: Fieldname CHAR[(maximum-size)]

NVARCHAR2 and NCHARAnalogous to VARCHAR2 and CHAR but use Unicode rather than ASCIIUsed to hold character data in languages other then English

Page 12: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

LONGVariable-Length character data up to 2 GB, max. of one per tableNumber data typesStores negative, positive, fixed and floating point numbers with precision up to 38 decimal placesSyntax: Fieldname NUMBER[(precision , scale)]Integer: Fieldname NUMBER (precision)Fixed Point: Fieldname NUMBER[(precision , scale)]

Date and Time data typesDateDates from December 31,4712 BC to December 31,4712 ADDefault format DD-MON-YYDefault time format HH:MI:SS AM

Page 13: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Syntax: Fieldname DATE

TimestampSimilar to DATE but stores fractional seconds

Syntax: Fieldname TIMESTAMP(Fractional-seconds-pre)

DDL Commands -CREATE -ALTER -DROP

Page 14: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

CREATE commandUsed to create table Syntax:CREATE TABLE table-name (Fieldname1 data_type , Fieldname2 data_type , …. ….. ….)

ExampleCREATE TABLE Sailors ( sid NUMBER(2), sname VARCHAR2(20), rating NUMBER(2))

ALTER commandUsed to add attributes to an existing relation(table)All rows in the relation(table) are assigned ‘null’ as the value for the new attributesSyntax: ALTER TABLE tablename ADD (fieldname Field_datatype)

Page 15: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Example: ALTER TABLE Sailors ADD (age NUMBER(2))Modifying an existing fieldSyntax: ALTER TABLE tablename MODIFY (fieldname new_field_datatype)Example ALTER TABLE Sailors MODIFY (age NUMBER(3,1))

Deleting an existing fieldSyntax: ALTER TABLE tablename DROP COLUMN FieldnameExample: ALTER TABLE Sailors DROP COLUMN age

DROP commandUsed to delete an existing tableSyntax: DROP TABLE tablename Example: DROP TABLE Sailors

Page 16: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

DML Commands -INSERT -DELETE -UPDATE -SELECT

INSERT commandInserting record into a tableSyntax: INSERT INTO table-name VALUES (field1,field2,…)Example:INSERT INTO Sailors values (22,’Dustin’,7,45.0)

Inserting a record that has some null attributesRequires identifying the fields that actually get dataSyntax: INSERT INTO table-name (field1,field4) VALUES (value1,value2)

Page 17: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Inserting records from another tableSyntax: INSERT INTO table_name1 SELECT * FROM table_name2

UPDATE commandFor modifying attribute values of (some) tuples in a tableSyntax: UPDATE tablename SET column1=value1,…, columnn=valuen WHERE conditionExample: UPDATE Sailors SET age=34.5 WHERE sid=22

DELETE commandRemoving specified rows from a tableSyntax: DELETE FROM tablename WHERE conditionExample: DELETE FROM Sailors WHERE sid=22

Page 18: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Removing all rows from a tableSyntax: DELETE FROM tablename Example: DELETE FROM Sailors (or)Syntax: TRUNCATE table SailorsExample: TRUNCATE table SailorsNote: TRUNCATE Removes all rows from a table without backup

Fig 4.2 Boats table

Page 19: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Fig 4.3 Reserves table

Page 20: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

AND, OR and NOT Operators

BETWEENUsed to define range limits

Page 21: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

INUsed to check whether an attribute value matches a value contained within a set of listed values

Page 22: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

STRING operators“%” character is used to match any substring“_” character is used to match any characterExpresses patterns by using the ‘like’ comparison operatorExample1 SELECT * FROM Sailors WHERE sname LIKE '_u%'Output:

Example2 SELECT * FROM Sailors WHERE sname LIKE 'A_d_'Output:

SID SNAME RATING AGE

22 Dustin 7 45

31 Lubber 8 55.5

58 Rusty 10 35

SID SNAME RATING AGE

32 Andy 8 25.5

Page 23: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

SET operatorsOperations such as union, intersect, minus and exists operate on relationsCorresponding to relational-algebra operations U, ∩ and –Relations participating in the operations must be compatible; i.e., must have same set of attributes

<query 1> <set operator> <query 2>

union returns a table consisting of all rows either appearing in the result of <query1> or in the result of <query 2>intersect returns all rows that appear in both results <query 1> and <query 2>minus returns those rows that appear in the result of <query 1> but not in the result of <query 2>

Page 24: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Example (union)SELECT * FROM SailorsUNIONSELECT * FROM Sailors1Output:

Page 25: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Example (intersect)SELECT * FROM SailorsINTERSECTSELECT * FROM Sailors1Output:

Page 26: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Example (minus)SELECT * FROM SailorsMINUSSELECT * FROM Sailors1Output: no rows selected

Nested QueriesA nested query is a query that has another query embedded within it The embedded query is called a subqueryA subquery typically appears within the WHERE clause of a querySubqueries can sometimes appear in the FROM clause or the HAVING clause

Page 27: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Introduction to Nested QueriesQuestion: Find the names of sailors who have reserved boat 103Query: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103)Output:

Question: Find the names of sailors who have reserved a blue boatQuery: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid IN (SELECT B.bid FROM Boats B WHERE B.color='blue'))

SNAME

Dustin

Lubber

Horatio

Page 28: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Output:

Correlated Nested QueriesIn the nested queries, the inner subquery has been completely independent of the outer queryIn general the inner subquery could depend on the row that is currently being examined in the outer queryQuestion: Find the names of sailors who have reserved boat 103Query: SELECT S.sname FROM Sailors S WHERE EXISTS ( SELECT * FROM Reserves R WHERE R.bid = 103 AND R.sid = S.sid )

SNAME

Dustin

Horatio

Page 29: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Output:

The EXISTS operator is another set comparison operator, such as INIt allows us to test whether a set is nonempty. Thus, for each Sailor row S, we test whether the set of Reserves rows R such that R.bid = 103 AND S.sid = R.sid is nonempty. If so, sailor S has reserved boat 103, and we retrieve the nameThe subquery clearly depends on the current row S and must be re-evaluated for each row in SailorsThe occurrence of S in the subquery (in the form of the literal S.sid) is called a correlation, and such queries are called correlated queries.

SNAME

Dustin

Lubber

Horatio

Page 30: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

SYMBOL MEANING

= Equal to

< Less than

<= Less than or equal to

> Grater than

>= Greater than or equal to

<> or != or ^= Not equal to

COMPARISION OPERATORSThe following operators can be used in ‘WHERE’ clause

Example Question: Find sailors whose rating is better than some sailor called HoratioQuery: SELECT S1.sname, S1.rating FROM Sailors S1 WHERE S1.rating > ANY ( SELECT S2.rating FROM

Page 31: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Sailors S2 WHERE S2.sname='Horatio' )Output:

If there are several sailors called Horatio, this query finds all sailors whose rating is better than that of some sailor called HoratioQuestion: Find sailors whose rating is better than some sailor called HoratioQuery: SELECT S1.sname, S1.rating FROM Sailors S1 WHERE S1.rating > ALL ( SELECT S2.rating FROM

SNAME RATING

Rusty 10

Zorba 10

Horatio 9

Lubber 8

Andy 8

Page 32: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Sailors S2 WHERE S2.sname='Horatio' )Output:

AGGREGATE OPERATORSIn addition to simply retrieving data, we often want to perform some computation or summarizationSQL supports the following aggregate operations, which can be applied on any column, say A, of a relation(table):1. COUNT ([DISTINCT] A): The number of (unique) values in the A column2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column3. AVG ([DISTINCT] A): The average of all (unique) values in the A column

SNAME RATING

Rusty 10

Zorba 10

Page 33: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

4. MAX (A): The maximum value in the A column5. MIN (A): The minimum value in the A columnNote: not specify DISTINCT in conjunction with MIN or MAXExamples:Question: Find the average age of all sailorsQuery: SELECT AVG (age) FROM SailorsOutput:

Question: Find the name and age of the oldest sailorQuery: SELECT S1.sname, S1.age FROM Sailors S1 WHERE S1.age = ( SELECT MAX (S2.age) FROM Sailors S2 )Output:

AVG(AGE)

36.9

SNAME AGE

Bob 63.5

Page 34: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: Count the number of sailorsQuery: SELECT COUNT (*) FROM SailorsOutput:

The GROUP BY and HAVING ClausesWe have applied aggregate operations to all (qualifying) rows in a relation(table)GROUP BY used to apply aggregate operations to each of a number of groups of rows in a relationHAVING is used to place a condition, which is applied on the groups of rows general form:SELECT [ DISTINCT ] select-listFROM from-listWHERE qualificationGROUP BY grouping-list HAVING group-qualification

COUNT(*)

10

Page 35: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

ExamplesQuestion: Find the number of sailors belongs to each rating levelQuery: SELECT rating, COUNT(rating) FROM Sailors GROUP BY ratingOutput:

RATING COUNT(RATING)

1 1

3 2

7 2

8 2

9 1

10 2

Page 36: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: Find the age of the youngest sailor for each rating levelQuery: SELECT rating, MIN (age) FROM Sailors GROUP BY ratingOutput:

RATING MIN(AGE)

1 33

3 25.5

7 35

8 25.5

9 35

10 16

Page 37: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: Find the age of the youngest sailor for each rating level, which is greater than 7Query: SELECT rating, MIN (age) FROM Sailors GROUP BY rating HAVING rating>7Output:

ORDER BYThe order by clause is used to sort the tuples in a query result based on the values of some attributesExample Question: display the sailors table in the ascending order of sname

RATING MIN(AGE)

8 25.5

9 35

10 16

Page 38: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Query: SELECT * FROM Sailors ORDER BY snameOutput:

SID SNAME RATING AGE

32 Andy 8 25.5

85 Art 3 25.5

95 Bob 3 63.5

29 Brutus 1 33

22 Dustin 7 45

64 Horatio 7 35

74 Horatio 9 35

31 Lubber 8 55.5

58 Rusty 10 35

71 Zorba 10 16

Page 39: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Question: display the sailors table in the descending order of snameQuery: SELECT * FROM Sailors ORDER BY sname DESCOutput: SID SNAME RATING AGE

71 Zorba 10 16

58 Rusty 10 35

31 Lubber 8 55.5

64 Horatio 7 35

74 Horatio 9 35

22 Dustin 7 45

29 Brutus 1 33

95 Bob 3 63.5

85 Art 3 25.5

32 Andy 8 25.5

Page 40: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

NULL VALUES

Thus far, we have assumed that column values in a row are always known. In practice column values can be unknown

We use null when the column value is either unknown

Example

Insert the row (98,Dan,null,39) to represent Dan into sailors table

Query: INSERT INTO Sailors VALUES(98,'Dan',null,39)Query: SELECT * FROM Sailors

Page 41: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

SID SNAME RATIN

G AGE

22 Dustin 7 45

29 Brutus 1 33

31 Lubber 8 55.5

32 Andy 8 25.5

58 Rusty 10 35

64 Horatio 7 35

71 Zorba 10 16

74 Horatio 9 35

85 Art 3 25.5

95 Bob 3 63.5

98 Dan   39

Output:

Page 42: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Comparisons Using Null ValuesConsider a comparison such as rating = 8If this is applied to the row for Dan, is this condition true or false? Since Dan's rating is unknown, it is reasonable to say that this comparison should evaluate to the value unknownThis is the case for the comparisons rating > 8 and rating < 8 as wellSQL also provides a special comparison operator IS NULL to test whether a column value is null for example, we can say rating IS NULL, which would evaluate to true on the row representing DanWe can also say rating IS NOT NULL, which would evaluate to false on the row for DanExample Query: SELECT * FROM sailors WHERE rating IS NULL

Page 43: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

SID SNAME RATING AGE

98 Dan   39

Output:

Logical Connectives AND, OR, and NOTwhat about boolean expressions such as

rating = 8 OR age < 40 rating = 8 AND age < 40?

Considering the row for Dan again, because age < 40, the first expression evaluates to true regardless of the value of rating, but what about the second? We can only say unknown

The expression NOT unknown is defined to be unknown

Page 44: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

OR of two arguments evaluates to true if either argument evaluates to true, and to unknown if one argument evaluates to false and the other evaluates to unknownAND of two arguments evaluates to false if either argument evaluates to false, and to unknown if one argument evaluates to unknown and the other evaluates to true or unknownImpact on SQL ConstructsIn the presence of null values, any row that evaluates to false or to unknown is eliminatedEliminating rows that evaluate to unknown has a subtle but significant impact on queries, especially nested queries involving EXISTS or UNIQUEIf we compare two null values using =, the result is unknown! In the context of duplicates, this comparison is implicitly treated as true, which is an anomaly

Page 45: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

The arithmetic operations +, - ,* , / and = all return null if one of their arguments is null

nulls can cause some unexpected behavior with aggregate operations

COUNT(*) handles null values just like other values, that is, they get counted

All the other aggregate operations (COUNT, SUM, AVG, MIN, MAX, and variations using DISTINCT) simply discard null values

Page 46: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Outer Joinsjoin operation that rely on null values, called outer joins

Consider the join of two tables, say Sailors Reserves

In a full outer join, ‘matching rows’ plus ‘Sailors rows without a matching Reserves rows’ (columns inherited from Reserves assigned null values) plus ‘Reserves rows without a matching Sailors rows’ (columns inherited from Sailors assigned null values) appear in the result

In a left outer join, ‘matching rows’ plus ‘Sailors rows without a matching Reserves rows’ (columns inherited from Reserves assigned null values) appear in the result

Page 47: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

In a right outer join, ‘matching rows’ plus ‘Reserves rows without a matching Sailors rows’ (columns inherited from Sailors assigned null values) appear in the resultNote: In inner join only matching rows appear in the resultExampleQuery: SELECT S.sid,S.sname, R.bid,R.day FROM Sailors S LEFT OUTER JOIN Reserves R ON S.sid=R.sid Disallowing Null ValuesWe can disallow null values by specifying NOT NULL as part of the field definition, for example, sname CHAR(20) NOT NULLThe fields in a primary key are not allowed to take on null valuesThere is an implicit NOT NULL constraint for every field listed in a PRIMARY KEY constraint

Page 48: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

COMPLEX INTEGRITY CONSTRAINTS IN SQLConstraints over a Single TableWe can specify complex constraints over a single table using table constraints, which have the form CHECK conditional-expressionFor example, to ensure that rating must be an integer in the range 1 to 10, we could use:CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK ( rating >= 1 AND rating <= 10 ))To enforce the constraint that Interlake boats cannot be reserved, we could use:CREATE TABLE Reserves ( sid INTEGER,bid INTEGER,day DATE,FOREIGN KEY (sid) REFERENCES Sailors

Page 49: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

FOREIGN KEY (bid) REFERENCES BoatsCONSTRAINT noInterlakeResCHECK ( `Interlake' <>( SELECT B.bname FROM Boats B WHERE B.bid = Reserves.bid )))When a row is inserted into Reserves or an existing row is modied, the conditional expression in the CHECK constraint is evaluated. If it evaluates to false, the command is rejectedDomain ConstraintsA user can dene a new domain using the CREATE DOMAIN statement, which makes use of CHECK constraintsCREATE DOMAIN ratingval INTEGER DEFAULT 0CHECK ( VALUE >= 1 AND VALUE <= 10 )

Page 50: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

INTEGER is the base type for the domain ratingval, and every ratingval value must be of this type. Values in ratingval are further restricted by using a CHECK constraintOnce a domain is defined, the name of the domain can be used to restrict column values in a table rating ratingvalAssertions: ICs over Several TablesTable constraints are associated with a single table, although the conditional expression in the CHECK clause can refer to other tablesTable constraints are required to hold only if the associated table is nonemptyAssertions, which are constraints not associated with any one table

Page 51: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

As an example, suppose that we wish to enforce the constraint that the number of boats plus the number of sailors should be less than 100. (This condition might be required, say, to qualify as a `small' sailing club.) We could try the following table constraint:CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK ( rating >= 1 AND rating <= 10)CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S )+ ( SELECT COUNT (B.bid) FROM Boats B )< 100 ))CREATE ASSERTION smallClubCHECK ( ( SELECT COUNT (S.sid) FROM Sailors S )+ ( SELECT COUNT (B.bid) FROM Boats B) < 100 )

Page 52: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

TRIGGERS AND ACTIVE DATABASESA trigger is a procedure that is automatically invoked by the DBMS in response to specified changes to the database, and is typically specified by the DBAA database that has a set of associated triggers is called an active databaseA trigger description contains three parts:Event: A change to the database that activates the triggerCondition: A query or test that is run when the trigger is activatedAction: A procedure that is executed when the trigger is activated and its condition is trueExamples of Triggers in SQLCREATE TRIGGER init count BEFORE INSERT ON Students /* Event */DECLARE count INTEGER;

Page 53: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

BEGIN /* Action */count := 0;END

CREATE TRIGGER incr count AFTER INSERT ON Students /* Event */WHEN (new.age < 18) /* Condition; `new' is just-inserted tuple */FOR EACH ROWBEGIN /* Action */count := count + 1;END

Page 54: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

1. (a) Consider the following schema given. The primary keys are underlined.Sailors(sailor-id, sailor-name, sailor-rating, sailor-age)Boats(boat-id, boat-name, boat-color)Reserves(sailor-id, boat-id, day)

Write the Nested queries in SQL. i. Find the names of sailors who have reserved boat number 120 ii. Find the names of sailors who have reserved a green boat iii. Find the names of sailors who have not reserved a green boat iv. Find the names of sailors with the highest rating (b) Explain the GROUP BY and HAVING clauses.2(a) Consider the following scheme for the COMPANY database. The primary keys are underlined. Employee (SSN, Fname, Lname, Birthdate, Address, Salary, Dnumber) Department (Dnumber, Dname, Dlocation) Perform the following operations using SQL. Assume the data:

i. Insert a record into employee tableii. Delete an employee with SSN equal to 10.iii. Update the Dnumber of the employee tuple having salary greater than Rs 10,000.iv. Retrieve the name and address of all employees who work for the ”XYZ” department.

Assignment - 3

Page 55: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

3 (a) Explain with an example in SQLi. Unspecified where-clause and use of Asteriskii. Exist and not existsiii. Explicit sets and NULLSiv. Renaming attributes and joined tables. (b) Why are null values not preferred in a relation?

4 (a) Explain the general syntax of SELECT command (b) What are the steps followed while creating a table in SQL?5(a) What are the various salient features of the SQL?

(b) Write short notes on:i) Key constraintsii) General constraints

6 (a) What is the role of SQL in a database architecture? (b) What are the notations used in SQL commands?7 (a) Explain the various types of aggregate functions with suitable examples in SQL (b) Explain the following

(i) Key constraints(ii) Foreign key constraints(iii) General constraints

Page 56: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

8 a) Consider the following schema:

Suppliers(sid, sname, saddress)

Parts(pid, pname, color)

Catalog(sid, pid, cost)

The key fields are underlined. Write the following queries in relational algebra

(i) Find the names of suppliers who supply blue part

(ii) Find the sids of suppliers who supply every red part

(iii) Find the pids of parts that are supplied by at least two different suppliers

(iv) Find all the pids of parts supplied by supplier with sid=200

(v) Find the pids of parts supplied by every supplier at less than Rs 500

9 Distinguish between DDL and DML

10 Explain various integrity constraints.

Page 57: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

• Note that the outer query references the dummy table called “dual” 

the dual table is used in Oracle when you need to run SQL that does

not logically have a table name.  For example, we can select our

current user ID from dual and the current date from dual.    

select user from dual;

select sysdate from dual;

Page 58: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Conversion functions

1. TO_CHAR function:

– TO_CHAR(str,'fmt')

– Fmt -> can be a string created by date format element or numeric format elements.

– The TO_CHAR function is used to convert a date type value or a numeric value into a character string.

– This is often used when you want to display a date in a format other than a DD-MON-YY format.

Page 59: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

Format Element Description Example YYYY Full year in numbers 2010 YEAR Year spelled out Two thousand Nine MM Two digit value for month 09 MONTH Full name of month APRIL MON Three letter abbreviation of month APR DY Three letter abbreviation of day of week TUE DAY Full name of the day of the week TUESDAY DD Numeric day of the month 25

Page 60: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

2. TO_DATE(str,'fmt')

– Converts a string representing a date that is in a non default date to a date value in the default date format.

– The TO_DATE function is used to convert a character string that represents a date into a date value. In the example:SELECT TO_DATE('3 of June, 2009','DD "of" Month, YYYY')FROM DUAL;

The character string '3 of June, 2009' needs to be converted to a date as in 06-03-09. The second argument in the TO_DATE function tells Oracle how to read the first argument. It defines the format that the first argument is in. This tells Oracle how to read the first argument, to identify the individual date elements from the character string.

 

Page 61: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

3. TO_NUMBER(str,'fmt')

• Converts a string representing a numeric value with format to a number without formatting.

• The TO_NUMBER function is used to convert a character string into a numeric value.

• Example:SELECT TO_NUMBER('$45.67','$99.99')FROM DUAL;The first argument is a formatted numeric value with a dollar sign. The TO_NUMBER function is used to convert this string into a number as in 45.67. The second argument tells Oracle how to interpret the first argument. Using the second argument Oracle is able to identify the number without the formats.

Page 62: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

The ADD_MONTHS function:

• Syntax:

ADD_MONTHS(date,n)

Returns a date, that is n months before (if n is negative) or after (if n

is positive) the date.

• SELECT ADD_MONTHS(SYSDATE,3) FROM DUAL;

• You are adding three months to the current date. If the current date

Aug 03, 2009, the output is 03-NOV-09.

Page 63: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

• The MONTHS_BETWEEN function:

• Syntax:MONTHS_BETWEEN(date1, date2)Returns a number representing the number of months between date1 and date2.

• SELECT ENAME, MONTHS_BETWEEN(SYSDATE,HIREDATE) FROM EMPWHERE JOB=‘CLERK';

Page 64: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

• The last_day Oracle date function returns the last day of the month of the date d.  If you want to find the first day of the next month, simply add one to the last_day results.

Page 65: Structured Query Language (SQL).  A query is a statement requesting the retrieval of information  The portion of a DML that involves information retrieval

• The next_day Oracle date function returns the date of the

day_of_week after date d.  day_of_week can be the full name or

abbreviation.  Below, we get the date for next Monday, next Friday,

and the first Tuesday of next month.