0% found this document useful (0 votes)
16 views70 pages

Dbms 3 Final

The document contains a series of SQL-related questions and answers covering various topics such as SQL clauses, functions, operators, and queries. It includes both short answer questions and long answer questions, addressing concepts like the GROUP BY clause, logical operators, joins, and constraints in SQL. Additionally, it provides examples and syntax for SQL operations, demonstrating how to manipulate and query data effectively.

Uploaded by

akshay246908
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)
16 views70 pages

Dbms 3 Final

The document contains a series of SQL-related questions and answers covering various topics such as SQL clauses, functions, operators, and queries. It includes both short answer questions and long answer questions, addressing concepts like the GROUP BY clause, logical operators, joins, and constraints in SQL. Additionally, it provides examples and syntax for SQL operations, demonstrating how to manipulate and query data effectively.

Uploaded by

akshay246908
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/ 70

Q.

No Question BL CO PO
1 Describe the Group by clause with an example II III I
2 Display the employee details who is having the salary between 3000
I III III
and 60000?
3 Show the employee table using order by clause on employee name?
I III II
4 Display the employee salary by adding the bonus of Rs. 1000/-?
I III II

5 Write the different types of logical operators in SQL?


I III III
6 Write any four date functions of SQL? III
I II

7 Differentiate between sum() and count() function with an example? III


IV II

8 Describe the power(),sqrt(),floor(),mod() functions in SQL? III


II II

9 List any five functions of strings in SQL? III


I II
10 How to establish the relationship between two tables using primary III
key and foreign key? I III

11 How to add the primary key constraint at table level with an III
example? IV II

12 What are keywords for enabling and disabling the constraints in III
SQL? I III

13 Difference between unique and primary key in SQL? III


IV II
14 Differentiate between alter and update key words in SQL? III
IV II
15 What are the different type of joins in SQL? III
I III
16 Explain the advantages and disadvantages of views in SQL? III
II I
17 What is sub query and its types? III
I I
18 What is the result for the following queries? III
a. SQL> Select s.sname from sailors s, reserves r,
boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’red’ I II
b. SQL>SELECT ename FROM emp WHERE sal =
(SELECT MAX(sal) FROM EMP WHERE sal <
(SELECT MAX(sal) FROM emp)) ;
19 Write the query for Select employees whose salary is greater than III
every salesman’s salary ? I II

20 Find the sailor’s ID whose name is equal to ‘DUSTIN’? III


I II

Part-B
Long Answer Questions (10M)
Q. No Question BL CO PO
Write a SQL query by using Select and Project commands
1 with some examples? IV III II

2 Discuss about Where Clause in Database VI III II


3 Discuss in brief about arithmetic and logic operations in
VI III I
SQL?
4 Give the form of a basic SQL query. Write SQL queries to
demonstrate the usage of SQLdate and time data types and III III III
functions.
5 Explain the standard functions provided by SQL for String
V III II
manipulation
6 Explain about Different types of Functions in SQL? IV III II
7 Consider the following relational database. Give an
expression in SQL for each of the following queries.
employee (employee-name, street, city) works (employee-
name, company-name, salary) company (company-name,
city) manages (employee-name, manager-name)
a. Find the names of all employees who work for First
Bank Corporation.
b. Find the names and cities of residence of all employees
who work for First Bank Corporation. VI III III
c. Find the names, street addresses, and cities of
residence of all employees who work for First Bank
Corporation and earn more than $10,000.
d. Find all employees in the database who live in the
same cities as the companies for which they work.
e. Find all employees in the database who live in the
same cities and on the same streets as do their managers.
f. Find all employees in the database who do not work
for First Bank Corporation.
8
Consider the following schema
Customer (custId: Number, custName: String,
IV III II
city: String)

Order_Details(ordNo: Number, purAmt:


Number,ordDate: Date, custId:Number)

i) Write a SQL query to display those customers who

belongs to thecity “Hyderabad” and last purchase

amount is less than Rs.1000/-.

ii) Write a SQL statement to exclude the rows which


satisfy

a) order dates are 01-01-2023 and purchase


amount is below Rs.500/-

b) customers city is “Hyderabad” and purchase amount is


below Rs.500/-
9 Consider the following Relational schemas,

Sailors( sid: Integer, sname:

String, age: Integer, rating:

Integer)Boats(bid: Integer, bname:

String, bcolor: String) III III IIII

Reserves(sid: Integer, bid: Integer, date: Date)

Write the following queries in SQL

i) Find the names of sailors with Third highest rating


ii) Find the age of youngest sailor who is eligible to vote
(18 years age) for eachrating level with at least 2 sailors.
10 Consider the following Relational schemas,
Sailors( sid: Integer, sname: String, age: Integer, rating:
Integer)
Boats(bid: Integer, bname: String, bcolor: String)

Reserves(sid: Integer, bid: Integer, date: Date)


III III I
Write the following queries inw2q1 SQL

i) find the names of sailors who have reserved a red and


a green boat

ii) find the names of sailors who have reserved all boats
11 Explain the following SQL constructs with examples:
VI III II
(i) order by (ii) group by (iii) and having
12 Explain the distinctions among the terms primary key,
foreign key, unique key. III III II
13 Discuss about how add the constraints at table level and
column level with an example II III II

14 How to add the primary key, unique, foreign key and check
constraints on a table using alter command? IV III III

15 Explain Various types of keys? IV III I


16 What is a constraint? Explain in detail about integrity
constraints II III I

17 What is a nested query? Explain with SQL examples IV III I


18 What are nested queries? What is correlation in nested
queries? How would you use the operators IN, EXISTS,
UNIQUE, ANY, and ALL in writing nested queries? Explain II III II
with example

19 Write SQL queries using exists, in, not, any, and all I III III
20 Define Sub queries? Explain with Example queries? IV III I
21 What are the aggregate functions in explain with an
example? II III II

22 Explain Group by clause and order by clause with examples? II III I


23 Explain in brief about different types of joins in SQL II II III
24 What are the advantages of views? List out the constraints
for defining updateable and non-updateable views II III II

25 Discuss about updates on views. What is the need to restrict


view updates IV III I

26 Explain about the complex views and how they are


implemented in SQL? II III I

27 Write SQL queries using union, union all, intersect, minus


and explain?. IV III I

28 Explain about Relational Set operators with some examples? III III I
UNIT-III

SAQ’S
PART-B

1) Write a SQL query by using Select and Project commands with some examples?
ANS) a. Selection Operation
1. The selection operation works on a single relation R
2. And it defines a relation that contains only those tuples of R
3. That satisfies the specified condition (Predicate).
4. Selection operation can be considered as row wise filtering.
5. This is pictorially represented also known as RESTRICT
6. It creates values for all rows found in a table that satisfy a given condition.
7. Select can be used to list all of the row values, or it can create only those
row values
8. That matches a specified criterion.

9. Select create a horizontal subset of a table.

Syntax
σ Predicate (R).
ex: σ subject = "database"(Books)

b. Projection Operation
1. The projection operation works on a single relation R
2. And defines a relation that contains a vertical subject of R,
3. And extracting the values of specified attributes and elimination duplicates.
4. The projection operation can be considered as column wise filtering.

It’s creates all values for selected attributes. In other words, project creates a vertical
subset of a table.
Syntax
a1,a2, ..... an (R).
[Where a1, a2, ......... an are attributes and R stands for relation To illustrate projection operation consider
the relation STAFF, with the attributes Staff number, Name, Gender, Date of birth, and Salary.]
2) Discuss about Where Clause in Database
ANS) SQL Where clause:

 A where clause in SQL is a data manipulation language statement.


 Where clauses are not mandatory clauses of SQL DML statements but it can be
used to limit the number of rows affected by a SQL DML statement or
returned by query.
 Actually, it follows the records.it returns only those queries which the specific conditions.
Syntax:
Select column1, column2, …………column from table_name where[condition];

Where clause uses same conditional selection.

= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

3) Discuss in brief about arithmetic and logic operations in SQL?


ANS) Arithmetic and logical operations:

SQL operators:

 SQL statements generally contain some reserved words or characters that are used to
perform operations such as arithmetic and logical operations etc. Their reserved
words are known as operators.
SQL arithmetic operator:

 We can use various arithmetic operators on the data stored in tables.


 Arithmetic operators are:



+ Addition
- Subtraction
/ Division
* Multiplication
% modulus



1. Addition (+):
It is used to perform addition operation on data items.
Sample table:
EMP_ID EMP_NAME SALARY

1 Alex 25000
2 John 55000
3 Daniel 52000
4 Sam 12312
Output:
EMP_ID EMP_NAM SALARY SALARY+100
E
1 Alex 25000 25100
2 John 55000 55100
3 Daniel 52000 52100
4 Sam 12312 12412
 Here we have done addition of 100 to each emp‟s salary.

2. Subtraction (-):
 It is used to perform subtraction on the data items.
Example:

Select emp_id, emp_name, salary, salary-100 as “salary-100” from employee;

EMP_ID EMP_NAM SALARY SALARY-100


E
1 Alex 25000 24900
2 John 55000 54900
3 Daniel 52000 51900
4 Sam 90000 89900
Here we have done subtraction of 100 for each emp‟s salary.

3. Division (/):
 The division function is used to integer division (x is divided by y).an integer value
Is returned.
Example:

 Select emp_id, emp_name, salary, salary/100 as


“salary/100” from employee;

EMP_ID EMP_NAME SALARY Salary/100


1 Alex 25000 250
2 John 55000 550
3 Daniel 52000 520
4 Sam 90000 900

4. Multiplication (*):
 It is used to perform multiplication of data items.
 Select emp_id, emp_name, salary, salary*100 as
“salary*100” from employee;

EMP_ID EMP_NAME SALARY SALARY*1


00
1 Alex 25000 2,500,000
2 John 55000 5,500,000
3 Daniel 52000 5,200,000
4 Sam 90000 9,000,000
 Here we have done multiplication of 100 to each emp‟s salary.

5. Modulus (%):
 It is used to get remainder when one data is divided by another. In oracle we mod in place of
symbol(%).
 Select emp_id, emp_name, salary,mod(salary,500) as
“salary%25000”
from modulus;

Output:
EMP_ID EMP_NAME SALARY SALARY%2
500
0
1 Alex 25000 0
2 John 55000 5000
3 Daniel 52000 2000
4 Sam 90000 15000
 Here we have done modulus operation to each emps salary.

Logical operations:

 Logical operations allow you to test for the truth of a condition.


 The following table illustrates the SQL logical operator.

OPERATOR MEANING
ALL Returns true if all comparisons are
true
AND Returns true if both expressions
are true
ANY Returns true if any one of the
comparisons is
true
BETWEEN Return true if the operand is within
a range
IN Return true if the operand is equal to one
of
the values in a list
EXISTS Return true if the sub query
contains any rows

AND:
The AND operator allows you to construct multiple condition in the WHERE clause of
an SQLstatement such as select.
The following example finds all employees where salaries are greater than the 5000 and
less than 7000.
 Select first_name, last_name, salary from
employees where salary>5000 AND
salary<7000 order by salary;

Output:
FIRST_NA LAST_NAME SALARY
ME
John Wesley 6000
Eden Daniel 6000
Luis Popp 6900
Shanta Suji 6500

2. ALL:
The ALL operator compares a value to all values in another value set.

 The following example finds all employees whose salaries are greater
than all salaries of employees.
EX:
select first_name, last_name, salary from employees where
salary>=ALL (select salary from employees where
department_id =8) order by salary DESC;

Output:

FIRST_NA LAST_NAME SALARY


ME
Steven King 24000
John Russel 17000
Neena Kochhar 14000

3. ANY:
The ANY operator compares a value to any value in a set ascending to condition.
The following example statement finds all employees whose salaries are greater than
the averagesalary of every department.
EX:
select first_name, last_name, salary from employees where salary
>ANY (select avg (salary) from employees‟ group by department_id)
order by first_name, last_name;

Output:

FIRST_NA LAST_NAME SALARY


ME
Alexander Hunold 9000.00
Charles Johnson 6200.00
David Austin 4800.00
Eden Flip 9000.00

4. Between:
 The between operator searches for values that are within a set of values.
 For example, the following statement finds all employees where salaries
are between 9000 and 12000.

EX:

select first_name, last_name, salary from employees where


salary between 9000 AND 12000 order by salary;

Output:

FIRST_NAME LAST_NAME SALARY


Alexander Hunold 9000.00
Den Richards 10000.00
Nancy Prince 12000.00
5. IN:
 The IN operator compares a value to list of specified values. The IN operator
return true if compared value matches at least one value in the list.
 The following statement finds all employees who work in

department _id 8 or 9.

 EX:
select first_name, last_name, department_id from employees
where department_id IN (8,9) order by department_id;

output:

FIRST_NAME LAST_NAME DEPARTMEN


T_ID
John Russel 8
Jack Livingstone 8
Steven King 9
Neena Kochhar 9

Exists:

 The EXISTS operator tests if a sub query contains any rows.


 For example, the following statement finds all employees who have dependents.
 select first_name, last_name from employees where
EXISTS (select 1 from dependent d where
d.employee_id=e.employee_id);

FIRST_NAME LAST_NAME
Steven King
Neena Kochhar
Alexander Hunold
4) Give the form of a basic SQL query. Write SQL queries to demonstrate the usage of SQLdate and
time data types and functions.

ANS)
DATE & TIME FUNCTIONS:
Some important date and time functions are below:

Sysdate: It generates the

system date. Ex: Select

sysdate from dual;

Output: 05-DEC-2021.

ADD_MONTHS: This function returns a date after adding data with specified no of months.EX:

Select ADD_MONTHS („2017-02-29‟,1) from dual;

Output: 31-MAR-17.
Select add_months(sysdate,3) from dual;

Output: 05-MAR-22.

CURRENT_DATE: This function displays the current date.

Ex: Select CURRENT_DATE from dual;


Output: 05-DEC-2021.

NEXT_DAY: This function represents both day and date and returns the day of the next given day.

EX: Select NEXT_DAY(SYSDATE,‟MONDAY‟) from dual;

Output: 07-DEC-21.

LAST_DAY: This function returns a day corresponding last day of months.

EX: Select LAST_DAY (sysdate) from dual;

Output: 31-DEC-21.
MONTHS_BETWEEN: It is used to find no of months between two
given dates.

EX: Select MONTHS_BETWEEN(‟16-APRIL-2021‟,‟16-AUGUST-2021)


from dual;

Output: -4.

ROUND: It gives the nearest value or round off value for the argument pass. (or) It returns
a daterounded to a specific unit of measure.

EX: Select ROUND(‟26-NOV-21‟,‟YYYY‟) from dual;

Output: 01-JAN-22.

TRUNC: This function returns the date with the time(co-efficient) portion of the date
truncated to the unit specified.

EX: Select TRUNC (sysdate, ‟MM‟) from dual;

Output: 01-DEC-21.

TO_DATE: This function converts date which is in the character string to a date value.

EX: Select TO_DATE (‟01 jan 2017‟,‟DD MM YYYY‟) from dual;

Output: 01-JAN-17.

TO_CHAR: This function converts DATE or an INTERVAL value to a character string


in a specified format.
EX: Select TO_CHAR (sysdate,‟DD MM YYYY‟) from dual;

Output: 05 12 2021.

LEAST: This function displays the oldest date present in the argument list.

EX: Select LEAST(‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟)


from dual;

Output: 01-MAR-21.

GREATEST: This function displays the latest date present in the


argument list.

EX: Select GREATEST (‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟)


from dual;

Output: 28-DEC-21.

5) Explain the standard functions provided by SQL for String manipulation

ANS) STRING CONVERSION FUNCTIONS OF SQL:


String Functions are used to perform an operation on input string and return the
output string. Following are the string functions

1. CONCAT (): This function is used to add two words (or) strings.

EX: select „database‟ ||‟ „|| „management system‟ From dual;

OUTPUT: „database management system‟

2. INSTR (): This function is used to find the occurrence of an alphabet.

EX: instr („database system‟,‟ a‟) from dual;

OUTPUT: 2 (the first occurrence of „a‟)

3. LOWER (): This function is used to convert the given string into lowercase.

EX: select lower („DATABASE‟) from dual;

OUTPUT: database

4. UPPER (): This function is used to convert the lowercase string into uppercase.
EX: select upper („database „) from dual;

OUTPUT: DATABASE

5. LPAD (): This function is used to make the given string of the given size by adding the given symbol.

EX: > lpad („system „, 8, „0‟) from dual;

OUTPUT: 00system
6. RPAD (): This function is used to make the given string as long as the given size
by adding the given symbol on the right.

EX: rpad („system „,8, „0„) from dual;

OUTPUT: system00

7. LTRIM (): This function is used to cut the given substring from the original string.

EX: ltrim („database „, „data „) from dual;

OUTPUT: base

8. RTRIM (): This function is used to cut the given

substring from the original string.EX: rtrim

(„database „, „base „) from dual;

OUTPUT: data.

9. INITCAP (): This function returns the string with first letter of each word starts with uppercase.

EX: Select INITCAP („data base management system‟) from dual;

OUTPUT: Data Base Management System.

10. LENGTH (): Tis function returns the length of the given string.

EX: select LENGTH („SQ LANGUAGE‟) from dual;

OUTPUT: 11.

11. SUBSTR (): This function returns a portion of a string beginning

at the character position.EX: select SUBSTR („MY WORLD


IS AMAZING‟,12,3) from dual; OUTPUT: AM.

12. TRANSLATE (): This function returns a string after replacing some set of characters

into another set.EX: select TRANSLATE („Delhi is the capital of

India‟,‟i‟,‟a‟) from dual;

OUTPUT: Delha as the capatal andaa.

6) Explain about Different types of Functions in SQL?

ANS) SQL FUNCTIONS (Date & Time, Numeric, Aggregate, String conversions):

DATE & TIME FUNCTIONS:


Some important date and time functions are below:

Sysdate: It generates the

system date. Ex: Select

sysdate from dual;

Output: 05-DEC-2021.

ADD_MONTHS: This function returns a date after adding data with specified no of months. EX:

Select ADD_MONTHS („2017-02-29‟,1) from dual;

Output: 31-MAR-17.
Select add_months(sysdate,3) from dual;

Output: 05-MAR-22.

CURRENT_DATE: This function displays the current date.

Ex: Select CURRENT_DATE from dual;

Output: 05-DEC-2021.
NEXT_DAY: This function represents both day and date and returns the day of the next given day.

EX: Select NEXT_DAY(SYSDATE,‟MONDAY‟) from dual;

Output: 07-DEC-21.

LAST_DAY: This function returns a day corresponding last day of months.

EX: Select LAST_DAY (sysdate) from dual;

Output: 31-DEC-21.
MONTHS_BETWEEN: It is used to find no of months between two
given dates.

EX: Select MONTHS_BETWEEN(‟16-APRIL-2021‟,‟16-AUGUST-2021)


from dual;

Output: -4.

ROUND: It gives the nearest value or round off value for the argument pass. (or) It returns
a daterounded to a specific unit of measure.

EX: Select ROUND(‟26-NOV-21‟,‟YYYY‟) from dual;

Output: 01-JAN-22.

TRUNC: This function returns the date with the time(co-efficient) portion of the date
truncated to the unit specified.

EX: Select TRUNC (sysdate, ‟MM‟) from dual;

Output: 01-DEC-21.

TO_DATE: This function converts date which is in the character string to a date value.

EX: Select TO_DATE (‟01 jan 2017‟,‟DD MM YYYY‟) from dual;

Output: 01-JAN-17.

TO_CHAR: This function converts DATE or an INTERVAL value to a character string


in a specified format.

EX: Select TO_CHAR (sysdate,‟DD MM YYYY‟) from dual;

Output: 05 12 2021.
LEAST: This function displays the oldest date present in the argument list.

EX: Select LEAST(‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟)


from dual;

Output: 01-MAR-21.

GREATEST: This function displays the latest date present in the


argument list.

EX: Select GREATEST (‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟)


from dual;

Output: 28-DEC-21.

Aggregate Functions:

Aggregate Functions take a collection of values as input and returns a single value.
1. Count ()
2. Sum ()
3. Avg ()
4. Max ()
5. Min ()

1. Count (): This function returns number of rows returned by a query.


Syntax: Select count(column_name)

From

table_name

Where

condition);

Example: Select count (distinct manager_id) from employees;

2. Sum (): It will add/ sum all the column values in the query.
Syntax: Select sum (column_name)

From

table_na

me Where

condition);
Example: Select sum(salaries) from employees;

3. Avg (): Avg function used to calculate average values of the set of rows.
Syntax: Select avg (column_name)

From

table_na

me Where

condition);

Example: Select avg(salary) from employees;

4. Max (): This function is used to find maximum value from the set of values.

Syntax: Select max (column_name)

From

table_na

me Where

condition);

Example: Select max (salary) from employees;

5. Min (): This function is used to find minimum value from the set of values.

Syntax: Select min (column_name)

From table_name

Where condition);

Example: Select min (salary) from employees;

SQL NUMERIC FUNCTIONS:


Numeric functions are used to perform operations on numbers and return numbers.

Following are some of the Numeric functions

1. ABS (): It returns the absolute value of a

number. EX: select ABS (- 243.5)

from dual; OUTPUT:

243.5

2. ACOS (): It returns the cosine of a


number. EX: select ACOS
(0.25) from dual;
OUTPUT: 1.318116071652818

3. ASIN (): It returns the arc sine of a


number. EX: select ASIN
(0.25) from dual;
OUTPUT: 0.253680255142

4. CEIL (): It returns the smallest integer value that is a greater than or equal
to a number. EX: select CEIL (25.77) from dual;
OUTPUT: 26
5. FLOOR (): It returns the largest integer value that is a less than or equal to a
number. EX: select FLOOR (25.75) from dual;
OUTPUT: 25
6. TRUNCATE (): This does not work for SQL server. It returns the truncated to 2 places
right of the decimal point.
EX: select TRUNCATE (7.53635, 2) from dual;
OUTPUT: 7.53
7. MOD (): It returns the remainder when two
numbers are divided. EX: select MOD
(55,2) from dual;
OUTPUT: 1.
8. ROUND (): This function rounds the given value to given number of digits of
precision. EX: select ROUND (14.5262,2) from dual;
OUTPUT: 14.53.
9. POWER (): This function gives the value of m raised to the
power of n. EX: select POWER (4,9) from dual;
OUTPUT: 262144.
10. SQRT (): This function gives the square root of the
given value n. EX: Select SQRT
(576) from dual;
OUTPUT: 24.
11. LEAST (): This function returns least integer from given set of

integers. EX: select LEAST (1,9,2,4,6,8,22)

from dual;

OUTPUT: 1.

12. GREATEST (): This function returns greatest integer from given set

of integers. EX: select GREATEST

(1,9,2,4,6,8,22) from dual;

OUTPUT: 22

STRING CONVERSION FUNCTIONS OF SQL:


String Functions are used to perform an operation on input string and return the
output string. Following are the string functions

1. CONCAT (): This function is used to add two words (or) strings.
EX: select „database‟ ||‟ „|| „management system‟ From dual;

OUTPUT: „database management system‟


2. INSTR (): This function is used to find the occurrence of an alphabet.
EX: instr („database system‟,‟ a‟) from dual;

OUTPUT: 2 (the first occurrence of „a‟)

3. LOWER (): This function is used to convert the given string into lowercase.
EX: select lower („DATABASE‟) from dual;

OUTPUT: database

UPPER (): This function is used to convert the lowercase string into uppercase.

EX: select upper („database „) from dual;


OUTPUT: DATABASE
4. LPAD (): This function is used to make the given string of the given size by adding the given symbol.
EX: > lpad („system „, 8, „0‟) from dual;

OUTPUT: 00system

5. RPAD (): This function is used to make the given string as long as the given size
by adding the given symbol on the right.

EX: rpad („system „,8, „0„) from dual;

OUTPUT: system00

6. LTRIM (): This function is used to cut the given substring from the original string.

EX: ltrim („database „, „data „) from dual;

OUTPUT: base

7. RTRIM (): This function is used to cut the given

Substring from the original string.EX: rtrim

(„database „, „base „) from dual;

OUTPUT: data.
8. INITCAP (): This function returns the string with first letter of each word starts with uppercase.
EX: Select INITCAP („data base management system‟) from dual;

OUTPUT: Data Base Management System.

9. LENGTH (): Tis function returns the length of the given string.

EX: select LENGTH („SQ LANGUAGE‟) from dual;

OUTPUT: 11.

10. SUBSTR (): This function returns a portion of a string beginning

at the character position.EX: select SUBSTR („MY WORLD

IS AMAZING‟,12,3) from dual;


OUTPUT: AM.

11. TRANSLATE (): This function returns a string after replacing

some set of characters into another set.EX: select

TRANSLATE („Delhi is the capital of

India‟,‟i‟,‟a‟) from dual; OUTPUT: Delha as the

capatal andaa.

7) Consider the following relational database.


Give an expression in SQL for each of the following queries. employee (employee-name,
street, city) works (employee-name, company-name, salary) company (company-name,
city) manages (employee-name, manager-name)

a. Find the names of all employees who work for First Bank Corporation.

b. Find the names and cities of residence of all employees who work for First
Bank Corporation.
c. Find the names, street addresses, and cities of residence of all employees who work
for First Bank Corporation and earn more than $10,000.
d. Find all employees in the database who live in the same cities as the companies
for which they work.

Ans)

a) Find the names of all employees who work for First Bank Corporation.

SELECT w.employee- name


FROM works w
WHERE w.company-name = 'First Bank Corporation';

b) Find the names and cities of residence of all employees who work for First Bank
Corporation.

SELECT e.employee-name, e.city


FROM employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.company-name = 'First Bank Corporation';

c) 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 e.employee-name, e.street, e.city


FROM employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.company-name = 'First Bank Corporation'
AND w.salary > 10000;

d) Find all employees in the database who live in the same cities as the companies for
which they work.

SELECT e.employee-name, e.street, e.city FROM


employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.company-name = 'First Bank Corporation'
AND w.salary > 10000;
8) Consider the following schema
Customer (custId: Number, custName: String, city: String)
Order_Details(ordNo:Number,purAmt: Number,ordDate:Date, custId:Number)

i) Write a SQL query to display those customers who belongs to thecity “Hyderabad”
and last purchase amount is less than Rs.1000/-.
ii) Write a SQL statement to exclude the rows which satisfy
a) order dates are 01-01-2023 and purchase amount is below Rs.500/-
b)customers city is “Hyderabad” and purchase amount is below Rs.500/-

Ans)

i) Write a SQL query to display those customers who belongs to thecity “Hyderabad”
and last purchase amount is less than Rs.1000/-.

ii) Write a SQL statement to exclude the rows which satisfy


a) order dates are 01-01-2023 and purchase amount is below Rs.500/-
b)customers city is “Hyderabad” and purchase amount is below Rs.500/-

SELECT *
FROM Order_Details o
JOIN Customer c ON o.custId = c.custId WHERE
NOT (
(o.ordDate = '2023-01-01' AND o.purAmt < 500) OR
(c.city = 'Hyderabad' AND o.purAmt < 500)
);

9) Consider the following Relational schemas,

Sailors( sid: Integer, sname: String, age: Integer, rating: Integer)


Boats(bid: Integer, bname: String, bcolor: String)
Reserves(sid: Integer, bid: Integer, date: Date)

Write the following queries in SQL

i) Find the names of sailors with Third highest rating


ii) Find the age of youngest sailor who is eligible to vote (18 years age) for each rating level
with at least 2 sailors
Ans)

i) Find the names of sailors with Third highest rating

ii) Find the age of youngest sailor who is eligible to vote (18 years age) for each rating level with at least 2 sailors

10) Consider the following Relational schemas,

Sailors( sid: Integer, sname: String, age: Integer, rating: Integer) Boats(bid: Integer, bname:
String, bcolor: String)
Reserves(sid: Integer, bid: Integer, date: Date)

Write the following queries in SQL

i) find the names of sailors who have reserved a red and a green boat
ii) find the names of sailors who have reserved all boats
Ans)
i) find the names of sailors who have reserved a red and a green boat
ii) find the names of sailors who have reserved all boats

11)Explain the following SQL constructs with examples:

(i) order by (ii) group by (iii) and having

ANS) Basic SQL querying (select and project) using where clause:

The following are the various SQL clauses: SQL


Clause

Group by clause having clause Order by clause

1. Group by:
 SQL group by statement is used to arrange identical data into groups.
 The group by statement is used with the SQL select statement.
 The group by statement follows the WHERE clause in a SELECT statement
and precedes the ORDER BY clause.
Syntax:

Select column from table_name where column group by column,


order by column;

Sample table: product

PRODUC COMPA QTY RATE COST


T NY
Item 1 Com 1 2 10 20
Item 2 Com 2 3 25 75
Item 3 Com 1 2 30 60
Item 4 Com 3 5 10 50
Item 5 Com 2 2 20 40

Example:

 Select company count (*) from product group by company;

Output:

Com 1 2
Com 2 2
Com 3 1

2. Having clause:
 Having clause is used to specify a search condition for a group or an aggregate.

Having clause is used in a group by clause, if you are not using group by clause then you
Can usehaving function like a where clause.

Syntax:
Select column1, column2 from table_name

Conditions Group

by column1,

column2 Having conditions Order

by column1, column2;
Example:

 select company count (*) from product Group by company Having count (*)
= 2;

Output:

Com 2 2
Com 1 2

3. Order by clause:
The order by clause sorts the result _set in ascending or descending order.

Syntax:

Select column1, column2, from


table_name

Where condition

Order by column1, column2…asc;

Sample table:

Take a student table

Example:

Select * from student order by name;


Output:

NAME ID CITY
Alekhya 501 Hyderabad
Deepti 502 Guntur
Rasi 503 Nellore

12)Explain the distinctions among the terms primary key, foreign key, unique key.

ANS)
PRIMARY KEY constraint :-

PRIMARY KEY is one of the candidates key , which uniquely identifies a record in a table.
-used to define key column of a table.
-it is provided with an automatic index.
-A primary key constraint combines a NOT NULL and UNIQUE behavior in one declaration.

Characteristics of PRIMARY KEY :-

 There should be at the most one Primary Key or Composite primary key per table.
 PK column do not accept null values.
 PK column do not accept duplicate values.
 RAW,LONG RAW,VARRAY,NESTED TABLE,BFILE columns cannot be declared with PK
 If PK is composite then uniqueness is determined by the combination of columns.
 A composite primary key cannot have more than 32 columns
 It is recommended that PK column should be short and numeric.
 Oracle automatically creates Unique Index on PK column
Ex:

FOREIGN KEY Constraint: -

 Foreign key is used to establish relationship between tables.


 Foreign key is a column in one table that refers primary
key/uniquecolumns of another or same table.

 Values of foreign key should match with values of primary key/unique orforeign
key can be null.

 Foreign key column allows null values unless it is declared with NOTNULL.
 Foreign key column allows duplicates unless it is declared with UNIQUE
 By default, oracle establish 1:M relationship between two tables.
 To establish 1:1 relationship between two tables declare foreign key with unique
constraint

 Foreign key can be declared at column level or table level.

 Composite foreign key must refer composite primary key or Compositeunique key.

EX: TABLES: STUDENT 1 & MARKS 1

PARENT TABLE ‘STUDENT1’ :


Unique:

Sometimes we need to maintain only. Unique data in the column of a database table,
this is possible by using a unique constraint.

 Unique constraint ensures that all values in a column are Unique.

Example:

Create table PERSONS (id int unique, last_name varchar (25) not null,First name
varchar (25), age int);
In the above example, as we have used unique constraint on ID column we are not

Supposed to enter the data that is already present, simply no two ID values
are same.
13)Discuss about how to add the constraints at table level and column level with an example

Ans) We can add constraints in two ways


Column level :-

 Constraint is declared immediately after declaring the column.


 Define with each column
 Use column level to declare constraint for single column.
 Composite key cannot be defined at column level.
Table level :-

constraint is declared after declaring all columns.


use table level to declare constraint for combination of columns.(i.e composite key)
 not null cannot be defined.

Another type is possible at Alter level

 constraint is declared with ALTER

command.

When we use this, make sure that the table should not contain data.

To add these constraints, we can use constraint with label or without


label. TWO BASIC TYPES -------

1. Constraint WITH NAME


2. Constraints WITHOUT NAME.

i) Declaring Constraint at “TABLE” level (Constraints


with label) Syntax :- CREATE TABLE
<table name> (
col_name1 DATATYPE(SIZE) ,

…..,

col_nameN DATATYPE(SIZE) ,

CONSTRAINT <cons_lable> NAME _OF_ THE_CONSTRAINT [column_list] );


ii) Declaring Constraint at “Column” level (Constraints with label)
Syntax :-
col_name DATATYPE(SIZE) CONSTRAINT <cons_lable> NAME _OF_ THE_CONSTRAINT

iii) Declaring Constraint at “TABLE” level (Constraints without label)


Syntax :-
CREATE TABLE <table name>( col_name1
DATATYPE(SIZE) ,

…..,

col_nameN DATATYPE(SIZE) ,
NAME _OF_ THE_CONSTRAINT [column_list] );

iv) Declaring Constraint at “Column” level (Constraints without


label) Syntax :-
col_name DATATYPE(SIZE) NAME _OF_ THE_CONSTRAINT

v) Adding Constraint to a table at “Alter” level (Constraints with label)

A constraint can be added to a table at any time after the table was created by using
ALTERTABLE statement, using ADD clause.

Syntax:

ALTER TABLE <table_name> ADD CONSTRAINT cont_label NAME _OF_


THE_CONSTRAINT (column);

vi) Declaring Constraint at “Alter” level (Constraints without label) Syntax:

ALTER TABLE <table_name> ADD NAME _OF_ THE_CONSTRAINT

(column);

Note:’ Constraint ‘clause is not required when constraints declared without a label.
14)How to add the primary key, unique, foreign key and check constraints on a table using alter command?

Ans) ADD PRIMARY KEY @ ALTER LEVEL

ADD UNIQUE KEY @ ALTER LEVEL

Alter table table_unique ADD UNIQUE (sid) // with out label

Alter table table_unique ADD CONSTRAINT uq UNIQUE(sid) // with label

ADD FOREIGN KEY @ ALTER LEVEL

ADD CHECK CONSTRAINT @ ALTER LEVEL


15)Explain Various types of Keys?`
Ans) PRIMARY KEY:-

PRIMARY KEY is one of the candidates key , which uniquely identifies a record in a table.
-used to define key column of a table.
-it is provided with an automatic index.
-A primary key constraint combines a NOT NULL and UNIQUE behavior in one declaration.
Characteristics of PRIMARY KEY :-

 There should be at the most one Primary Key or Composite primary key per table.
 PK column do not accept null values.
 PK column do not accept duplicate values.
 RAW,LONG RAW,VARRAY,NESTED TABLE,BFILE columns cannot be declared with PK
 If PK is composite then uniqueness is determined by the combination of columns.
 A composite primary key cannot have more than 32 columns
 It is recommended that PK column should be short and numeric.
 Oracle automatically creates Unique Index on PK column

Ex:
FOREIGN KEY :-

 Foreign key is used to establish relationship between tables.


 Foreign key is a column in one table that refers primary
key/uniquecolumns of another or same table.

 Values of foreign key should match with values of primary key/unique orforeign
key can be null.

 Foreign key column allows null values unless it is declared with NOTNULL.
 Foreign key column allows duplicates unless it is declared with UNIQUE
 By default, oracle establish 1:M relationship between two tables.
 To establish 1:1 relationship between two tables declare foreign key with unique
constraint

 Foreign key can be declared at column level or table level.


 Composite foreign key must refer composite primary key or Compositeunique key.

EX: TABLES: STUDENT 1 & MARKS 1

PARENT TABLE ‘STUDENT1’ :


UNIQUE KEY:-

Sometimes we need to maintain only. Unique data in the column of a database table,
this is possible by using a unique constraint.

 Unique constraint ensures that all values in a column are Unique.

Example:

Create table PERSONS (id int unique, last_name varchar (25) not null,First name
varchar (25), age int);
In the above example, as we have used unique constraint on ID column we are not

supposedto enter the data that is already present, simply no two ID values
are same.

16)What is a constraint? Explain in detail about integrity constraints

Ans) Data constraints: All the business world run on business data being gathered, stored and
analyzed. Business managers determine a set of business rules that must be applied to their data
prior to it being stored in the database/table of ensure its integrity.
For instance, no employee in the sales department can have a salary of less than Rs.1000/- . Such
rules have to be enforced on data stored. If not, inconsistent data is maintained in database.

Note: It is used to impose business rules on DBs. It allows to enter only valid data.

Various types of Integrity Constraints:


Integrity constraints are the rules in real life, which are to be imposed on the data. If the data is not
satisfying the constraints then it is considered as inconsistent. These rules are to be enforced on
data because of the presence of these rules in real life. These rules are called integrity constraints.
Every DBMS software must enforce integrity constraints, otherwise inconsistent data is
generated.

You can use constraints to do the following:

 To prevent invalid data entry into tables.


 To Enforce rules on the data in a table whenever a row is inserted, updated, or
deleted from that table. The constraint must be satisfied for the operation to
succeed.
 To Prevent the deletion of a record from a table if there are dependencies.


Example for Integrity Constraints :-

Constraints are categorized as follows.

2. Domain integrity constraints - A domain means a set of values assigned to a column.


i.e A set of permitted values. Domain constraints are handled by
Defining proper data type

Specifying not null constraint

Specifying check constraint.

Specifying default constraint


Not null –indicates that a column cannot store NULL value.
Check – Ensures that the value in column meets a specific condition.
Default- prevents null value in column when value is not provided in column by user. So, it assigns
default value or globally assigned value.

3. Entity integrity constraints – are TWO types


Unique constraint –It defines a Entity or column as a UNIQUE for particular table.

And ensures that each row of a column must have a UNIQUE value or name.
Primary key constraint – This avoids duplicate and null values. It combination of a NOT NULL
and UNIQUE.

4. Referential integrity constraints


Foreign key –indicates the relationship between child and parent tables. This
Constraint are always attached to a column not a table.

17)What is a nested query? Explain with SQL examples


ANS)
A subquery is a SQL query nested inside a larger query.
 A subquery may occur in :
- A SELECT clause
- A FROM clause
- A WHERE clause
 The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement
or inside another subquery.
 A subquery is usually added within the WHERE Clause of another SQL SELECT
statement.
 You can use the comparison operators, such as >, <, or =. The comparison operator canalso
be a multiple-row operator, such as IN, ANY, or ALL.
 A subquery is also called an inner query or inner select, while the statement
containing asubquery is also called an outer query or outer select.
 The inner query executes first before its parent query so that the results of inner query
canbe passed to the outer query.
You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to performthe
following tasks :
 Compare an expression to the result of the query.
 
 Determine if an expression is included in the results of the query.
 Check whether the query selects any rows.
Syntax :

 The subquery (inner query) executes once before the main query (outer query)
executes.
 The main query (outer query) use the subquery result.
Type of Subqueries
 Single row subquery : Returns zero or one row.
 Multiple row subquery : Returns one or more rows.
 Multiple column subquery : Returns one or more columns.
 Correlated subqueries : Reference one or more columns in the outer SQL statement. The
subquery is known as a correlated subquery because the subquery is related to the outerSQL
statement.
 Nested subqueries : Subqueries are placed within another subqueries.
SINGLE ROW SUBQUERIES:- Returns zero or one row.
If inner query returns only one row then it is called single row subquery.

Syntax :-

SELECT <collist> FROM <tabname>


WHERE colname OPERATOR (SELECT statement)
Operator can be < > <= >= = <>
Examples:- (on Emp Table)
18)What are nested queries? What is correlation in nested queries? How would you use the operators IN,
EXISTS, UNIQUE, ANY, and ALL in writing nested queries? Explain with example

19)Write SQL queries using exists, in, not, any, and all

ANS) Exists:
 The EXISTS operator tests if a sub query contains any rows.
 For example, the following statement finds all employees who have dependents.
 select first_name, last_name from employees where
EXISTS (select 1 from dependent d where
d.employee_id=e.employee_id);

FIRST_NAME LAST_NAME
Steven King
Neena Kochhar
Alexander Hunold
IN:
 The IN operator compares a value to list of specified values. The IN operator
return true if compared value matches at least one value in the list.

 The following statement finds all employees who work in

department _id 8 or 9. EX:

select first_name, last_name, department_id from employees


where department_id IN (8,9) order by department_id;

Output:

FIRST_NAME LAST_NAME DEPARTMEN


T_ID
John Russel 8
Jack Livingstone 8
Steven King 9
Neena Kochhar 9
ALL:
The ALL operator compares a value to all values in another value set.

 The following example finds all employees whose salaries are greater
than all salaries of employees.
EX:
select first_name, last_name, salary from employees where
salary>=ALL (select salary from employees where
department_id =8) order by salary DESC;

Output:

FIRST_NA LAST_NAME SALARY


ME
Steven King 24000
John Russel 17000
Neena Kochhar 14000
ANY:
The ANY operator compares a value to any value in a set ascending to condition.
The following example statement finds all employees whose salaries are greater than
the averagesalary of every department.
EX:
select first_name, last_name, salary from
employees where salary >ANY (select avg (salary)
from employees‟ group by department_id) order by first_name,
last_name;

Output:

FIRST_NA LAST_NAME SALARY


ME
Alexander Hunold 9000.00
Charles Johnson 6200.00
David Austin 4800.00
Eden Flip 9000.00

20)Define Sub queries? Explain with Example queries?


ANS) REFER 17TH QUESTION

21)What are the aggregate functions in explain with an example?


ANS)REFER 6TH QUESTION

22)Explain Group by clause and order by clause with examples?


ANS) REFER 11TH QUESTION
23)Explain in brief about different types of joins in SQL
ANS) SQL JOINS

A SQL JOIN is an Operation , used to retrieve data from multiple tables. It is performed
whenever two or more tables are joined in a SQL statement. so, SQL Join clause is used to
combine records from two or more tables in a database. A JOIN is a means for combining fields
from two tables by using values common to each. Several operators can be used to join tables,
such as =, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; these all to be used to join tables.However,
the most common operator is the equal symbol.
SQL Join Types:
There are different types of joins available in SQL:
 INNER JOIN
 OUTER JOIN:
- LEFT JOIN/LEFT OUTER JOIN: Returns all rows from the left table, even if there are no
matches in the right table.

-RIGHT JOIN/RIGHT OUTER JOIN: Returns all rows from the right table, even if there are no
matches in the left table.
-FULL JOIN/FULL OUTER JOIN: Returns rows when there is a match in one of the
tables

 SELF JOIN: It is used to join a table to itself as if the table were two
tables, temporarilyrenaming at least one table in the SQL statement.
 CARTESIAN JOIN or CROSS JOIN: It returns the Cartesian product of the sets of records from
the two or more joined tables.
Based on Operators, The Join can be classified as

- Inner join or Equi Join


- Non-Equi Join
 NATURAL JOIN: It is performed only when common column name is same. In
this,noneed to specify join condition explicitly , ORACLE automatically performs
join operation on the column with same name.
1. SQL INNER JOIN (simple join)
It is the most common type of SQL join. SQL INNER JOINS return all rows from
multipletables where the join condition is met.

Syntax

SELECT columns FROM table1 INNER JOIN table2 ON table1.column =


Table2.column; Visual Illustration
In this visual diagram, the SQL INNER JOIN returns the shaded area:

The SQL INNER JOIN would return the records where table1 and table2 intersect.Let's
look at some data to explain how the INNER JOINS work with example.

We have a table called SUPPLIERS with two fields (supplier_id and supplier_name).It
contains the following data:

supplier_id supplier_name

10000 ibm

10001 hewlett packard

10002 microsoft

10003 nvidia

We have another table called ORDERS with three fields (order_id, supplier_id, andorder_date).

It contains the following data:

order_id supplier_id order_date


500125 10000 2003/05/12
500126 10001 2003/05/13
500127 10004 2003/05/14

Example of INNER JOIN:

Q: List supplier id, name and order id of supplier.

SELECT s.supplier_id, s.supplier_name, od.order_date FROM suppliers s INNER JOINorders od ON


s.supplier_id = od.supplier_id;
This SQL INNER JOIN example would return all rows from the suppliers and orders tables where
there is a matching supplier_id value in both the suppliers and orders tables.

Our result set Would look like this:

supplier_id Name order_date


10000 Ibm 2003/05/12
10001 hewlett packard 2003/05/13

The rows for Microsoft and NVIDIA from the supplier table would be omitted, since the supplier_id's
10002 and 10003 do not exist in both tables.

The row for 500127 (order_id) from the orders table would be omitted, since thesupplier_id 10004
does not exist in the suppliers table.

2. OUTER JOIN:
Inner / Equi join returns only matching records from both the tables but not unmatched
record,An Outer join retrieves all row even when one of the column met join
condition.Types of outer join:

1. LEFT JOIN/LEFT OUTER JOIN


2. RIGHT JOIN/RIGHT OUTER JOIN
3. FULL JOIN/FULL OUTER JOIN
2.1. LEFT OUTER JOIN

This type of join returns all rows from the LEFT-hand table specified in the ON condition and
only those rows from the other table where the joined fields are equal (joincondition is met).

Syntax
SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON
table1.column = table2.column;

Visual Illustration

In this visual diagram, the SQL LEFT OUTER JOIN returns the shaded area:

The SQL LEFT OUTER JOIN would return the all records from table1 and only thoserecords
from table2 that intersect with table1.

Example

SELECT suppliers.supplier_id,
suppliers.supplier_name, orders.order_date FROM
suppliers LEFT OUTER JOIN orders ON suppliers.supplier_id =

orders.supplier_id;

This LEFT OUTER JOIN example would return all rows from the suppliers table and onlythose rows from
the orders table where the joined fields are equal.
supplier_id supplier_name order_date
-------------- ---------------------- ---------------------
--
10000 ibm 2003/05/12
10001 hewlett 2003/05/13
packard
10002 microsoft <null>
10003 nvidia <null>
The rows for Microsoft and NVIDIA would be included because a LEFT OUTER JOINwas
used. However, you will notice that the order_date field for those records contains a

<null> value.

2.2 SQL RIGHT OUTER JOIN

This type of join returns all rows from the RIGHT-hand table specified in the ON condition
and only those rows from the other table where the joined fields are equal (joincondition is
met).

Syntax

SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column


=table2.column; In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.

Visual Illustration

In this visual diagram, the SQL RIGHT OUTER JOIN returns the shaded area:

The SQL RIGHT OUTER JOIN would return the all records from table2 and only thoserecords from table1
that intersect with table2.

Example

SELECT orders.order_id, orders.order_date, suppliers.supplier_name FROM suppliers RIGHT


OUTER JOIN orders ON suppliers.supplier_id = orders.supplier_id;
This RIGHT OUTER JOIN example would return all rows from the orders table and onlythose rows from
the suppliers table where the joined fields are equal.

If a supplier_id value in the orders table does not exist in the suppliers table, all fields inthe
suppliers table will display as <null> in the result set.

order_id order_date supplier_name


------------ --------------- -----------------
500125 2013/05/12 ibm
500126 2013/05/13 hewlett
packard
500127 2013/05/14 <null>

The row for 500127 (order_id) would be included because a RIGHT OUTER JOIN wasused.
However, you will notice that the supplier_name field for that record contains a <null> value.

2.3. SQL FULL OUTER JOIN

This type of join returns all rows from the LEFT-hand table and RIGHT-hand table withnulls in place
where the join condition is not met.

Syntax

SELECT columns FROM table1 FULL [OUTER] JOIN table2 ON table1.column = table2.column; In
some databases, the FULL OUTER JOIN keywords are replaced withFULL JOIN.

Visual Illustration

In this visual diagram, the SQL FULL OUTER JOIN returns the shaded area:
The SQL FULL OUTER JOIN would return the all records from both table1 and table2.

Example

Here is an example of a SQL FULL OUTER JOIN:

Query : Find supplier id, supplier name and order date of suppliers who have ordered.

SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date FROM suppliers


FULL OUTER JOIN orders ON suppliers.supplier_id = orders.supplier_id;

This FULL OUTER JOIN example would return all rows from the suppliers table and allrows from
the orders table and whenever the join condition is not met, <nulls> would be extended to
those fields in the result set.

If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the
orders table will display as <null> in the result set. If a supplier_id value in the orderstable does
not exist in the suppliers table, all fields in the suppliers table will display as <null> in the result
set.

supplier_id supplier_name order_date


----------------- -------------------- --------------------
-
10000 ibm 2013/05/12
10001 hewlett 2013/05/13
packard
10002 microsoft <null>
10003 nvidia <null>
<null> <null> 2013/05/14

The rows for Microsoft and NVIDIA would be included because a FULL OUTER JOINwas used. However,
you will notice that the order_date field for those records contains a

<null> value.

The row for supplier_id 10004 would be also included because a FULL OUTER JOIN wasused.
However, you will notice that the supplier_id and supplier_name field for those records contain a

<null> value.

Equi join :

When the Join Condition is based on EQUALITY (=) operator, the join is said to be an Equijoin.
It is also called as Inner Join.
Syntax
Select col1,col2,…From <table 1>,<table 2>Where <join condition with ‘=’ > .

Ex.Query : Find supplier id, supplier name and order date of suppliers who have ordered .

select s.supplierid, s.uppliername ,o.order_date from suppliers s, orders o where s.supplierid

=o.supplierid.

supplier_id Name order_date


10000 ibm 2003/05/12
10001 hewlett packard 2003/05/13

Non Equi Join :-

When the join condition based on other than equality operator , the join is said to be a Non- Equijoin.
Syntax:-

Select
col1,col2,……
. From <table
1>,<table 2>

Where <join condition > [AND <join cond> AND <cond> ]

In NON- EQUI JOIN, JOIN COND is not based on = operator. It is based
on other than = operator, usually BETWEEN or > or < operators.
Query : Find supplier id,supplier name and order date in between 50025 and 500127.

sql> select s.supplier_id,s.supplier_name,o.order_date from suppliers s , orders o whereo.order_id between


500125 and 500127;

SUPPLIER_ID SUPPLIER_N ORDER_DAT

10000 ibm 12-may-03


10000 ibm 13-may-03
10000 ibm 14-may-03
10001 hewlett12-may-03
10001 hewlett13-may-03
10001 hewlett14-may-03
10002 microsoft 12-may-03
10002 microsoft 13-may-03
10002 microsoft 14-may-03
10003 nvidia 12-may-03
10003 nvidia 13-may-03
10003 nvidia 14-may-03

Query : Find supplier id,supplier name and order date above 500126.
sql> select s.supplier_id,s.supplier_name,o.order_date from suppliers s , orders o whereo.order_id
>500126;

SUPPLIER_ID SUPPLIER_NO ORDER_DAT


10000 ibm 14-may-03
10001 hewlett 14-may-
03
10002 microsof 14-may-
t 03
10003 nvidia 14-may-03

Self Join :-

Joining a table to itself is called Self Join.


 Self Join is performed when tables having self refrential integrity.
 To perform Self Join same table must be listed twice with different alias.
 Self Join is Equi Join within the table.
It is used to join a table to itself as if the table were two tables, temporarily renaming at
leastone table in the SQL statement.

Syntax :

(Here T1 and T2 refers same table)

SELECT <collist> From Table1 T1, Table1 T2 Where


T1.Column1=T2.Column2;

Example:
select s1.supplier_id ,s1.supplier_name ,s2.supplier_id from suppliers s1, suppliers s2 where
s1.supplier_id=s2.supplier_id ;
supplier_id supplier_name supplier_id
----------------- ------------------ ---------------

10000 ibm 10000


10001 hewlett 10001
packard
10002 microsoft 10002
10003 nvidia 10003
CROSS JOIN:

It returns the Cartesian product of the sets of records from the two or more joined tables. In
Cartesian product, each element of one set is combined with every element of another set to
formthe resultant elements of Cartesian product.
Sytax: SELECT * FROM <tablename1> CROSS JOIN <tablename2>

 CROSS JOIN returns cross product of two tables.


 Each record of one table is joined to each and every record of another table.
 If table1 contains 10 records and table2 contains 5 records then CROSS
JOIN betweentable1 and table2 returns 50 records.
 ORACLE performs CROSS JOIN when we submit query without JOIN COND.
Example: sql> SELECT * FROM suppliers CROSS JOIN orders;
supplier_id supplier_n order_id supplier_id order_dat

10000 ibm 500125 10000 12-may-03


10000 ibm 500126 10001 13-may-03
10000 ibm 500127 10003 14-may-03
10001 hewlett 500125 10000 12-may-03
10001 hewlett 500126 10001 13-may-03
10001 hewlett 500127 10003 14-may-03
10002 microsoft 500125 10000 12-may-03
10002 microsoft 500126 10001 13-may-03
10002 microsoft 500127 10003 14-may-03
10003 nvidia 500125 10000 12-may-03
10003 nvidia 500126 10001 13-may-03
NATURAL JOIN:
 NATURAL JOIN is possible in ANSI SQL/92 standard.
 NATURAL JOIN is similar to EQUI JOIN.
 NATURAL JOIN is performed only when common column name is same.
 In NATURAL JOIN no need to specify join condition explicitly , ORACLE
automatically performs join operation on the column with same name.
Syntax: SELECT <column list> FROM table1 NATURAL JOIN table2;

Example: ( Sailors table)

SELECT sid,sname,sid FROM sailors NATURAL JOIN reserves ; //both tables havesame
column name.

SID SNAME SID


---------- ---------- ----------

22 DUSTIN 22
22 DUSTIN 22
22 DUSTIN 22
22 DUSTIN 22
31 LUBBER 31
31 LUBBER 31
31 LUBBER 31
64 HORTIO 64
64 HORTIO 64
74 HORTIO 74

24)What are the advantages of views? List out the constraints for defining updateable and non-
updateable views

ANS) Advantages Of View: -

Security: - Each user can be given permission to access only a set of views that contain specific data.
Query simplicity: - A view can draw from several different tables and present it as a single tableturning
multiple table queries into single table queries against the view.
Data Integrity: - If data is accessed and entered through a view, the DBMS can automatically check the
data to ensure that it meets specified integrity constraints.
25)Discuss about updates on views. What is the need to restrict view updates

Ans) Updating record through view :-

Updating a View:

A view can be updated under certain conditions:


 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view in order
forthe INSERT query to function.

So if a view satisfies all the above-mentioned rules then you can update a view.

EX: SQL>UPDATE emp_v SET sal=2000 WHERE empno=1;

26)Explain about the complex views and how they are implemented in SQL? Ans) Complex Views: -

A view is said to complex view


If it based on more than one table
Query contains
AGGREGATE
functions DISTINCT
clause GROUP BY
clause HAVING
clause Sub-queries
Constants
Strings or Values Expressions
UNION, INTERSECT, MINUS operators.

Example 1 :-
SQL>CREATE VIEW V3 AS
SELECT
E.empno,E.ename,E.sal,D.dname,D.loc FROM
emp E JOIN dept D USING(deptno) ;

NON- UPDATABLE VIEWS:


we cannot perform insert or update or delete operations on base table through complex
views. Complex views are not updatable views.
Example 2 :-

SQL>CREATE VIEW V2 AS
SELECT deptno,SUM(sal) AS sumsal
FROM EMP
GROUP BY deptno;

Destroying a View: -
The DROP VIEW command is used to destroy a view from the database.
Syntax: -

DROP VIEW<viewName>
Example: -

SQL>DROP VIEW emp_v;


DIFFERENCES BETWEEN SIMPLE AND COMPLEX
COMPLEX VIEWS:SIMPLE
Created from one table Created from one or more tables

Does not contain functions Conations functions

Does not contain groups of data Contain groups of data

27)Write SQL queries using union, union all, intersect, minus and explain?
. ANS) same as 28th question
28)Explain about Relational Set operators with some examples?

ANS) SQL set operators allows combine results from two or more SELECT statements. At first
sight this looks similar to SQL joins although there is a big difference. SQL joins tends to
combine columns i.e. with each additionally joined table it is possible to select more and more
columns. SQL set operators on the other
hand combine rows from different queries with strong preconditions.
 Retrieve the same number of columns and
 The data types of corresponding columns in each involved SELECT must be
compatible(either the same or with possibility implicitly convert to the data types of
the first SELECT statement).

Set operator types

According to SQL Standard there are following Set operator types:

 UNION ---returns all rows selected by either query. To return all rows from
multipletables and eliminates any duplicate rows.
 UNION ALL-- returns all rows from multiple tables including duplicates.
 INTERSECT – returns all rows common to multiple queries.
 MINUS—returns rows from the first query that are not present in second query.

Note: Whenever these operators used select statement must have

- Equal no. of columns.


- Similar data type columns.
SYNTAX:

SELECT statement 1

UNION / UNION ALL / INTERSECT / MINUS


SELECT statement 2
; Rules :-

1 No of columns returned by first query must be equal


to no of columns returned by second query
2 Corresponding columns datatype type must be same.
1. UNION

 UNION operator combines data returned by two SELECT statement.


 Eliminates duplicates.
 Sorts result.
 This will combine the records of multiple tables having the same structure.

Example :-

1 SQL>SELECT job FROM emp WHERE deptno=10

UNION
SELECT job FROM emp WHERE deptno=20 ;

2 SQL>SELECT job,sal FROM emp WHERE deptno=10


UNION
SELECT job,sal FROM emp
WHERE deptno=20 ORDER BY
sal ; NOTE:- ORDER BY clause
must be used with last query.

3 SQL> select * from student1 union select * from


student2;
2. UNION ALL

This will combine the records of multiple tables


having the same structurebut including
duplicates. IT is similar to UNION but it includes
duplicates.

Example :-

SQL>SELECT job FROM


emp WHERE
deptno=10 UNION
ALL

SELECT job FROM emp WHERE deptno=20 ;

SQL> select * from student1 union all select * from student2;

3. INTERSECT

This will give the common records of multiple tables having the
samestructure.

INTERSECT operator returns common values from the result of two SELECT
statements.

Example:-

Display common jobs belongs to 10th and 20th departments ?


EX 1: SQL>SELECT job FROM
emp WHERE
deptno=10
INTERSECT

SELECT job FROM emp WHERE deptno=20;

EX2: SQL> select * from student1 intersect select


* from student2;

4. MINUS

This will give the records of a table whose records are not in
other tableshaving the same structure.
MINUS operator returns values present in the result of first SELECT
statement and not presentin the result of second SELECT statement.

Example:-

Display jobs in 10th dept and not in 20th dept ?

EX1: SQL>SELECT job FROM


emp WHERE
deptno=10 MINUS

SELECT job FROM emp WHERE deptno=20;

Ex2: SQL> select * from student1 minus select * from student2;

You might also like