0% found this document useful (0 votes)
8 views33 pages

DBMS Module 4

The document provides an overview of SQL, detailing its data definition, data types, and various commands such as CREATE TABLE and SELECT. It explains the structure of SQL, including constraints, data types like numeric and character strings, and retrieval queries. Additionally, it covers advanced SQL features such as views, assertions, and triggers, emphasizing the importance of schema design and integrity constraints.

Uploaded by

bilgaradi2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views33 pages

DBMS Module 4

The document provides an overview of SQL, detailing its data definition, data types, and various commands such as CREATE TABLE and SELECT. It explains the structure of SQL, including constraints, data types like numeric and character strings, and retrieval queries. Additionally, it covers advanced SQL features such as views, assertions, and triggers, emphasizing the importance of schema design and integrity constraints.

Uploaded by

bilgaradi2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Department of Artificial Intelligence and Machine Learning

Module 4
SQL: SQL data definition and data types, Schema change statements in SQL, specifying
constraints in SQL, retrieval queries in SQL, INSERT, DELETE, and UPDATE
statements in SQL, Additional features of SQL.
Advances Queries: More complex SQL retrieval queries, Specifying constraints as
assertions and action triggers, Views in SQL, Schema change statements in SQL.

Basic SQL

• The name SQL is presently expanded as Structured Query Language.


• Originally, SQL was called SEQUEL (Structured English QUEry Language) and was
designed and implemented at IBM Research as the interface for an experimental
relational database system called SYSTEM R.
• SQL is now the standard language for commercial relational DBMSs.
• The standardization of SQL is a joint effort by the American National Standards
Institute (ANSI) and the International Standards Organization (ISO), and the first
SQL standard is called SQL-86 or SQL1.
• A revised and much expanded standard called SQL-92.
• SQL is a comprehensive database language: It has statements for data definitions,
queries, and updates. Hence, it is both a DDL and a DML.
• In addition, it has facilities for defining views on the database, for specifying security
and authorization, for defining integrity constraints, and for specifying transaction
controls.
• It also has rules for embedding SQL statements into a general-purpose programming
language such as Java or C/C++.

SQL Data Definition and Data Types

• SQL uses the terms table, row, and column for the formal relational model terms
relation, tuple, and attribute, respectively.
• The main SQL command for data definition is the CREATE statement, which can be
used to create schemas, tables (relations), types, and domains, as well as other
constructs such as views, assertions, and triggers.

0) Attribute Data Types and Domains in SQL

• Data Types

The basic data types available for attributes include numeric, character string, bit string,
Boolean, date, and time.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

Numeric
• Numeric data types include integer numbers of various sizes (INTEGER or
INT, and SMALLINT) and floating-point (real) numbers of various precision
(FLOAT or REAL, and DOUBLE PRECISION).
• Formatted numbers can be declared by using DECIMAL(i, j)—or DEC(i, j) or
NUMERIC(i, j)—where i, the precision, is the total number of decimal digits
and j, the scale, is the number of digits after the decimal point.
• The default for scale is zero, and the default for precision is implementation-
defined.

Character-string
• Character-string data types are either fixed length—CHAR(n) or
CHARACTER(n), where n is the number of characters—or varying length—
VARCHAR(n) or CHAR VARYING(n) or CHARACTER
VARYING(n), where n is the maximum number of characters.
• When specifying a literal string value, it is placed between single quotation
marks and it is case sensitive (a distinction is made between uppercase and
lowercase).
• For fixed length strings, a shorter string is padded with blank characters to the
right.
• For example, if the value ‘Smith’ is for an attribute of type CHAR(10), it is
padded with five blank characters to become ‘Smith’ if needed.
• Padded blanks are generally ignored when strings are compared.
• For comparison purposes, strings are considered ordered in alphabetic (or
lexicographic) order; if a string str1 appears before another string str2 in
alphabetic order, then str1 is considered to be less than str2.
• There is also a concatenation operator denoted by || (double vertical bar) that
can concatenate two stringsin SQL. For example, ‘abc’ || ‘XYZ’ results in a
single string ‘abcXYZ’.

Bit-string
• Bit-string data types are either of fixed length n—BIT(n)—or varying
length— BIT VARYING(n), where n is the maximum number of bits. The
default for n, the length of a character string or bit string, is 1.
• Literal bit strings are placed between single quotes but preceded by a B to
distinguish them from character strings; for example, B‘10101’.

Boolean
• This data type has the traditional values of TRUE or FALSE.
• In SQL, because of the presence of NULL values, a three-valued logic is
used, so a third possible value for a Boolean data type is UNKNOWN.

DATE and TIME


• The DATE data type has ten positions, and its components are YEAR,
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

MONTH, and DAY in the form YYYY-MM-DD.


• The TIME data type has at least eight positions, with the components
HOUR, MINUTE, and SECOND in the form HH:MM:SS.
• A timestamp data type (TIMESTAMP) includes the DATE and TIME fields,
plus a minimum of six positions for decimal fractions of seconds and an
optional WITH TIME ZONE qualifier. Literal values are represented by
single-quoted strings preceded by the keyword TIMESTAMP, with a blank
space between data and time;
• for example, TIMESTAMP ‘2014-09-27 09:12:47.648302’.
• Another data type related to DATE, TIME, and TIMESTAMP is the
INTERVAL data type. This specifies an interval—a relative value that can be
used to increment or decrement an absolute value of a date, time, or timestamp.
Intervals are qualified to be either YEAR/MONTH intervals or DAY/TIME
intervals.

Domains

 It is possible to specify the data type of each attribute directly,;


 Alternatively, a domain can be declared, and the domain name can be used with
the attribute specification.
 This makes it easier to change the data type for a domain that is used by
numerous attributes in a schema, and improves schema readability.
CREATE DOMAIN SSN_TYPE AS CHAR(9);

• We can use SSN_TYPE in place of CHAR(9) for the attributes Ssn and
Super_ssn of EMPLOYEE, Mgr_ssn of DEPARTMENT, Essn of WORKS_ON,
and Essn of DEPENDENT.
• A domain can also have an optional default specification via a DEFAULT
clause.

The CREATE TABLE Command in SQL

 An SQL schema is identified by a schema name and includes an authorization


identifier to indicate the user or account who owns the schema, as well as
descriptors for each element in the schema.
 Schema elements include tables, types, constraints, views, domains, and other
constructs (such as authorization grants) that describe the schema.
 A schema is created via the CREATE SCHEMA statement, which can include all the
schema elements’ definitions.
CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith’;

 In general, not all users are authorized to create schemas and schema elements.
The privilege to create schemas, tables, and other constructs must be explicitly
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

granted to the relevant user accounts by the system administrator or DBA.

 The CREATE TABLE command is used to specify a new relation by giving it a


name and specifying its attributes and initial constraints.
 The attributes are specified first, and each attribute is given a name, a data type to
specify its domain of values, and possibly attribute constraints, such as NOT NULL.
 Examples:

CREATE TABLE EMPLOYEE( Fname VARCHAR(15) NOT NULL, Minit CHAR,


Lname VARCHAR(15) NOT NULL, Ssn CHAR(9) NOT NULL, Bdate DATE, Address
VARCHAR(30), Sex CHAR, Salary DECIMAL(10,2), Super_ssn CHAR(9), Dno INT NOT
NULL,
PRIMARY KEY (Ssn));

CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL, Dnumber INT NOT
NULL, Mgr_ssn CHAR(9) NOT NULL, Mgr_start_date DATE,
PRIMARY KEY (Dnumber),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn) );

CREATE TABLE DEPT_LOCATIONS( Dnumber INT NOT NULL, Dlocation


VARCHAR(15) NOT NULL,
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber) );

Specifying Constraints in SQL

The different types of constraints are:


 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 DEFUALT
 CHECK
 User defined constraints by using triggers and assertions.

• Because SQL allows NULLs as attribute values, a constraint NOT NULL may be
specified if NULL is not permitted for a particular attribute.
• This is always implicitly specified for the attributes that are part of the primary key of
each relation, but it can be specified for any other attributes whose values are required
not to be NULL.
• It is also possible to define a default value for an attribute by appending the clause
DEFAULT <value> to an attribute definition.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

• The default value is included in any new tuple if an explicit value is not provided for
that attribute . If no default clause is specified, the default default value is NULL for
attributes that do not have the NOT NULL constraint.
• Another type of constraint can restrict attribute or domain values using the
CHECK clause following an attribute or domain definition.
• The PRIMARY KEY clause specifies one or more attributes that make up the
primary key of a relation.
• If a primary key has a single attribute, the clause can follow the attribute directly.
Dnumber INT PRIMARY KEY,
• The UNIQUE clause specifies alternate (unique) keys, also known as candidate keys.
• The UNIQUE clause can also be specified directly for a unique key if it is a single
attribute, as in the following example:
Dname VARCHAR(15) UNIQUE,
• Referential integrity is specified via the FOREIGN KEY clause.
• A referential integrity constraint can be violated when tuples are inserted or deleted,
or when a foreign key or primary key attribute value is updated.
• The default action that SQL takes for an integrity violation is to reject the update
operation that will cause a violation, which is known as the RESTRICT option.
• However, the schema designer can specify an alternative action to be taken by
attaching a referential triggered action clause to any foreign key constraint. The
options include SET NULL, CASCADE, and SET DEFAULT. An option must be
qualified with either ON DELETE or ON UPDATE.
• Another type of constraint can restrict attribute or domain values using the
CHECK clause following an attribute or domain definition.
• For example: suppose that department numbers are restricted to integer
numbers between 1 and 20; then, we can change the attribute declaration of
Dnumber in the DEPARTMENT table to the following:

Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);

• The CHECK clause can also be used in conjunction with the CREATE DOMAIN
statement.
• For example, we can write the following statement:

CREATE DOMAIN D_NUM AS


INTEGER CHECK (D_NUM > 0 AND
D_NUM < 21);

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

• Giving Names to Constraints


• A constraint may be given a constraint name, following the keyword
CONSTRAINT. The names of all constraints within a particular schema
must be unique.
• A constraint name is used to identify a particular constraint in case the
constraint must be dropped later and replaced with another constraint.
• Giving names to constraints is optional.
• It is also possible to temporarily defer a constraint until the end of a
transaction

CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL, Dnumber INT NOT
NULL, Mgr_ssn CHAR(9) NOT NULL, Mgr_start_date DATE,
CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
CONSTRAINT DEPTSK UNIQUE (Dname),
CONSTRAINT DEPTMGRFK FOREIGN KEY (Mgr_ssn) REFERENCES
EMPLOYEE(Ssn) ON DELETE SET DEFAULT ON UPDATE CASCADE);

Basic Retrieval Queries in SQL


• SQL has one basic statement for retrieving information from a database: the
SELECT statement.
• The SELECT statement is not the same as the SELECT operation of relational algebra.
• SQL allows a table (relation) to have two or more tuples that are identical in all their
attribute values.
• Hence, in general, an SQL table is not a set of tuples, because a set does not allow two
identical members; rather, it is a multiset (sometimes called a bag) of tuples.

SELECT <attribute list>


FROM <table list>
WHERE <condition>;

Where

• <attribute list> is a list of attribute names whose values are to be retrieved by the
query.
• <table list> is a list of the relation names required to process the query.
• <condition> is a conditional (Boolean) expression that identifies the tuples to be
retrieved by the query.

• In SQL, the basic logical comparison operators for comparing attribute values with
one another and with literal constants are =, <, <=, >, >=, and <>. These correspond to
the relational algebra operators =, <, ≤, >, ≥, and ≠, respectively.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

• The SELECT clause of SQL specifies the attributes whose values are to be retrieved,
which are called the projection attributes in relational algebra and the WHERE
clause specifies the Boolean condition that must be true for any retrieved tuple, which
is known as the selection condition in relational algebra.
• We can think of an implicit tuple variable or iterator in the SQL query ranging or
looping over each individual tuple in the EMPLOYEE table and evaluating the
condition in the WHERE clause. Only those tuples that satisfy the condition—that is,
those tuples for which the condition evaluates to TRUE after substituting their
corresponding attribute values—are selected.

Examples:
i. Retrieve the birth date and address of the employee(s) whose name is ‘John
B. Smith’.

SELECT Bdate, Address


FROM EMPLOYEE
WHERE Fname = ‘John’ AND Minit = ‘B’ AND Lname = ‘Smith’;

ii. Retrieve the name and address of all employees who work for the
‘Research’ department.

SELECT Fname, Lname, Address


FROM EMPLOYEE, DEPARTMENT
WHERE Dname = ‘Research’ AND Dnumber = Dno;

iii. For every project located in ‘Stafford’, list the project number, the controlling
department number, and the department manager’s last name, address, and birth date.

SELECT Pnumber, Dnum, Lname, Address, Bdate


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Plocation = ‘Stafford’;

Ambiguous Attribute Names, Aliasing, Renaming, and Tuple Variables

• In SQL, the same name can be used for two (or more) attributes as long as the
attributes are in different tables.
• If this is the case, and a multitable query refers to two or more attributes with the
same name, we must qualify the attribute name with the relation name to prevent
ambiguity. This is done by prefixing the relation name to the attribute name and
separating the two by a period.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

Example:
SELECT Fname, EMPLOYEE.Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.Name = ‘Research’ AND
DEPARTMENT.Dnumber = EMPLOYEE.Dnumber;

• Fully qualified attribute names can be used for clarity even if there is no
ambiguity in attribute names.
• We can also rename the table names to shorter names by creating an alias for each
table name to avoid repeated typing of long table names.

Example: For each employee, retrieve the employee’s first and last name and
thefirst and last name of his or her immediate supervisor.

SELECT E.Fname, E.Lname, S.Fname, S.Lname


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn = S.Ssn;

• We can use this alias-naming or renaming mechanism in any SQL query to specify
tuple variables for every table in the WHERE clause, whether or not the same relation
needs to be referenced more than once.

SELECT E.Fname, E.LName, E.Address


FROM EMPLOYEE AS E, DEPARTMENT AS D
WHERE D.DName = ‘Research’ AND D.Dnumber = E.Dno;

• It is also possible to rename the relation attributes within the query in SQL by
giving them aliases.
• Example: if we write
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex, Sal, Sssn, Dno)
in the FROM clause, Fn becomes an alias for Fname, Mi for Minit, Ln for Lname, and
so on.

Unspecified WHERE Clause and Use of the Asterisk

• A missing WHERE clause indicates no condition on tuple selection; hence, all tuples
of the relation specified in the FROM clause qualify and are selected for the query
result. If more than one relation is specified in the FROM clause and there is no
WHERE clause, then the CROSS PRODUCT—all possible tuple combinations—of
these relations is selected.

SELECT Ssn, Dname


FROM EMPLOYEE, DEPARTMENT;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

• The above Query selects all combinations of an EMPLOYEE Ssn and a


DEPARTMENT Dname, regardless of whether the employee works for the
department or not.
• To retrieve all the attribute values of the selected tuples, we do not have to list the
attribute names explicitly in SQL; we just specify an asterisk (*), which stands for all
the attributes.
• The * can also be prefixed by the relation name or alias; for example, EMPLOYEE.*
refers to all attributes of the EMPLOYEE table.
• Example:1. Retrieve all the attribute values of any EMPLOYEE who works in
DEPARTMENT number 5.

SELECT *
FROM EMPLOYEE
WHERE Dno = 5;

 Retrieve all the attributes of an EMPLOYEE and the attributes of the


DEPARTMENT in which he or she works for every employee of the
‘Research’ department.

SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE Dname = ‘Research’ AND Dno = Dnumber;

The query given below specifies the CROSS PRODUCT of the EMPLOYEE
and DEPARTMENT relations

SELECT *
FROM EMPLOYEE, DEPARTMENT;
.
Tables as Sets in SQL

 SQL usually treats a table not as a set but rather as a multiset; duplicate tuples can
appear more than once in a table, and in the result of a query.
 SQL does not automatically eliminate duplicate tuples in the results of
queries, for the following reasons:
 Duplicate elimination is an expensive operation. One way to implement it is to
sort the tuples first and then eliminate duplicates.
 The user may want to see duplicate tuples in the result of a query.
 When an aggregate function is applied to tuples, in most cases we do not
want to eliminate duplicates.

 An SQL table with a key is restricted to being a set, since the key value must be
distinct in each tuple.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 If we do want to eliminate duplicate tuples from the result of an SQL query, we use
the keyword DISTINCT in the SELECT clause, meaning that only distinct tuples
should remain in the result. In general, a query with SELECT DISTINCT
eliminates duplicates, whereas a query with SELECT ALL does not.
 Specifying SELECT with neither ALL nor DISTINCT is equivalent to SELECT ALL.

 Example1: Retrieve the salary of every employee

SELECT ALL Salary


FROM EMPLOYEE;

 Example2: Retrieve all distinct salary employees

SELECT DISTINCT Salary


FROM EMPLOYEE;

 SQL has directly incorporated some of the set operations from mathematical set
theory, which are also part of relational algebra.
 There are set union (UNION), set difference (EXCEPT), and set intersection
(INTERSECT) operations.
 The relations resulting from these set operations are sets of tuples; that is,
duplicate tuples are eliminated from the result.
 These set operations apply only to type compatible relations, so we must make sure
that the two relations on which we apply the operation have the same attributes and
that the attributes appear in the same order in both relations.

 Example: Make a list of all project numbers for projects that involve an
employee whose last name is ‘Smith’, either as a worker or as a manager of the
department that controls the project.

( SELECT DISTINCT Pnumber


FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Lname =
‘Smith’ )

UNION

( SELECT DISTINCT Pnumber


FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE Pnumber = Pno AND Essn = Ssn AND Lname = ‘Smith’ );

 SQL also has corresponding multiset operations, which are followed by the keyword
ALL (UNION ALL, EXCEPT ALL, INTERSECT ALL). Their results are multisets
(duplicates are not eliminated).

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

Substring Pattern Matching and Arithmetic Operators

 Substring Pattern Matching


 Using the LIKE comparison operator: This can be used for string pattern
matching. Partial strings are specified using two reserved characters: % replaces an
arbitrary number of zero or more characters, and the underscore ( _ ) replaces a single
character.
 Example: Retrieve all employees whose address is in Houston, Texas.

SELECT Fname, Lname


FROM EMPLOYEE
WHERE Address LIKE ‘%Houston,TX%’;

 Example: Find all employees who were born during the 1950s.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Bdate LIKE ‘_ _ 7______ ’;

 If an underscore or % is needed as a literal character in the string, the character should


be preceded by an escape character, which is specified after the string using the
keyword ESCAPE.
 For example, ‘AB\_CD\%EF’ ESCAPE ‘\’ represents the literal string
‘AB_CD%EF’ because \ is specified as the escape character.
 Any character not used in the string can be chosen as the escape character.
 Also, we need a rule to specify apostrophes or single quotation marks (‘ ’) if they are
to be included in a string because they are used to begin and end strings.
 If an apostrophe (’) is needed, it is represented as two consecutive apostrophes (”) so
that it will not be interpreted as ending the string.

Arithmetic Operators

 The standard arithmetic operators for addition (+), subtraction (−), multiplication (*),
and division (/) can be applied to numeric values or attributes with numeric domains.
 Example: raise the salary of all employees who work on the ‘ProductX’ project
by 10%.

SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal


FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE E.Ssn = W.Essn AND W.Pno = P.Pnumber AND P.Pname = ‘ProductX’;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 For string data types, the concatenate operator || can be used in a query to append
two string values.
 For date, time, timestamp, and interval data types, operators include incrementing
(+) or decrementing (−) a date, time, or timestamp by an interval.
 In addition, an interval value is the result of the difference between two date, time, or
timestamp values. Another comparison operator, which can be used for convenience,
is BETWEEN.
 Example: Retrieve all employees in department 5 whose salary is between
$30,000 and $40,000.

SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;

Ordering of Query Results

 SQL allows the user to order the tuples in the result of a query by the values of one or
more of the attributes that appear in the query result, by using the ORDER BY clause.
 Example: Retrieve a list of employees and the projects they are working on, ordered
by department and, within each department, ordered alphabetically by last name, then
first name.

SELECT D.Dname, E.Lname, E.Fname, P.Pname


FROM DEPARTMENT AS D, EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE D.Dnumber = E.Dno AND E.Ssn = W.Essn AND W.Pno =P.Pnumber
ORDER BY D.Dname, E.Lname, E.Fname;

 The default order is in ascending order of values.


 We can specify the keyword DESC if we want to see the result in a descending
order of values.
 The keyword ASC can be used to specify ascending order explicitly.

 Example:
SELECT D.Dname, E.Lname, E.Fname, P.Pname
FROM DEPARTMENT AS D, EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE D.Dnumber = E.Dno AND E.Ssn = W.Essn AND W.Pno =P.Pnumber
ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

INSERT Statement in SQL

 INSERT is used to add a single tuple (row) to a relation (table).


 We must specify the relation name and a list of values for the tuple.
 The values should be listed in the same order in which the corresponding
attributes were specified in the CREATE TABLE command.

 Example:
INSERT INTO EMPLOYEE VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’,
‘1962- 12-30’, ’98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 );

 A second form of the INSERT statement allows the user to specify explicit
attribute names that correspond to the values provided in the INSERT command.
 This is useful if a relation has many attributes but only a few of those attributes are
assigned values in the new tuple.
 However, the values must include all attributes with NOT NULL specification and
no default value.
 Example: INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn)
VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’);

 A DBMS that fully implements SQL should support and enforce all the integrity
constraints that can be specified in the DDL.
 Example1:
INSERT INTO EMPLOYEE (Fname, Lname, Ssn, Dno)
VALUES (‘Robert’, ‘Hatcher’, ‘980760540’, 2);
The DBMS should reject the operation if no DEPARTMENT tuple exists in the
database with Dnumber = 2.

 Example2: INSERT INTO EMPLOYEE (Fname, Lname, Dno)


VALUES (‘Robert’, ‘Hatcher’, 5);
This query would be rejected because no Ssn value is provided and it is the
primary key, which cannot be NULL.

 A variation of the INSERT command inserts multiple tuples into a relation in


conjunction with creating the relation and loading it with the result of a query.
 Example: to create a temporary table that has the employee last name, project name,
and hours per week for each employee working on a project.

1. CREATE TABLE WORKS_ON_INFO ( Emp_name VARCHAR(15),


Proj_name VARCHAR(15), Hours_per_week DECIMAL(3,1) );

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

2. INSERT INTO WORKS_ON_INFO ( Emp_name, Proj_name, Hours_per_week )


SELECT E.Lname, P.Pname, W.Hours
FROM PROJECT P, WORKS_ON W, EMPLOYEE E
WHERE P.Pnumber = W.Pno AND W.Essn = E.Ssn;

 Another variation for loading data is to create a new table TNEW that has the same
attributes as an existing table T, and load some of the data currently in T into TNEW.
 The syntax for doing this uses the LIKE clause.

 Example: create a table D5EMPS with a similar structure to the EMPLOYEE table
and load it with the rows of employees who work in department 5,

 CREATE TABLE D5EMPS LIKE


EMPLOYEE (SELECT E.*
FROM EMPLOYEE AS E
WHERE E.Dno = 5) WITH DATA;

 The clause WITH DATA specifies that the table will be created and loaded with the
data specified in the query, although in some implementations it may be left out.

The DELETE Command

 The DELETE command removes tuples from a relation.


 It includes a WHERE clause, similar to that used in an SQL query, to select the
tuples to be deleted.
 Tuples are explicitly deleted from only one table at a time.
 However, the deletion may propagate to tuples in other relations if referential
triggered actions are specified in the referential integrity constraints of the DDL .
 Depending on the number of tuples selected by the condition in the WHERE
clause, zero, one, or several tuples can be deleted by a single DELETE command.
 Example 1:

DELETE FROM EMPLOYEE


WHERE Lname = ‘Brown’;

 Example 2:

DELETE FROM EMPLOYEE


WHERE Dno = 5;

 A missing WHERE clause specifies that all tuples in the relation are to be
deleted; however, the table remains in the database as an empty table.
 Example 3: DELETE FROM EMPLOYEE;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 Note: We must use the DROP TABLE command to remove the table
definition.

The UPDATE Command

 The UPDATE command is used to modify attribute values of one or more selected
tuples.
 As in the DELETE command, a WHERE clause in the UPDATE command selects the
tuples to be modified from a single relation.
 However, updating a primary key value may propagate to the foreign key values of
tuples in other relations if such a referential triggered action is specified in the
referential integrity constraints of the DDL .
 An additional SET clause in the UPDATE command specifies the attributes to be
modified and their new values.
 Example 1: change the location and controlling department number of project
number 10 to ‘Bellaire’ and 5.
UPDATE PROJECT
SET Plocation = ‘Bellaire’, Dnum = 5
WHERE Pnumber = 10;\

 Several tuples can be modified with a single UPDATE command.


 Example: Give all employees in the ‘Research’ department a 10% raise in salary.

UPDATE EMPLOYEE
SET Salary = Salary * 1.1
WHERE Dno = 5;

 Note: each UPDATE command explicitly refers to a single relation only. To modify
multiple relations, we must issue several UPDATE commands.

Schema Change Statements in SQL

The DROP Command

 The DROP command can be used to drop named schema elements, such as tables,
domains, types, or constraints.
 One can also drop a whole schema if it is no longer needed by using the DROP
SCHEMA command.
 There are two drop behavior options: CASCADE and RESTRICT.

DROP SCHEMA COMPANY CASCADE;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 If the RESTRICT option is chosen in place of CASCADE, the schema is dropped


only if it has no elements in it; otherwise, the DROP command will not be executed.
 To use the RESTRICT option, the user must first individually drop each element in
the schema, then drop the schema itself.
 If a base relation within a schema is no longer needed, the relation and its definition
can be deleted by using the DROP TABLE command.

DROP TABLE DEPENDENT CASCADE;

 If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it


is not referenced in any constraints or by any other elements.
 With the CASCADE option, all such constraints, views, and other elements that
reference the table being dropped are also dropped automatically from the schema,
along with the table itself.

The ALTER Command

 The definition of a base table or of other named schema elements can be changed by
using the ALTER command.
 For base tables, the possible alter table actions include adding or dropping a column
(attribute), changing a column definition, and adding or dropping table constraints.

Example: ALTER TABLE EMPLOYEE ADD COLUMN Job VARCHAR(12);

NOTE:

We must still enter a value for the new attribute Job for each individual EMPLOYEE tuple.
This can be done either by specifying a default clause or by using the UPDATE command
individually on each tuple .If no default clause is specified, the new attribute will have
NULLs in all the tuples of the relation immediately after the command is executed; hence, the
NOT NULL constraint is not allowed in this case.

 To drop a column, we must choose either CASCADE or RESTRICT for drop


behavior. If CASCADE is chosen, all constraints and views that reference the column
are dropped automatically from the schema, along with the column. If RESTRICT is
chosen, the command is successful only if no views or constraints (or other schema
elements) reference the column.

ALTER TABLE EMPLOYEE DROP COLUMN Address CASCADE;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 It is also possible to alter a column definition by dropping an existing default clause


or by defining a new default clause.
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn
DROP DEFAULT;

ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn


SET DEFAULT ‘333445555’;

 One can also change the constraints specified on a table by adding or dropping a named
constraint.
 To be dropped, a constraint must have been given a name when it was specified.

ALTER TABLE COMPANY.EMPLOYEE


DROP CONSTRAINT EMPSUPERFK CASCADE;

Summary of SQL Commands

ALTER TABLE:

1. Add a Column:
ALTER TABLE table_name ADD column_name datatype;
2. Drop a Column:
ALTER TABLE table_name DROP column_name;
3. Modify a Column (Change datatype or other attributes):
ALTER TABLE table_name MODIFY column_name new_datatype;
4. Rename a Column:
ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
5. Add or Drop Constraints (e.g., PRIMARY KEY, FOREIGN KEY, UNIQUE, DEFAULT):
ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint_definition;
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
6. Rename Table:
ALTER TABLE old_table_name RENAME TO new_table_name;

Delete:

1. DELETE FROM MyTable;

2. DELETE FROM MyTable


WHERE column_name = value;

Update:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

COMPARISONS INVOLVING NULL AND THREE-VALUED LOGIC


 Consider the following examples to illustrate each of the meanings of NULL.
1. Unknown value. A person’s date of birth is not known, so it is represented by NULL in the
database. An example of the other case of unknown would be NULL for a person’s home
phone because it is not known whether or not the person has a home phone.
2. Unavailable or withheld value. A person has a home phone but does not want it to be
listed, so it is withheld and represented as NULL in the database.
3. Not applicable attribute. An attribute LastCollegeDegree would be NULL for aperson
who has no college degrees because it does not apply to that person.

 In general, each individual NULL value is considered to be different from every other
NULL value in the various database records.
 When a record with NULL in one of its attributes is involved in a comparison operation, the
result is considered to beUNKNOWN (it may be TRUE or it may be FALSE).
 Hence, SQL uses a three-valued logic with values TRUE, FALSE, and UNKNOWN
instead of the standard two-valued (Boolean) logic with values TRUE or FALSE.
 It is therefore necessary to define the results (or truth values) of three-valued logical
expressions when the logical connectives AND, OR, and NOT are used.

 SQL allows queries that check whether an attribute value is NULL.


 Rather than using= or <> to compare an attribute value to NULL, SQL uses the
comparison operators IS or IS NOT.
 This is because SQL considers each NULL value as being distinct from every other
NULL value, so equality comparison is not appropriate. It follows that when a join
condition is specified, tuples with NULL values for the join attributes are not included in
the result.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 Example: Retrieve the names of all employees who do not have supervisors.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Super_ssn IS NULL;

NESTED QUERIES, TUPLES AND SET/MULTISET COMPARISONS

 Some queries require that existing values in the database be fetched and then used in a
comparison condition. Such queries can be conveniently formulated by using nested
queries, which are complete select-from-where blocks within another SQL query. That
other query is called the outer query.
 These nested queries can also appear in the WHERE clause or the FROM clause or the
SELECT clause or other SQL clauses as needed.
 The comparison operator IN, which compares a value v with a set (or multiset) of values
V and evaluates to TRUE if v is one of the elements in V.
 If a nested query returns a single attribute and a single tuple, the query result will be a
single (scalar) value.
 In such cases, it is permissible to use = instead of IN for the comparison operator.
 In general, the nested query will return a table (relation), which is a set or multiset of
tuples.
 Example 1: selects the project numbers of projects that have an employee with last
name ‘Smith’ involved as manager or as a employee

SELECT DISTINCT Pnumber


FROM PROJECT
WHERE Pnumber IN ( SELECT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Lname = ‘Smith’ )
OR
Pnumber IN ( SELECT Pno
FROM WORKS_ON, EMPLOYEE
WHERE Essn = Ssn AND Lname = ‘Smith’ );

 SQL allows the use of tuples of values in comparisons by placing them within
parentheses.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 Example 2: select the Essns of all employees who work the same (project, hours)
combination on some project that employee ‘John Smith’ (whose Ssn = ‘123456789’) works
on.

SELECT DISTINCT Essn


FROM WORKS_ON
WHERE (Pno, Hours) IN ( SELECT Pno, Hours
FROM WORKS_ON
WHERE Essn = ‘123456789’ );

 In addition to the IN operator, a number of other comparison operators can be used to


compare a single value v (typically an attribute name) to a set or multiset v (typically a
nested query).
 The = ANY (or = SOME) operator returns TRUE if the value v is equal to some value in
the set V and is hence equivalent to IN.The two keywords ANY and SOME have the
same effect.
 Other operators that can be combined with ANY (or SOME) include >, >=, <, <=, and
<>. The keyword ALL can also be combined with each of these operators.
 For example, the comparison condition (v > ALL V) returns TRUE if the value v is
greater than all the values in the set (or multiset) V.
 Example 3: Find names of employees whose salary is greater than the salary of all the
employees in department 5:
SELECT Lname, Fname
FROM EMPLOYEE
WHERE Salary > ALL ( SELECT Salary
FROM EMPLOYEE
WHERE Dno = 5 );

 Example 4:Retrieve the name of each employee who has a dependent with the same first
name and is the same sex as the employee.

SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name AND E.Sex = D.Sex );

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

CORRELATED NESTED QUERIES

Whenever a condition in the WHERE clause of a nested query references some attribute of a relation
declared in the outer query, the two queries are said to be correlated.

 Example 4: Retrieve the name of each employee who has a dependent with the
same first name and is the same sex as the employee.

ANS1: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name AND E.Sex = D.Sex );

ANS 2: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn = D.Essn AND E.Sex = D.Sex
AND E.Fname = D.Dependent_name;

EXISTS and UNIQUE Functions in SQL


 EXISTS and UNIQUE are Boolean functions that return TRUE or FALSE; hence, they
can be used in a WHERE clause condition.
 The EXISTS function in SQL is used to check whether the result of a nested query is
empty (contains no tuples) or not.
 The result of EXISTS is a Boolean value TRUE if the nested query result contains at
least one tuple, or FALSE if the nested query result contains no tuples.

 Example 4: Retrieve the name of each employee who has a dependent with the
same first name and is the same sex as the employee.

SELECT E.Fname, E.Lname FROM EMPLOYEE AS E WHERE EXISTS


( SELECT *
FROM DEPENDENT AS D
WHERE E.Ssn = D.Essn AND E.Sex = D.Sex
AND E.Fname = D.Dependent_name);

 Example 5: Retrieve the names of employees who have no dependents.

SELECT Fname, Lname


FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 Example 6: List the names of managers who have at least one dependent.

SELECT Fname, Lname


FROM EMPLOYEE
WHERE EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn )
AND
EXISTS
( SELECT *
FROM DEPARTMENT
WHERE Ssn = Mgr_ssn );

Example 7: Retrieve the name of each employee who works on all the projects
controlled by department number 5

SELECT Fname, Lname


FROM EMPLOYEE
WHERE NOT EXISTS ( ( SELECT Pnumber
FROM PROJECT
WHERE Dnum = 5)
EXCEPT ( SELECT Pno
FROM WORKS_ON
WHERE Ssn = Essn) );

EXPLICIT SETS AND RENAMING IN SQL


EXPLICIT SETS
 It is also possible to use an explicit set of values in the WHERE clause, rather than a
nested query.
 Example 8: Retrieve the Social Security numbers of all employees who work on
project numbers 1, 2, or 3.
SELECT DISTINCT Essn
FROM WORKS_ON
WHERE Pno IN (1, 2, 3);

RENAMING IN SQL
 In SQL, it is possible to rename any attribute that appears in the result of a query by
adding the qualifier AS followed by the desired new name.
 Hence, the AS construct can be used to alias both attribute and relation names in
general, and it can be used in appropriate parts of a query.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 Example 9: find the details of employee and their immediate supervisor

SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn = S.Ssn;

JOINED TABLES IN SQL AND OUTER JOINS

 The concept of a joined table (or joined relation) was incorporated into SQL to permit
users to specify a table resulting from a join operation in the FROM clause of a query.
 This construct may be easier to comprehend than mixing together all the select and join
conditions in the WHERE clause.
 Example1: retrieves the name and address of every employee who works for the
‘Research’ department

SELECT Fname, Lname, Address


FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

 The concept of a joined table also allows the user to specify different types of join, such
as NATURAL JOIN and various types of OUTER JOIN.
 In a NATURAL JOIN on two relations R and S, no join condition is specified; an implicit
EQUIJOIN condition for each pair of attributes with the same name from R and S is
created.
 Each such pair of attributes is included only once in the resulting relation.
 If the names of the join attributes are not the same in the base relations, it is possible to
rename the attributes so that they match, and then to apply NATURAL JOIN.
 In this case, the AS construct can be used to rename a relation and all its attributes in the
FROM clause.

SELECT Fname, Lname, Address


FROM (EMPLOYEE NATURAL JOIN(DEPARTMENT AS DEPT (Dname,
Dno, Mssn, Msdate)))
WHERE Dname = ‘Research’;

 The default type of join in a joined table is called an inner join, where a tuple is included
in the result only if a matching tuple exists in the other relation.
SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name
FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S
ON E.Super_ssn = S.Ssn);
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 It is also possible to nest join specifications; that is, one of the tables in a join may itself be
a joined table.
 This allows the specification of the join of three or more tables as a single joined table,
which is called a multiway join.

SELECT Pnumber, Dnum, Lname, Address, Bdate


FROM ((PROJECT JOIN DEPARTMENT ON Dnum = Dnumber)
JOIN EMPLOYEE ON Mgr_ssn = Ssn)
WHERE Plocation = ‘Stafford’;

 Not all SQL implementations have implemented the new syntax of joined tables.
 In some systems, a different syntax was used to specify outer joins by using the
comparison operators + =, = +, and + = + for left, right, and full outer join, respectively,
when specifying the join condition.

SELECT E.Lname, S.Lname


FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn + = S.Ssn;

AGGREGATE FUNCTIONS IN SQL

 Aggregate functions are used to summarize information from multiple tuples into a
single-tuple summary.
 Grouping is used to create subgroups of tuples before summarization. Grouping and
aggregation are required in many database applications, and we will introduce their use in
SQL through examples.
 A number of built-in aggregate functions exist: COUNT, SUM, MAX, MIN, and AVG.
 The COUNT function returns the number of tuples or values as specified in a query.
 The functions SUM, MAX, MIN, and AVG can be applied to a set or multiset of numeric
values and return, respectively, the sum, maximum value, minimum value, and average
(mean) of those values.
 These functions can be used in the SELECT clause or in a HAVING clause.
 Example10: Find the sum of the salaries of all employees, the maximum salary, the
minimum salary, and the average salary.

SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)


FROM EMPLOYEE;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 We could use AS to rename the column names in the resulting single-row table; for
example, as in example 10.
SELECT SUM (Salary) AS Total_Sal, MAX (Salary) AS Highest_Sal,
MIN (Salary) AS Lowest_Sal, AVG (Salary) AS Average_Sal
FROM EMPLOYEE;

 Example11: Find the sum of the salaries of all employees of the ‘Research’ department,
as well as the maximum salary, the minimum salary, and the average salary in this
department.

SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)


FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

 Example12: Retrieve the total number of employees in the company


SELECT COUNT (*)
FROM EMPLOYEE;

 Example13: Retrieve the number of employees in the ‘Research’ department.

SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO = DNUMBER AND DNAME = ‘Research’;

 Example14: Count the number of distinct salary values in the database.

SELECT COUNT (DISTINCT Salary)


FROM EMPLOYEE;

 Example14: retrieve the names of all employees who have two or more
dependents.

SELECT Lname, Fname


FROM EMPLOYEE
WHERE ( SELECT COUNT (*)
FROM DEPENDENT
WHERE Ssn = Essn ) > = 2;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

GROUPING: THE GROUP BY AND HAVING CLAUSES

 In many cases we want to apply the aggregate functions to subgroups of tuples in a


relation, where the subgroups are based on some attribute values.
 Example 15: For each department, retrieve the department number, the number of
employees in the department, and their average salary.

SELECT Dno, COUNT (*), AVG (Salary)


FROM EMPLOYEE
GROUP BY Dno;

 Note: If NULLs exist in the grouping attribute, then a separate group is created for all
tuples with a NULL value in the grouping attribute.

 Example 16: For each project, retrieve the project number, the project name, and the
number of employees who work on that project.

SELECT Pnumber, Pname, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname;

 Sometimes we want to retrieve the values of these functions only for groups that satisfy
certain conditions. SQL provides a HAVING clause, which can appear in conjunction
with a GROUP BY clause, for this purpose.
 HAVING provides a condition on the summary information regarding the group of
tuples associated with each value of the grouping attributes. Only the groups that satisfy
the condition are retrieved in the result of the query.
 Example 17: For each project on which more than two employees work, retrieve the
project number, the project name, and the number of employees who work on the project.

SELECT Pnumber, Pname, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 Example 18:For each project, retrieve the project number, the project name, and the
number of employees from department 5 who work on the project.

SELECT Pnumber, Pname, COUNT (*)


FROM PROJECT, WORKS_ON, EMPLOYEE
WHERE Pnumber = Pno AND Ssn = Essn AND Dno = 5
GROUP BY Pnumber, Pname;

 Example 19: For each department that has more than five employees, retrieve the
department number and the number of its employees who are making more than
$40,000.

SELECT Dno, COUNT (*)


FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN( SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) >
5)
GROUP BY Dno;

Other SQL Constructs: WITH and CASE

 The WITH clause allows a user to define a table that will only be used in a particular
query; it is somewhat similar to creating a view that will be used only in one query and
then dropped.
 Example:

WITH BIGDEPTS (Dno) AS


( SELECT Dno
FROM
EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN BIGDEPTS
GROUP BY Dno;

 In the above example ,we defined in the WITH clause a temporary table BIG_DEPTS
whose result holds the Dno’s of departments with more than five employees, then used
this table in the subsequent query. Once this query is executed, the temporary table
BIGDEPTS is discarded.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 SQL also has a CASE construct, which can be used when a value can be different based on
certain conditions. This can be used in any part of an SQL query where a value is
expected, including when querying, inserting or updating tuples.

 Example: Suppose we want to give employees different raise amounts depending on


which department they work for; for example, employees in department 5 get a
$2,000 raise, those in department 4 get $1,500 and those in department 1 get $3,000.

UPDATE EMPLOYEE
SET Salary =
CASE WHEN Dno = 5 THEN Salary +
2000 WHEN Dno = 4 THEN Salary
+ 1500 WHEN Dno = 1 THEN
Salary + 3000
ELSE Salary + 0;

 The CASE construct can also be used when inserting tuples that can have different
attributes being NULL depending on the type of record being inserted into a table, as
when a specialization is mapped into a single table or when a union type is mapped into
relations.

SUMMARY:
SELECT <attribute and function list>
FROM <table list>
[ WHERE <condition> ]
[ GROUP BY <grouping attribute(s)> ]
[ HAVING <group condition> ]
[ ORDER BY <attribute list> ];

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

Specifying General Constraints as Assertions in SQL


 In SQL, users can specify general constraints via declarative assertions, using the
CREATE ASSERTION statement.
 Each assertion is given a constraint name and is specified via a condition similar to the
WHERE clause of an SQL query.
 Example, specify the constraint that the salary of an employee must not be greater than
the salary of the manager of the department that the employee works for in SQL.

CREATE ASSERTION SALARY_CONSTRAINT


CHECK ( NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M,DEPARTMENT D
WHERE E.Salary>M.Salary
AND E.Dno = D.Dnumber
AND D.Mgr_ssn = M.Ssn ) );

 The basic technique for writing such assertions is to specify a query that selects any
tuples that violate the desired condition.
 By including this query inside a NOT EXISTS clause, the assertion will specify that the
result of this query must be empty so that the condition will always be TRUE.
 Thus, the assertion is violated if the result of the query is not empty.
 In the preceding example, the query selects all employees whose salaries are greater than
the salary of the manager of their department. If the result of the query is not empty, the
assertion is violated.
 A major difference between CREATE ASSERTION and the individual domain
constraints and tuple constraints is that = the CHECK clauses on individual attributes,
domains, and tuples are checked in SQL only when tuples are inserted or updated in a
specific table.
 Hence, constraint checking can be implemented more efficiently by the DBMS in these
cases.
 The schema designer should use CHECK on attributes, domains, and tuples only when he
or she is sure that the constraint can only be violated by insertion or updating of tuples.
 On the other hand, the schema designer should use CREATE ASSERTION only in cases
where it is not possible to use CHECK on attributes, domains, or tuples, so that simple
checks are implemented more efficiently by the DBMS.

DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

Actions as Triggers

 In many cases it is convenient to specify the type of action to be taken when certain
events occur and when certain conditions are satisfied.
 The CREATE TRIGGER statement is used to implement such actions in SQL.

CREATE TRIGGER SALARY_VIOLATION


BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE
FOR EACH ROW
WHEN ( NEW.SALARY > ( SELECT SALARY FROM EMPLOYEE
WHERE SSN = NEW.SUPERVISOR_SSN ) )
INFORM_SUPERVISOR( NEW.Supervisor_ssn, NEW.Ssn );

 A typical trigger which is regarded as an ECA (Event, Condition, Action) rule has three
components:
a. The event(s):
 These are usually database update operations that are explicitly applied to the
database.
 In this example the events are: inserting a new employee record, changing an
employee’s salary, or changing an employee’s supervisor.
 The person who writes the trigger must make sure that all possible events are
accounted for.
 In some cases, it may be necessary to write more than one trigger to cover all
possible cases.
 These events are specified after the keyword BEFORE in our example, which
means that the trigger should be executed before the triggering operation is
executed.
 An alternative is to use the keyword AFTER, which specifies that the trigger
should be executed after the operation specified in the event is completed.
b. The condition that determines whether the rule action should be executed:
 Once the triggering event has occurred, an optional condition may be evaluated.
 If no condition is specified, the action will be executed once the event occurs. If a
condition is specified, it is first evaluated, and only if it evaluates to true will the
rule action be executed. The condition is specified in the WHEN clause of the
trigger.
c. The action to be taken:
 The action is usually a sequence of SQL statements, but it could also be a
database transaction or an external program that will be automatically executed.
 In this example, the action is to execute the stored procedure
INFORM_SUPERVISOR.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

Views (Virtual Tables) in SQL

 A view in SQL terminology is a single table that is derived from other tables.
 These other tables can be base tables or previously defined views.
 A view does not necessarily exist in physical form; it is considered to be a virtual table,
in contrast to base tables, whose tuples are always physically stored in the database.
 This limits the possible update operations that can be applied to views, but it does not
provide any limitations on querying a view.
 In SQL, the command to specify a view is CREATE VIEW.
 The view is given a (virtual) table name (or view name), a list of attribute names, and a
query to specify the contents of the view. If none of the view attributes results from
applying functions or arithmetic operations, we do not have to specify new attribute
names for the view, since they would be the same as the names of the attributes of the
defining tables in the default case.

 Example1: CREATE VIEW WORKS_ON1 AS


SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn = Essn AND Pno = Pnumber;

 Example1: CREATE VIEW DEPT_INFO(Dept_name, No_of_emps, Total_sal)


AS SELECT Dname, COUNT (*), SUM (Salary)
FROM DEPARTMENT, EMPLOYEE
WHERE Dnumber = Dno
GROUP BY Dname;

 If we do not need a view anymore, we can use the DROP VIEW command to dispose of
it.

DROP VIEW WORKS_ON1;


 A view is supposed to be always up-to-date; if we modify the tuples in the base tables
on which the view is defined, the view must automatically reflect these changes.
 It is the responsibility of the DBMS and not the user to make sure that the view is kept
upto-date.
 Two main approaches have been suggested.
a. Query modification
b. view materialization

a. Query modification:
 It involves modifying or transforming the view query into a query on the
underlying base tables.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

 The disadvantage of this approach is that it is inefficient for views defined via
complex queries that are time-consuming to execute, especially if multiple view
queries are going to be applied to the same view within a short period of time.

b. view materialization:
 It involves physically creating a temporary or permanent view table when the view
is first queried or created and keeping that table on the assumption that other
queries on the view will follow.
 In this case, an efficient strategy for automatically updating the view table when
the base tables are updated must be developed in order to keep the view up-to-date.
 Techniques using the concept of incremental update have been developed for
this purpose, where the DBMS can determine what new tuples must be inserted,
deleted, or modified in a materialized view table when a database update is
applied to one of the defining base tables.
 The view is generally kept as a materialized (physically stored) table as long as it
is being queried.
 If the view is not queried for a certain period of time, the system may then
automatically remove the physical table and recompute it from scratch when
future queries reference the view.
 Different strategies as to when a materialized view is updated are possible.
 Theimmediate update strategy updates a view as soon as the base tables are
changed; the lazy update strategy updates the view when needed by a view query;
and the periodic update strategy updates the view periodically.
Example: UPDATE WORKS_ON1
SET Pname = ‘ProductY’
WHERE Lname = ‘Smith’ AND Fname = ‘John’ AND Pname = ‘ProductX’;
This query can be mapped into several updates on the base relations to give the desired update
effect on the view. In addition, some of these updates will create additional side effects that
affect the result of other queries. For example, here are two possible updates, (a) and (b), on the
base relations corresponding to the view update operation.
a. UPDATE WORKS_ON
SET Pno = ( SELECT Pnumber
FROM PROJECT
WHERE Pname = ‘ProductY’ )
WHERE Essn IN ( SELECT Ssn
FROM EMPLOYEE
WHERE Lname = ‘Smith’ AND Fname = ‘John’ )
AND
Pno = ( SELECT Pnumber
FROM PROJECT
WHERE Pname = ‘ProductX’ );
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning

b. UPDATE PROJECT
SET Pname = ‘ProductY’
WHERE Pname = ‘ProductX’;

observations:

a. A view with a single defining table is updatable if the view attributes contain the primary
key of the base relation, as well as all attributes with the NOT NULL constraint that do
not have default values specified.
b. Views defined on multiple tables using joins are generally not updatable.
c. Views defined using grouping and aggregate functions are not updatable.

DEPT OF AI&ML,BMSIT

You might also like