SQL Module 1
SQL Module 1
MODULE - 1
SQL: SQL Data Definition and Data Types specifying basic constraints in SQL, Basic
retrieval queries in SQL, Insert, Delete and Update statements in SQL, Additional
features of SQL, More complex SQL Queries, Specifying Constraints as Assertions and
Triggers, Views (Virtual Tables) in SQL, Schema Change Statement in SQL.
• SQL is used to interact with a database to manage and retrieve the data.
• DBMS processes SQL request retrieves the requested data from the database and returns it.
• This process of requesting data from the database and receiving back the result is called a
database query and hence the name SQL (Structured query language)
• SQL is mainly used for creating tables, inserting, updating and deleting records.
Operators in SQL
Note
Case sensitivity in SQL
SQL is NOT case sensitive
SQL keywords are NOT case sensitive
SQL data types are NOT case sensitive
TABLE Name is NOT case sensitive
Column Names are NOT case sensitive
Row values for VARCHAR, CHAR, DATE, TIME, TIMESTAMP data type are case sensitive
Coding convention
All the keywords must be written in UPPER CASE.
All the table names, column names must be written in lower case.
The values of the columns whose data type is CHAR, VARCHAR or DATE must be mentioned in
single quotes. Example : „S1001‟, ‟15-AUG-2010‟, „1GA14CS101‟
The values that are mentioned after the VALUES keyword must follow the same order as the
columns mentioned after the table name.
SQL Commands
DDL
1. Create Command
2. Alter Command
3. Drop Command
4. Rename Command
5. Truncate Command
1. Create Command
• DDL command.
• Works with columns of a table.
• Used to create the columns/attributes of the table.
• CREATE is used along with the keyword TABLE.
Constraints in SQL
3. NOT NULL
• It implies that value has to be provided for the column(s) compulsorily.
• It prevents null values to be entered.
Example :
CREATE TABLE persons (
p_id number(3) primary key, name
varchar(10) not null, address
varchar(10),
city varchar(10)
);
4. Unique
• It implies that the values in the column(s) should be distinct.
• A column with unique constraint can have null value.
CREATE TABLE
emp (
emp_id varchar(20) primary key, empname
varchar(10) not null, deptno number(5),
salary number(7) check (salary>1000)
);
6. DEFAULT
• It is used to provide default value at column level.
• The DEFAULT constraint can also be used to insert system values, by using functions like
sysdate
Note : The ON UPDATE and ON DELETE specify which action will execute
when a row in the parent table is updated and deleted.
If you delete one or more rows in the parent table, you can set one of the following actions:
Dept of AI&ML,DSCE,Bangalore pg. 10
ON DELETE NO ACTION: SQL Server raises an error and rolls back the delete action on the row in
the parent table.
ON DELETE CASCADE: SQL Server deletes the rows in the child table that is corresponding to the
row deleted from the parent table.
ON DELETE SET NULL: SQL Server sets the rows in the child table to NULL if the corresponding
rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.
ON DELETE SET DEFAULT SQL Server sets the rows in the child table to their default values if the
corresponding rows in the parent table are deleted. To execute this action, the foreign key columns
must have default definitions. Note that a nullable column has a default value of NULL if no default
value specified.
By default, SQL Server appliesON DELETE NO ACTION if you don‟t explicitly specify any action.
If you update one or more rows in the parent table, you can set one of the following actions:
ON UPDATE NO ACTION: SQL Server raises an error and rolls back the update action on the row in
the parent table.
ON UPDATE CASCADE: SQL Server updates the corresponding rows in the child table when the
rows in the parent table are updated.
ON UPDATE SET NULL: SQL Server sets the rows in the child table to NULL when the
corresponding row in the parent table is updated. Note that the foreign key columns must be null able
for this action to execute.
ON UPDATE SET DEFAULT: SQL Server sets the default values for the rows in the child table that
have the corresponding rows in the parent table updated.
DELETE CASCADE:
ON DELETE CASCADE clause in MySQL/SQL is create at foreign key. By using this option,
it automatically remove the matching records from the child table when we delete the rows from
the parent table. It is a kind of referential action related to the foreign key.
UPDATE CASCADE:
ON UPDATE CASCADE clause in MySQL/SQL is create at foreign key. By using UPDATE
CASCADE in the referencing table it used to update the matching records from the child table
automatically when we update the rows in the parent table.
* These two CANNOT be used with alter command
2. Alter Command
• DDL command.
• Works with columns of a table.
• Used to add, delete, or modify columns in an existing table.
• Used to add and drop various constraints on an existing table.
• Works with the keywords ADD / MODIFY / DROP
Syntax :
ALTER TABLE tablename ADD/MODIFY/DROP (fieldname datatype [constraint]);
Examples :
• ALTER TABLE persons ADD(phone varchar(10));
• ALTER TABLE persons MODIFY(name varchar(15));
• ALTER TABLE persons MODIFY(phone varchar(12) constraint ph not null);
• ALTER TABLE persons DROP(constraint ph);
• ALTER TABLE cust_details ADD constraint pk_cust_accno primary key(account_no);
• ALTER TABLE cust_transaction ADD constraint fk_custaccno foreign key (account_no)
references cust_details (account_no);
Note :
• We can change data type and length of the column.
• If the table has only one column, ALTER cannot be used to drop the column.
• Column to be modified should be empty to decrease the column length.
3. Drop Command
• It is used to delete both columns and rows of a table.
• There is no way to recover the data. (ROLLBACK command does not work)
Syntax :
DROP TABLE tablename;
Example : DROP TABLE persons;
TRUNCATE TABLE
DESCRIBE TABLE
{DESCRIBE | DESC} table_name;
SQL Commands
DML
1. Insert Command
• DML command.
• Works with records of a table.
• Used to insert records of the table.
• INSERT is used along with the keywords INTO and VALUES.
2. Update Command
• DML command.
• Works with records.
• Used to update the values of the records.
• UPDATE is used with the keyword SET.
Syntax :
1. It used to update the specified column value
UPDATE tablename SET(columnname=value );
or
2. It used to update the specified column value for given condition
UPDATE tablename SET(columnname=value ) [WHERE condition]);
Increase the scholarship of all EC students by 30% who have got „A grade
UPDATE student SET scholarship=scholarship+0.3*scholarship WHERE stream='EC' AND
grade='A';
Change the grades of all the students to „A‟ who have got greater than or equal to 75 marks
UPDATE student SET grade='A' WHERE marks>=75;
• DML command.
• Works with records.
• Used to delete all / specified records of a table.
• DELETE is used with the keyword FROM.
Syntax : it delete all values of table
DELETE FROM tablename;
Delete the student details who have got the stipend in 3000s
DELETE FROM student WHERE stipend BETWEEN 3000 AND 3999;
Summary
4. Select Command
• DML command.
• Works with records of a table.
• Used to display all or specified records of the table.
• SELECT is used along with the keywords FROM.
• Also used with the keyword WHERE on giving conditions on rows.
SELECT *
FROM < Table List>;
Syntax : To retrieve the column details of specified table for given condition.
SELECT */column name1, column name2,. ... FROM tablename [WHERE CONDITION];
Display all the records who are either in „MECH‟ or who have got C grade.
SELECT * FROM student WHERE stream='MECH‟ OR grade='C';
Display all the details who are getting a stipend between 3500 and 4000.
SELECT * FROM student WHERE stipend>=3500 AND stipend<=4000;
OR
SELECT * FROM student WHERE stipend BETWEEN 3500 AND 4000;
Display usn, name, stream and marks of all the students whose marks are in the range 65 to
75.
SELECT usn, name, stream, marks FROM student WHERE marks BETWEEN
65 AND 75;
Display the details of all Mechanical students who are in 5th semester.
SELECT * FROM student WHERE stream='MECH' AND sem like '5_';
Display the details of 7th semester students who have got „A‟ grade.
SELECT * FROM student WHERE sem LIKE '7_' AND grade='A';
IN / NOT IN
ALL
The ANY and ALL operators allow you to perform a comparison between a single column value and a
range of other values.
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <,
or <=).
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
Dept of AI&ML,DSCE,Bangalore pg. 23
FROM table_name
WHERE condition);
ANY
SQL ANY compares a value of the first table with all values of the second
table and returns the row if there is a match with any value.
SELECT column
FROM table1
WHERE column OPERATOR ANY (
SELECT column
FROM table2
);
ORDER by CLAUSE
IS / IS NOT NULL
Display the details who have not got scholarship.
Dept of AI&ML,DSCE,Bangalore pg. 25
SELECT * FROM student WHERE scholarship IS NULL;
DISTINCT
• By default, the select statement retrieves all the rows that are filtered by select statement.
This may contain duplicate roes.
• Distinct helps to avoid duplicate values.
Arithmetic Operators
The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and
division, respectively) can be applied to numeric values in an SQL query result
Aggregate Functions
Dept of AI&ML,DSCE,Bangalore pg. 26
The aggregate function takes a complete column of data as its argument and produces a single
resultant data value that summarizes the column.
• Sum() It computes the total of a given column.
• Avg() It computes the average of a given column.
• Min() It finds the smallest value in a given column.
• Max() It finds the largest value in a given column.
• Count() It counts the number of non-null values in a given column.
• Count(*) It counts rows of query results including rows which have NULL values. If
there are no rows, it returns a value 0.
Find the sum of the marks.
SELECT SUM(marks) FROM student;
Find the sum of all the marks who have „C‟ grade.
SELECT SUM(marks) FROM student WHERE grade='C';
Find the maximum salary, the minimum salary, and the average salary among all employees.
Find the maximum salary, the minimum salary, and the average salary among employees who work for the
'Research' department.
Group By Command
It is used in select statement to collect data across multiple records and group the results by one or
more columns.
Having clause
• It is used along with group by clause.
• It is used to specify search condition for groups.
Display different streams and their count which are appearing more than twice.
SELECT stream, COUNT(stream) FROM student GROUP BY stream HAVING count(stream)>2;
ORDER BY GROUP BY
WHERE is used with order by to give HAVING is used with group by to give condition
condition
Aggregate functions cannot be used Aggregate functions can be used with group by
with order by
WHERE HAVING
WHERE is used with order by to give HAVING is used with group by to give condition
condition
Uses relational operators like =,<, > etc Uses aggregate functions like sum(), min() etc
• 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 multiple table 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.
Example :
SELECT Fname, Address, [Link] FROM EMPLOYEE, DEPARTMENT
WHERE DName = 'Accounts' AND [Link] = [Link];
Dept of AI&ML,DSCE,Bangalore pg. 28
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.
SELECT Fname, Address, [Link] FROM EMPLOYEE E, DEPARTMENT D
WHERE [Link] = [Link];
Aliases are the temporary names given to table or column for the purpose of a particular SQL query. It
is used when name of column or table is used other than their original names, but the modified name
is only temporary.
• Aliases are created to make table or column names more readable.
• The renaming is just a temporary change and table name does not change in the original
database.
• Aliases are useful when table or column names are big or not very readable.
• These are preferred when there are more than one table involved in a query.
Set operators
• UNION
• MINUS
• INTERSECT
must satisfy Union Compatibility
SNAME
------------
Ganesh
Types of JOIN
• Inner joins
• Equi join (=)
• Natural join ( Joining attribute name should be same in both table if not rename
attribute then apply join condition)
• Theta join(>,<,<>,>=,=<)
• Cross Join(X)
• Self-Join
• Inner joins
Select *
From T1 JOIN T2 T1.P=T2.A;
Or
• Equi join
Select *
From T1,T2
WhereT1.P=T2.A;
SELECT *
FROM T1 LEFT OUTER JOIN T2 ON T1.P=T2A ;
Select *
From T1,T2
WhereT1.P=+T2.A;
SELECT *
FROM T1 RIGHT OUTER JOIN T2 ON T1.P=T2A;
SELECT *
FROM T1 FULL OUTER JOIN T2 ON T1.P=T2A;
P Q R A B C
10 a 5 10 b 5
10 a 5 10 b 5
25 a 6 25 c 3
15 b 8 NULL NULL NULL
Cross Join
Each row of n table mapping to all row of m table then output will n*m rows
Select *
From T1 cross join T1 B
Self Join
Joining a table with itself.
Select *
From T1 A,T1 B
WhereA.P=T1.R;
Examples:
or as:
Q2: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT
AS DEPT(DNAME, DNO, MSSN, MSDATE)
WHERE DNAME='Research‟
TH Another Example;
– Q3 could be written as follows; this illustrates multiple joins in the joined tables
Nested Queries
• 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.
• A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Rules :
1. Subqueries must be enclosed within parentheses.
2. A subquery can have only one column in the SELECT clause, unless multiple columns are
in the main query for the subquery to compare its selected columns.
3. An ORDER BY command cannot be used in a subquery, although the main query can use
an ORDER BY. The GROUP BY command can be used to perform the same function as
the ORDER BY in a subquery.
4. Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
5. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
6. A subquery can return a single value, a single row, a single column, or a whole table. They are
called scalar subqueries.
or
Types of SubQueries
1. Single row subqueries
2. Multiple value/column subqueries
3. Correlated subqueries
1. Single row subqueries
They return only one row.
Use single-row comparison operators (<, >, ≤, ≥, =, <>)
The inner query must return only one value, otherwise error will result.
The subquery result is then compared to the value of the column(s) in the parent
query.
3. Correlated Subquery
• A correlated subquery is one where the inner query depends on values provided by the outer
query.
• Correlated subqueries are used for row-by-row processing
• This means that in a correlated subquery, the inner query is executed repeatedly, once for
each row that might be selected by the outer query.
Dept of AI&ML,DSCE,Bangalore pg. 34
• A correlated subquery is used when result of the subquery depends on value in each
candidate row of main query.
• The inner query will be referencing the outer query.
• The outer query record is passed to the inner query, the inner query evaluates that record
and passes the data again back to the outer query.
• A correlated subquery is evaluated once for each row processed by the parent statement. The
parent statement can be a SELECT, UPDATE, or DELETE statement
. Examples :
Example 1:
Retrieve the employees who are earning a salary less than the average salary.
Steps :
1. Find average salary first.
SELECT avg(salary) FROM Emp;
Output of inner query :
Avg(salary) = (4400+13000+12000+8300+4400)/5 = 8420
2. Select employees where salary<the average salary calculated.
Dept of AI&ML,DSCE,Bangalore pg. 35
SELECT name, salary FROM Emp WHERE salary < 8420;
Query Statement :
SELECT name, salary FROM Emp WHERE salary < (SELECT avg(salary) FROM Emp);
Example 2:
Retrieve the details of employees who are earning a salary equal to minimum salary.
SELECT * FROM Emp WHERE salary = (SELECT MIN(salary) FROM Emp);
Example 3:
Write SQL Query to display employee name who has obtained maximum salary.
SELECT name from Emp where salary= (SELECT Max(salary) from Emp);
Example 4:
Write SQL Query to display the second highest salary.
SELECT max(salary) from Emp where salary != (SELECT Max(salary) from Emp);
Example 5:
Write SQL Query to display the second lowest salary.
SELECT min(salary) from Emp where salary != (SELECT min(salary) from Emp);
2. Outer Query :
SELECT * FROM Emp WHERE (salary, job_id) IN {(8300, ACC), (4400,ASST), (13000,MGR)}
SELECT * FROM Emp WHERE (salary, job_id) IN (SELECT max(salary), job_id FROM
Emp GROUP BY job_id );
Example 1:
Find out employees who earn a salary less than the average salary for their jobs.
SELECT name, job_id, salary FROM Emp E1 WHERE salary < (SELECT avg(salary) FROM
Emp E2 WHERE E1.job_id=E2.job_id);
NAME JOB_ID SALARY
Kavya MGR 12000
Example 2:
Find out employees who earn a salary equal to the sum of salary jobwise.
SELECT name, job_id, salary FROM Emp E1 WHERE salary = (SELECT sum(salary) FROM
Emp E2 WHERE E1.job_id=E2.job_id);
NAME JOB_ID SALARY
Saritha ACC 8300
Example 3:
Find all employee details who work in a department.
Output :
The EXISTS condition in SQL is used to check whether the result of a correlated nested query is
empty (contains no tuples) or not.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);
SELECT column_name(s)
FROM table_name
WHERE NOT EXISTS
(SELECT column_name(s)
FROM table_name
WHERE condition);
Example 1 :
Write the queries in SQL for the following relations.
SAILORS (sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)
1) Find the names of sailors who have reserved the boat number „103‟.
2) Find the names of sailors who have reserved a „red‟ and a „green‟ boat.
3) Find the names of sailors who have reserved atleast one boat.
4) Find the names of sailors with age over 20 years, who have not reserved a red boat.
Solution :
We will try creating the above tables with records and then execute the query.
1) Find the names of sailors who have reserved the boat number „103‟.
SELECT sname FROM sailors s, boats b, reserves r WHERE [Link]=103 AND [Link]=[Link]
AND [Link]=[Link];
2) Find the names of sailors who have reserved a „red‟ and a „green‟ boat.
SELECT sname FROM sailors s, boats b, reserves r WHERE [Link] IN('red', 'green') AND
[Link]=[Link] AND [Link]=[Link] ;
4) Find the names of sailors with age over 20 years, who have not reserved a red boat.
SELECT Sname FROM sailors s, boats b, reserves r WHERE age>20 AND color!='red‟
AND [Link]=[Link] AND [Link]=[Link] ;
Example 2 :
Write queries in SQL for the following. Refer the following relations
Employee (Name, SSN, Salary, Super SSN, DNo)
Department (DNum, DName, Mgr SSN)
Dept-Locations (DNum, Dlocation)
Works ON (ESSN, PNo, Hours)
Dependent (ESSN, Dep Name, Gender)
1) Retrieve the name of the employee who gets second highest salary.
2) For each department that has more than 5 employees, retrieve the department number and
no. of its employees who have salary more than Rs.5000.
3) Retrieve the name of employees whose salary is greater than all the employees working in
either department 5 or 6.
Solution :
1) Retrieve the name of the employee who gets second highest salary.
SELECT name, max(salary) FROM Employee WHERE salary < (SELECT max(salary)
FROM Employee);
2) For each department that has more than 5 employees, retrieve the department
number and no. of its employees who have salary more than Rs.5000.
SELECT dnum, count(SSN)FROM Employee, department WHERE Dno=dnum AND
salary>5000 GROUP BY dnum HAVING count(ssn)>5;
3) Retrieve the name of employees whose salary is greater than all the employees working
in either department 5 or 6.
SELECT name FROM employee WHERE salary >(SELECT max(salary) FROM
employee WHERE dno IN(5,6);
Example 3 :
Consider the following schema and write the SQL queries
STUDENT(USN, name, branch, percentage)
Dept of AI&ML,DSCE,Bangalore pg. 40
FACULTY(FID, fname, dept, designation, salary)
COURSE(CID, cname, FID)
ENROLL(CID, USN, grade)
i) Retrieve the names of all students enrolled for the course „CS-54‟.
ii) List all the departments having an average salary of the faculties above Rs.10,000.
iii) List the names of students enrolled for the course „CS-51‟ and having „B‟ grade.
Solution :
i) Retrieve the names of all students enrolled for the course „CS-54‟.
SELECT [Link] FROM student s, course c, enroll e WHERE [Link]=[Link] AND [Link]=[Link] AND
[Link]=‟CS-54‟;
ii) List all the departments having an average salary of the faculties above Rs.10,000.
SELECT dept FROM faculty WHERE avg(salary)> (SELECT salary FROM faculty WHERE
salary>10000);
iii) List the names of students enrolled for the course „CS-51‟ and having „B‟ grade.
SELECT [Link] FROM student s, enroll e, course c WHERE [Link]=[Link] AND [Link]=[Link] AND
[Link]=‟CS-51‟ AND [Link]=‟B‟;
Example 4 :
Given the schema and write the SQL queries
EMP (Fname, Lname, SSN, Bdate, Address, Gender, Salary, Super SSN, Dno)
DEPT (Dname, Dnumber, Mgr_SSN, Mgrstartdate)
DEPT_LOC (DNumber, Dloc)
PROJECT (Pname, Pnumber, Ploc, Dnum)
WORKS_ON (WSSN, Pno, Hours)
DEPENDENT (ESSN, Dept_name, Gender, Bdate, relation)
i) Retrieve the manager name with atleast 1 dependent
ii) Retrieve the employee names who work on any of the project that „kumar‟ works
iii) Retrieve the pno, pname, no. of man hours work done on each project.
iv) Retrieve the pname which are controlled by Research department.
v) Retrieve the employee name who work for dept number 10 and have a daughter.
vi) Retrieve the list of employees and the projects they are working on, ordered by department and,
within each department, ordered alphabetically by last name, first name.
vii) For each project, retrieve the project number, the project name, and the number of employees
who work on that project.
viii) 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.
ix) For each project, retrieve the project number, the project name, and the number of employees
from department 4 who work on the project.
Solution :
i) Retrieve the manager name with atleast 1 dependent
SELECT fname, lname FROM emp e1, dept d1, dependent d2 WHERE [Link]=[Link] AND
Dept of AI&ML,DSCE,Bangalore pg. 41
[Link]=[Link];
ii) Retrieve the employee names who work on any of the project that „kumar‟ works
SELECT fname, lname FROM emp e, project p WHERE [Link]=[Link] AND fname=‟Kumar‟;
iii) Retrieve the pno, pname, no. of man hours work done on each project.
SELECT [Link], [Link], [Link] FROM works_on w, project p WHERE [Link]=[Link];
v) Retrieve the employee name who work for dept number 10 and have a daughter.
SELECT fname, lname FROM employee e, dependent d WHERE [Link]=[Link] AND [Link]=10
AND [Link]=‟daughter‟;
vi) Retrieve the list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name, first name.
SELECT fname, lname, pname, dname from employee, department, project where dnumber=dno
and ssn=essn and pno=pnumber group by dname order by dname, lname, fname;
vii) For each project, retrieve the project number, the project name, and the number of
employees who work on that project.
SELECT [Link], [Link], count([Link]) FROM project p, dept d, emp e WHERE
[Link]=[Link] AND [Link]=[Link] GROUP BY pnumber;
viii) 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 [Link], [Link], count([Link]) FROM project p, dept d, emp e WHERE
[Link]=[Link] AND [Link]=[Link] GROUP BY pnumber HAVING count([Link])>2;
ix) For each project, retrieve the project number, the project name, and the number of
employees from department 4 who work on the project.
SELECT [Link], [Link], count([Link]) FROM project p, dept d, emp e WHERE
[Link]=[Link] AND [Link]=[Link] GROUP BY pnumber AND dnum=4 GROUP BY
pnumber HAVING count(dnum)>2;
Example 5 :
Consider the following tables :
Works (Pname, Cname, Salary)
Lives (Pname, Street, City)
Located_In (Cname, City)
1. List the names of people who work for the company „Wipro‟ along with the cities they live
in.
2. Find the names of persons who do not work for „Infosys‟
Dept of AI&ML,DSCE,Bangalore pg. 42
3. Find the people whose salaries are more than that of all of the average salary of „Oracle‟
employees.
4. Find the persons who work and live in the same city.
Solution :
1. List the names of people who work for the company „Wipro‟ along with the cities they live
in.
Select [Link], [Link] from works w, lives l where [Link]='Wipro' and [Link]=[Link] ;
3. Find the people whose salaries are more than that of all of the average salary of „Oracle‟
employees.
Select pname, salary from works where salary> (select avg(salary) from works where
cname='Oracle') ;
4. Find the persons who work and live in the same city.
Select [Link] from works w, lives l, located_in x where [Link]=[Link] and
[Link]=[Link] and [Link]=[Link];
• The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database.
• The clause is used for defining a temporary relation such that the output of this temporary
relation is available and is used by the query that is associated with the WITH clause.
• Queries that have an associated WITH clause can also be written using nested sub-queries
but doing so add more complexity to read/debug the SQL query.
• WITH clause is not supported by all database system.
• The name assigned to the sub-query is treated as though it was an inline view or table.
Example :
• The CASE statement goes through conditions and returns a value when the first condition
is met (like an IF-THEN-ELSE statement).
• So, once a condition is true, it will stop reading and return the result.
• If no conditions are true, it returns the value in the ELSE clause.
• If there is no ELSE part and no conditions are true, it returns NULL.
Example 1 :
SQL supports the creation of assertions which are constraints not associated with only one
table.
An assertion statement should ensure that a certain condition will always exist in the
database.
DBMS always checks the assertion whenever modifications are done in the corresponding
table.
Examples :
• Ensuring the sum of loan amounts for each branch is less than the sum of all account
balances at the branch.
• Ensuring every loan customer keeps a minimum of $1000 in an account.
Example 1 :
Sum of loans taken by a customer does not exceed 10,00,000
CREATE ASSERTION Sumloans CHECK (1000000>= ALL SELECT sum(amount) from
borrower B, loan L where B.loan_no=L.Loan_no GROUP BY customer_name);
Example 2 :
The salary of an employee must not be greater than the salary of the manager of the
department that the employee works for.
CREATE ASSERTION salaryconstraint CHECK (NOT EXISTS (SELECT * FROM employee e,
employee m, department d where [Link]>[Link] AND [Link]=[Link] AND [Link]=[Link]));
• The basic technique for writing 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.
Triggers
Example :
Create table words (word varchar(10));
Example
Assertions vs Triggers
Assertions do not maintain any track Triggers maintain track of all changes occurred
4.
of changes made in table. in table.
Triggers - a trigger is a piece of SQL to execute either before or after an update, insert, or
delete in a database. An example of a trigger in plain English might be something like: before
updating a customer record, save a copy of the current record.
Check Constraint - A check is a piece of SQL which makes sure a condition is satisfied
before action can be taken on a record. In plain English this would be something like: All
customers must have an account balance of at least $100 in their account.
Assertions - An assertion is a piece of SQL which makes sure a condition is satisfied or it
stops action being taken on a database object. It could mean locking out the whole table or
Dept of AI&ML,DSCE,Bangalore pg. 48
even the whole database.
Views in SQL
Example 1 :
Create table demo as select * from customer where id between 3 and 10;
CREATE VIEW cust_view AS SELECT * FROM customer WHERE salary>20000;
Example 2 :
Create a view which will display the department name, number of employees working
and total salary for each department.
CREATE VIEW view_info (deptname, no_of_emp,
totalsalary) AS
SELECT deptname, count(*), sum(salary) FROM emp, dept WHERE
[Link]=[Link] GROUP BY deptname;
View Update
• A view is supposed to be upto date. If we modify the tuples in base table on which the
view is defined, the view must automatically reflect these changes.
• Updating of view is complicated and can be ambiguous.
Example 1 :
Can be used to alter a schema by adding or dropping tables, attributes, constraints, and other
schema elements.
This can be done while the database is operational and does not require recompilation of the
database schema.
• 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.
Example : If we no longer wish to keep track of dependents of employees in the
COMPANY database, we can get rid of the DEPENDENT relation by issuing the
following command: DROP TABLE DEPENDENT CASCADE;
Reference:
[Link]
[Link]
[Link]
[Link]