0% found this document useful (0 votes)
36 views117 pages

DBE Unit 2

Uploaded by

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

DBE Unit 2

Uploaded by

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

Database Engineering

Unit 2

Structured Query Language


(SQL)
Getting Started
• Install jdk 1.7
• Install Oracle 11g Express Edition
• Set path C:\jdk1.7\bin
• Set classpath
Set Path
• Start
• Control Panel
• System
• Advanced Tab
• Environment Variables
• Select Path
• Edit
• Add semicolon;
• and then add path at the end – c:\jdk1.7\bin
Set classpath
• Start
• Control Panel
• System
• Advanced Tab
• Environment Variables
• New
• Give name – classpath
• Add semicolon;
• and then add path of the working folder
Getting Started

• Start-oracle11g-
• Get Started-
• Application Express-
• Create Database user and Workspace
• Login
• SQL Workshop
SQL Command Categories
• SQL language is divided into the following four
command categories:
• Data definition (Data Definition Language, or DDL)
• Data manipulation (Data Manipulation Language, or
DML)
• Retrieval
• Security and authorization
Data Definition Language (DDL)
• CREATE - to create a new database object

•ALTER - to change an aspect of the structure of an


existing database object

•DROP - to drop (remove) a database object

•TRUNCATE – remove all records from a table,


including all spaces allocated for the records are
removed

•RENAME - rename an database object


Create Table
Data Types
CREATE TABLE books
( book_id NUMBER PRIMARY KEY,
book_name VARCHAR2(30),
author_name VARCHAR2(40),
book_isbn VARCHAR2(20) );

CREATE TABLE books ( book_id NUMBER,


book_id_seq NUMBER, book_name VARCHAR2(30),
author_name VARCHAR2(40), book_isbn
VARCHAR2(20),
CONSTRAINT pk_books PRIMARY KEY (book_id,
book_id_seq));
• Foreign Key
CREATE TABLE supplier
( supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50),

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)


);

CREATE TABLE products


( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);
CREATE TABLE supplier
( supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,

contact_name varchar2(50),

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)


);

CREATE TABLE products


( product_id numeric(10) not null,

supplier_id numeric(10) not null,

supplier_name varchar2(50) not null,


CONSTRAINT fk_supplier_comp
FOREIGN KEY (supplier_id, supplier_name)
REFERENCES supplier(supplier_id, supplier_name)
);
• CREATE TABLE ref1 ( id VARCHAR2(3)
PRIMARY KEY );

• CREATE TABLE ref2 ( id VARCHAR2(3)


PRIMARY KEY );
• CREATE TABLE look ( p VARCHAR2(3),
CONSTRAINT fk_p_ref1
FOREIGN KEY (p) REFERENCES ref1(id),

CONSTRAINT fk_p_ref2
FOREIGN KEY (p) REFERENCES ref2(id) );
INSERT
• Insert into table_name values( , , )
• Insert values for All Attributes
• INSERT INTO departments VALUES (280,
'Recreation', 121, 1700);

• Insert values for some Attributes


• INSERT INTO employees (employee_id, last_name,
email, hire_date, job_id, salary, commission_pct)
VALUES (207, 'Gregory', 'pgregory@oracle.com',
sysdate, 'PU_CLERK', 1.2E3, NULL);
• Use of select in insert
• INSERT INTO bonuses SELECT employee_id,
salary*1.1 FROM employees WHERE
commission_pct > 0.25;
DROP
Syntax:
DROP <OBJECT> <object name>

Example:
DROP TABLE Employee;
TRUNCATE
Syntax:
TRUNCATE TABLE <table name>;

Example:
TRUNCATE TABLE Employee;
RENAME
Syntax:
RENAME <old object name> TO <new object name>

Example:
RENAME temporary to new
Constraints
Not Null Constraint
• If a column in a table is specified as Not Null,
• then it’s not possible to insert a null in such
column.
• It can be implemented with create and alter
commands.
• When we implement the Not Null constraint with
alter command there should not be any null
values in the existing table.
Not Null
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
Unique Constraint
The unique constraint doesn’t allow duplicate values in a
column.
If unique constraint encompasses two or more columns,
no two equal combinations are allowed
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
DEFAULT Constraint
The DEFAULT constraint is used to insert a default
value into a column.
The default value will be added to all new records, if no
other value is specified.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT ‘Ichalkaranji'
)
CHECK Constraint
CHECK constraint is used to limit the value range that
can be placed in a column.

If you define a CHECK constraint on a single column it


allows only certain values for this column.

If you define a CHECK constraint on a table it can limit


the values in certain columns based on values in other
columns in the row.
CHECK Constraint
CREATE TABLE Persons
(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
CHECK Constraint
• CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND
City=‘Ichalkaranji')
)
Alter Table
• The SQL ALTER TABLE command is used to add,
delete or modify columns in an existing table.
• also use ALTER TABLE command to add and drop
various constraints on an existing table.
• Syntax:
• The basic syntax of ALTER TABLE to add a new
column in an existing table is as follows:
• ALTER TABLE table_name ADD column_name
datatype;
Alter Table
• The basic syntax of ALTER TABLE to DROP
COLUMN in an existing table is as follows:
• ALTER TABLE table_name DROP COLUMN
column_name;

• The basic syntax of ALTER TABLE to change the


DATA TYPE of a column in a table is as follows:
• ALTER TABLE table_name MODIFY column_name
datatype;
Alter Table
• basic syntax of ALTER TABLE to add a NOT NULL
constraint to a column in a table is as follows:
• ALTER TABLE table_name MODIFY column_name
datatype NOT NULL;

• The basic syntax of ALTER TABLE to ADD UNIQUE


CONSTRAINT to a table is as follows:
• ALTER TABLE table_name ADD CONSTRAINT
MyUniqueConstraint UNIQUE(column1, column2...);
Alter Table
• The basic syntax of ALTER TABLE to ADD CHECK
CONSTRAINT to a table is as follows:
• ALTER TABLE table_name ADD CONSTRAINT
MyUniqueConstraint CHECK (CONDITION);

• The basic syntax of ALTER TABLE to ADD


PRIMARY KEY constraint to a table is as follows:
• ALTER TABLE table_name ADD CONSTRAINT
MyPrimaryKey PRIMARY KEY (column1,
column2...);
Alter Table
• The basic syntax of ALTER TABLE to DROP
CONSTRAINT from a table is as follows:
• ALTER TABLE table_name DROP CONSTRAINT
MyUniqueConstraint;
Alter Table
• The basic syntax of ALTER TABLE to DROP
PRIMARY KEY constraint from a table is as follows:
• ALTER TABLE table_name DROP CONSTRAINT
MyPrimaryKey;

• If you're using MySQL, the code is as follows:


• ALTER TABLE table_name DROP PRIMARY KEY;

• DROP TABLE table_name;


Data Manipulation Language DML)
• INSERT, to add rows to a table

• UPDATE, to change column values of existing rows

• DELETE, to remove rows from a table


INSERT
• Insert into table_name values( , , )
• Insert values for All Attributes
• INSERT INTO departments VALUES (280,
'Recreation', 121, 1700);

• Insert values for some Attributes


• INSERT INTO employees (employee_id, last_name,
email, hire_date, job_id, salary, commission_pct)
VALUES (207, 'Gregory', 'pgregory@oracle.com',
sysdate, 'PU_CLERK', 1.2E3, NULL);
• Use of select in insert
• INSERT INTO bonuses SELECT employee_id,
salary*1.1 FROM employees WHERE
commission_pct > 0.25;
Retrieval
Select
• Select * from employees;
• SELECT FIRST_NAME, LAST_NAME,
DEPARTMENT_ID FROM EMPLOYEES;
• Displaying Selected Columns Under New Headings
• SELECT FIRST_NAME First, LAST_NAME last,
DEPARTMENT_ID Dept FROM EMPLOYEES;
• Selecting Data that Satisfies Specified Conditions
• SELECT FIRST_NAME, LAST_NAME,
DEPARTMENT_ID FROM EMPLOYEES WHERE
DEPARTMENT_ID = 90;

• Selecting Data from Specified Departments – IN


• SELECT FIRST_NAME, LAST_NAME,
DEPARTMENT_ID FROM EMPLOYEES WHERE
DEPARTMENT_ID IN (100, 110, 120);
• Selecting Data for Last Names that Start with the
Same Substring
• SELECT FIRST_NAME, LAST_NAME FROM
EMPLOYEES WHERE LAST_NAME LIKE ‘%Ma%';

• Selecting Data that Satisfies Two Conditions


• SELECT FIRST_NAME, LAST_NAME, SALARY,
COMMISSION_PCT "%" FROM EMPLOYEES
WHERE (SALARY >= 11000) AND
(COMMISSION_PCT IS NOT NULL);
between
• A BETWEEN condition determines whether the value
of one expression is in an interval defined by two
other expressions.
• SELECT * FROM employees WHERE salary
BETWEEN 2000 AND 3000
• expr1 NOT BETWEEN expr2 AND expr3
• Order by
• The ORDER BY clause is used to sort the records in
result set.
• The ORDER BY clause can only be used in
SELECT statements.

SELECT expressions FROM tables


[WHERE conditions]
ORDER BY expression [ ASC | DESC ];

Default order is ASC


SELECT supplier_city FROM suppliers
WHERE supplier_name = 'Microsoft'
ORDER BY supplier_city ASC;

SELECT supplier_city FROM suppliers


WHERE supplier_name = 'Microsoft'
ORDER BY supplier_city DESC;
Update Data
• UPDATE employees SET salary = salary + 1000.0;
delete
• DELETE statement is a used to delete a one or more
records from a table.
• DELETE FROM table [WHERE conditions];

• DELETE FROM suppliers;

• DELETE FROM suppliers WHERE supplier_name =


'IBM';
• SQL Joins

• Inner Join
• Left outer join
• Right outer join
• Full outer join
• Natural join
• Cartesian product
SQL Inner Join – Simple Join
• use a comparison operator to match rows from two
tables
• based on the values in common columns from each
table.
• For example, retrieving all rows where the student
identification number is the same in both the students
and courses tables.
• If we want to list all the Consumers with any orders.
• We use the following SELECT statement:
The "Consumers" table:
P_Id LastName FirstName Address City
1 Kumar Ram Delhi AAA
2 Singh Laxman Chandigarh AAA
3 Sharma Sameer Ambala BBB

The "Orders" table


O_Id OrderNo P_Id
1 12355 3
2 12356 3
3 12357 1
4 24562 1
5 34764 15
• SELECT Consumers.LastName,
Consumers.FirstName, Orders.OrderNo
FROM Consumers
INNER JOIN Orders
ON Consumers.P_Id=Orders.P_Id
ORDER BY Consumers.LastName

• SELECT Consumers.LastName,
Consumers.FirstName, Orders.OrderNo
FROM Consumers, orders
WHERE Consumers.P_Id=Orders.P_Id
ORDER BY Consumers.LastName
• The result-set will look like this
LastName FirstName OrderNo
Kumar Ram 12357
Kumar Ram 24562
Sharma Sameer 12355
Sharma Sameer 12356
When to use inner join
Use an inner join when you want to match values from both tables.

Why to use Inner Joins:


Use inner joins to obtain information from two separate tables and
combine that information in one result set.
SQL Outer Join
• Outer joins can be a left, a right, or full outer join
• LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows
from the left table specified in the LEFT OUTER
clause, not just the ones in which the joined columns
match.
• When a row in the left table has no matching rows in
the right table,
• the associated result set row contains null values for
all select list columns coming from the right table.
The "Consumers" table:
P_Id LastName FirstName Address City
1 Kumar Ram Delhi AAA
2 Singh Laxman Chandigarh AAA
3 Sharma Sameer Ambala BBB

The "Orders" table


O_Id OrderNo P_Id
1 12355 3
2 12356 3
3 12357 1
4 24562 1
5 34764 15
• If we want to list all the Consumers and their orders -
if any, from the tables above.
• We use the following SELECT statement:

SELECT Consumers.LastName,
Consumers.FirstName, Orders.OrderNo
FROM Consumers
LEFT JOIN Orders
ON Consumers.P_Id=Orders.P_Id
ORDER BY Consumers.LastName
• The result-set will look like this:
LastName FirstName OrderNo
Kumar Ram 22456
Kumar Ram 24562
Sharma Sameer 77895
Sharma Sameer 44678
Singh Laxman

The LEFT JOIN keyword returns all the rows


from the left table (Consumers), even if there
are no matches in the right table (Orders).
• RIGHT JOIN or RIGHT OUTER JOIN
• A right outer join is the reverse of a left outer join.
• All rows from the right table are returned.
• Null values are returned for the left table any time a
right table row has no matching row in the left table.
• FULL JOIN or FULL OUTER JOIN
A full outer join returns all rows in both the left and
right tables.
• Any time a row has no match in the other table,
• the select list columns from the other table contain
null values.
• When there is a match between the tables,
• the entire result set row contains data values from
the base tables.
• FULL JOIN
Table P
p_id LastName FirstName City
1 Dhall Sachin Delhi
2 Gupta Pankaj Bangalore
3 Kumar Sanjeev Chandigarh

Table O

o_id OrderNo p_id


1 111 3
2 222 3
3 333 14
4 444 2
5 555 2
• SELECT P.LastName, P.FirstName, O.OrderNo
FROM P
FULL JOIN O
ON P.P_Id=O.P_Id
ORDER BY P.LastName

LastName FirstName OrderNo


NULL NULL 333
Dhall Sachin NULL
Gupta Pankaj 444
Gupta Pankaj 555
Kumar Sanjeev 111
Kumar Sanjeev 222
• Natural Join
1 In Inner join we give conditions explicitly
• Natural join takes condition implicitly
2 Colum names in both tables must be same for natural join
• In inner join column names can be different as we give
conditions explicitly
3 Repeated columns are avoided to display in natural join

SELECT * FROM foods NATURAL JOIN company;

SELECT * FROM company INNER JOIN foods ON


company.company_id = foods.company_id;
item_id item_name item_unit company_id
1 Chex Mix Pcs 16
6 Cheez-lt Pcs 15
2 BN Biscuit Pcs 15
3 Mighty Munch Pcs 17
4 Pot Rice Pcs 15

company_id company_name company_city


18 Order All Boston
15 Jack Hill Ltd London
16 Akas Foods Delhi
17 Foodies. London
19 sip-n-Bite. New York
• Inner Join
• Natural Join
Cartesian Product
• When we join every row of a table to every row of
another table we get Cartesian Product
• Cross join – every row of one table is matched with
every row of another table.
• Cartesian join and cross join are same
• If T1 and T2 are two sets then
• T1 X T2
• SELECT * FROM EMP CROSS JOIN DEPT;

• SELECT * FROM EMP, DEPT;

• In first statement it is specified explicitly


• Second one is implicit
Aggregate Functions
• Min
• Max
• Average
• Sum
• count
count
• count returns the number of tuples returned by the
query as a number.
• COUNT( [ALL | DISTINCT] expression )
• SELECT COUNT(*) Count FROM employees;
min
• SQL MIN()
Returns the minimum value in an expression.

Example 1 of SQL MIN()
Selecting Minimum salary from EMP table:

SELECT Min(salary) as "Minimum Salary"


FROM EMP;
• Example 2 of SQL MIN()
Selecting Minimum salary for each department:

SELECT Dept, Min(salary) as "Minimum Salary"


FROM EMP
GROUP BY Dept;

• SQL MIN() ignores any null values.

With character data columns, SQL MIN() finds the


value that is lowest in the sort sequence.
max
• SQL MAX()

Returns the maximum value in the expression.

Example 1 of SQL MAX()


Selecting Maximum salary from EMP table:

SELECT MAX(salary) as "Maximum Salary"


FROM EMP;
• Example 2 of SQL MAX()
Selecting Maximum salary for each department:

SELECT Dept, MAX(salary) as "Maximum Salary"


FROM EMP
GROUP BY Dept;

SQL MAX() ignores any null values.

For character columns, SQL MAX() finds the highest


value in the collating sequence.
average
• SQL AVG() function returns the Average of numeric
column. SQL AVG() ignores Null Values.
• Syntax of SQL AVG()
• AVG ( [ ALL | DISTINCT ] expression )
• Example 1 of SQL AVG()
From the Salary column, below query will show the
AVG of all the values which are less than 25000
• SELECT AVG(salary) as "Average Sal"
FROM emp
WHERE salary < 25000;
• Example 2 of SQL AVG() ID Numb
1 1
Below is the test_table
2 1
Select AVG(all Numb) from test_table 3 1
4 2
Result: 5 2
2 6 2
7 3
Select AVG(distinct Numb) from
8 3
test_table
9 4
10 1
Result:
1
sum
• SQL SUM() function returns the sum of numeric
column.
• SQL SUM() ignores Null Values
• Syntax of SQL SUM()
• SUM ( [ ALL | DISTINCT ] expression )
• Example 1 of SQL SUM()
From the Salary column, below query will sum all the
values which are less than 25000
SELECT SUM(salaly) as "Total Sal"
FROM emp
WHERE sal < 25000;
• Example 2 of SQL SUM() ID Numb
1 1
Below is the test_table
2 1
Select SUM(all Numb) from test_table 3 1
4 2
Result: 5 2
20 6 2
7 3
Select SUM(distinct Numb) from
8 3
test_table
9 4
10 1
Result:
10
SQL LIKE
• The SQL LIKE operator is used in a WHERE clause
to look for a particular pattern in a column.
Examples of SQL LIKE
If we want to select the employees which have their
names starting with "s".
SELECT * FROM employees
WHERE ename LIKE 's%'

We want to select the employees which have their


names ending with "s".
SELECT * FROM employees
WHERE ename LIKE '%s'
• We are looking for all employees whose name
contains the characters 'sam'
SELECT * FROM employees
WHERE ename LIKE '%sam%'

This SQL statement would return all employees


whose name is 5 characters long, where the first two
characters is 'Sm' and the last two characters is 'th'.
For example, 'Smith', 'Smyth', 'Smath', 'Smeth', etc.

SELECT * FROM employees


WHERE ename like 'Sm_th';
SQL IN
• Example 1 of SQL IN
You can use the IN function as below:

SELECT *
FROM EMP
WHERE EMP_ID in (10000, 10001, 10003, 10005);

This SQL statement would return all EMPLOYEES


where the EMP_ID is either 10000, 10001, 10003, or
10005.
• Example 2 of SQL IN

SELECT *
FROM suppliers
WHERE supplier_name in ('Apple', 'HP', 'Microsoft');

Above query will return all rows where the


supplier_name is either Apple, HP, or Microsoft.
SQL Group By
• specifies how to report the output of the query.
• Allows one to define a subset of the values of a
particular field and to apply an aggregate function to
the subsets.
• normally use a GROUP BY clause in conjunction
with an aggregate expression (like SUM, COUNT
etc).

• Example 1 of SQL Group BY


Calculate the total sales for each store in the
following table
store_name Sales Date
London $1500 Jan-05-1999
San Diego $250 Jan-07-1999
London $300 Jan-08-1999
Boston $700 Jan-08-1999
• First, we need to make sure we select the store
name as well as total sales.
SELECT store_name, SUM (Sales)
FROM Store_Information
Second, we need to make sure that all the sales
figures are grouped by stores.
SELECT store_name, SUM (Sales)
FROM Store_Information
GROUP BY store_name
• The result is

store_name SUM(Sales)
London $1800
San Diego $250
Boston $700
• Example 2 of SQL Group BY
SELECT COUNT (*) FROM t_state
• The above statement returns the total number of
rows in the table.
• We can use GROUP BY to count the number of
offices in each state.
• With GROUP BY, the table is split into groups by
state, and COUNT (*) is applied to each group in
turn.
• SELECT state, COUNT (*)
FROM t_state
GROUP BY state;
• we have a table name Orders.
Orders (O_Id, OrderDate, OrderPrice, Customer)
• we want to find the total sum (total order) of each
customer.
SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer
• Returns a list of Department IDs along with the sum
of their sales for the date of January 1, 2000.

SELECT DeptID, SUM(SaleAmount)


FROM Sales
WHERE SaleDate = '01-Jan-2000'
GROUP BY DeptID
SQL Having
• The SQL HAVING clause allows us to restrict the
data that is sent to the GROUP BY clause.
• Group functions cannot be used in the WHERE
clause.
• SQL statement can have both a WHERE clause and
an HAVING clause.
• WHERE filters data before grouping and HAVING
filters the data after grouping.
• A WHERE clause is useful in both grouped and
ungrouped queries,
• while a HAVING clause should appear only
immediately after the GROUP BY clause in a
grouped query.
• Find the average salary for each department that has
either more than 1 employee or starts with a “To”:

SELECT Dept, AvgSal=(AVG(Salary))


FROM Employee
GROUP BY Dept
HAVING COUNT(Name) > 1 OR Dept LIKE “To”
• Workforce (workforceno, name, position, salary,
email, dcenterno)
• For each distribution center with more than one
member of workforce, find the number of workforce
working in each of the centers and the sum of their
salaries.
SELECT dCenterNo, COUNT(workforceNo) AS
totalworkforce,
SUM(salary) AS totalSalary
FROM workforce
GROUP BY dCenterNo
HAVING COUNT(workforceNo) > 1
ORDER BY dCenterNo;
Set Operations
• need to combine the results from two or more
SELECT statements.
• SQL enables us to handle these requirements by
using set operations.
• The result of each SELECT statement can be treated
as a set, and SQL set operations can be applied on
those sets to arrive at a final result.
• Oracle SQL supports following four set operations:
• UNION ALL
• UNION
• MINUS
• INTERSECT
• <component query>
• {UNION | UNION ALL | MINUS | INTERSECT}
• <component query>

• UNION ALL
• Combines the results of two SELECT statements into
one result set.
• UNION
• Combines the results of two SELECT statements into
one result set, and then eliminates any duplicate
rows from that result set.
• MINUS
• Takes the result set of one SELECT statement, and
removes those rows that are also returned by a
second SELECT statement.

• INTERSECT
• Returns only those rows that are returned by each of
two SELECT statements.
• SELECT CUST_NBR, NAME FROM CUSTOMER
• WHERE REGION_ID = 5
• UNION
• SELECT C.CUST_NBR, C.NAME FROM
CUSTOMER C
• WHERE C.CUST_NBR IN
• (SELECT O.CUST_NBR FROM CUST_ORDER O,
EMPLOYEE E WHERE O.SALES_EMP_ID =
E.EMP_ID AND E.LNAME = 'MARTIN');
• The following query uses both MINUS and UNION
ALL to compare two tables for equality.
• (SELECT * FROM CUSTOMER_KNOWN_GOOD
MINUS SELECT * FROM CUSTOMER_TEST)
UNION ALL (SELECT * FROM CUSTOMER_TEST
MINUS SELECT * FROM
CUSTOMER_KNOWN_GOOD);
• CREATE TABLE table1 (
• id INTEGER NOT NULL PRIMARY KEY,
• city VARCHAR(10) NOT NULL);

• CREATE TABLE table2 (


• id INTEGER NOT NULL PRIMARY KEY,
• city VARCHAR(10) NOT NULL);

• CREATE TABLE table3 (


• city VARCHAR(10) NOT NULL);
• INSERT INTO table1 VALUES (1, 'RIGA');
• INSERT INTO table1 VALUES (2, 'RIGA');
• INSERT INTO table1 VALUES (3, 'RIGA');
• INSERT INTO table1 VALUES (4, 'TALLINN');
• INSERT INTO table1 VALUES (5, 'TALLINN');
• INSERT INTO table1 VALUES (6, 'TALLINN');
• INSERT INTO table1 VALUES (7, 'VILNIUS');
• INSERT INTO table1 VALUES (8, 'HELSINKI');
• INSERT INTO table1 VALUES (9, 'HELSINKI');
• INSERT INTO table1 VALUES (10, 'STOCKHOLM‘);
• INSERT INTO table2 VALUES (1, 'RIGA');
• INSERT INTO table2 VALUES (2, 'RIGA');
• INSERT INTO table2 VALUES (3, 'VILNIUS');
• INSERT INTO table2 VALUES (4, 'VILNIUS');
• INSERT INTO table2 VALUES (5, 'VILNIUS');
• INSERT INTO table2 VALUES (6, 'VILNIUS');
• INSERT INTO table2 VALUES (7, 'HELSINKI’);
• SELECT city FROM table1
• UNION
• SELECT city FROM table2;

• SELECT city FROM table1
• UNION ALL
• SELECT city FROM table2;
• SELECT city FROM table1
• MINUS
• SELECT city FROM table2;

• SELECT city FROM table1


• INTERSECT
• SELECT city FROM table2;
• SQL Examples
• Given the employee database composed of following
tables.
employee (employee-name, street, city)
works (employee-name, company-name, salary)
company (company-name, city)
manages (employee-name, manager-name)

• Give an expression in SQL for each of the following


queries
• Find the names of all employee who work for First
Bank Corporation
• Find the names of all employee who work for First
Bank Corporation
select employee-name
from works
where company-name = ’First Bank Corporation’
• Find the names and cities of residence of all
employees who work for First Bank Corporation.
• Find the names and cities of residence of all
employees who work for First Bank Corporation.
select e.employee-name, city
from employee e, works w
where w.company-name = ’First Bank Corporation’ and
w.employee-name = e.employee-name
• Find all employees in the database who live in the
same cities as the companies for which they work.
• Find all employees in the database who live in the
same cities as the companies for which they work.
select e.employee-name
from employee e, works w, company c
where e.employee-name = w.employee-name
and e.city = c.city and
w.company -name = c.company -name
• Find all employees in the database who live in the
same cities and on the same streets as do their
managers.
• Find all employees in the database who live in the
same cities and on the same streets as do their
managers.
select P.employee-name
from employee P, employee R, manages M
where P.employee-name = M.employee-name and
M.manager-name = R.employee-name and
P.street = R.street and P.city = R.city
• Find all employees in the database who do not work
for First Bank Corporation.
• Find all employees in the database who do not work
for First Bank Corporation.
select employee-name
from works
where company-name = ’First Bank Corporation’
• Assume that the companies may be located in
several cities.
• Find all companies located in every city in which
Small Bank Corporation is located
• Assume that the companies may be located in
several cities.
• Find all companies located in every city in which
Small Bank Corporation is located
select T.company-name
from company T
where (select R.city
from company R
where R.company-name = T.company-name)
contains
(select S.city
from company S
where S.company-name = ’Small Bank Corporation’)
• Find the names, street addresses, and cities of
residence of all employees who work for First Bank
Corporation and earn more than $10,000.
• Find the names, street addresses, and cities of
residence of all employees who work for First Bank
Corporation and earn more than $10,000.

select *
from employee
where employee-name in
(select employee-name
from works
where company-name = ’First Bank Corporation’ and
salary >= 10000)
• Modify the database so that Jones who was working
for City Bank now works for First Bank Corporation.
• Modify the database so that Jones who was working
for City Bank now works for First Bank Corporation.

update works
set company-name = ’ First Bank Corporation’
where person-name = ’Jones’
• SQL Examples
• Given the Academic Institute database composed of
following tables.
person (pid, pname, paddress, uid)
UIDData(uid, age)
student (rollno, pid, class, dept)
faculty (fid, pid, dept)
Studentattendance(rollno, perattendance);
Studentmarks(rollno, subject, marks)
Studentfee(rollno, feepaid, feedues)
Lectures(fid, class, subject)

• Give an expression in SQL for each of the following


queries
• Find the faculty who is also studying in M.Tech
• Find address of students whose attendance is less than
70%
• Find all the students who are eligible for voting
• Find the total fee paid by T.E.CSE students
• Find the address of students who have backlog subjects
• Find the list of students who are supposed to attend DBE
lectures.
• Find all the teachers who teaches to student with uid
123456789101

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy