0% found this document useful (0 votes)
2 views84 pages

Unit 3 - Interactive SQL & Advanced SQL (1) (1)949

The document provides an overview of various built-in SQL functions, including string, arithmetic, aggregate, date & time functions, as well as clauses like GROUP BY, HAVING, and ORDER BY. It details the syntax and examples for each function, explaining their usage in manipulating and querying data. Additionally, it covers different types of SQL joins and their applications in combining data from multiple tables.

Uploaded by

Tanishq Jagtap
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views84 pages

Unit 3 - Interactive SQL & Advanced SQL (1) (1)949

The document provides an overview of various built-in SQL functions, including string, arithmetic, aggregate, date & time functions, as well as clauses like GROUP BY, HAVING, and ORDER BY. It details the syntax and examples for each function, explaining their usage in manipulating and querying data. Additionally, it covers different types of SQL joins and their applications in combining data from multiple tables.

Uploaded by

Tanishq Jagtap
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 84

Inbuilt functions :

• Function that is built into an application and can be accessed by end users
are called as built in functions.
• SQL has many built in function performing processing on strings or
numeric data
• Built-In functions are used in SQL SELECT expressions to calculate values
and manipulate data.
String Functions :
1. CHAR_LENGTH(str) :
Returns the length of the string str measured in characters. A multi-byte character
counts as a single character. This means that for a string containing five two-byte
characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.
Syntax : SQL> SELECT CHAR_LENGTH(“str");
Example : CHAR_LENGTH("text")
Output : 4

CHARACTER_LENGTH(str)
CHARACTER_LENGTH() is a synonym for CHAR_LENGTH().
2. LENGTH(str) :
Returns the length of the string str, measured in bytes. A multi-byte
character counts as multiple bytes. This means that for a string
containing five two-byte characters, LENGTH() returns 10, whereas
CHAR_LENGTH() returns 5.
Syntax : SQL> SELECT LENGTH(‘str');
Example :
LENGTH('text‘); Output :
4
3. LOWER(str) :
Returns the string str with all characters changed to lowercase.
Syntax : select lower (‘str’);
Example : select lower
(‘College’); Output : college
LCASE(str) :
LCASE() is a synonym for LOWER().

4. UPPER(str) :
Returns the string str with all characters changed to uppercase.
Syntax : select upper (‘str’);
Example : select upper
(‘College’); Output : COLLEGE
UCASE(str)
UCASE() is a synonym for UPPER().
5. Initcap (‘string’) :
It is used to convert first letter of each word in capital letter
Syntax: Select initcap('string');
Example : select initcap('welcome to
college'); Output : Welcome To College
To display column :
Select initcap(name) from Student

6. CONCAT(str1,str2,...) :
Returns the string that results from concatenating the arguments. May have one or
more arguments.
Syntax : select concat(str1,str2,...);
Example : select concat(‘SQL’,
‘Server’); Output : SQLServer
Left() :
Extracts a number of characters from a string (starting from left)
Syntax :
Select left(‘string’, length) from table_name;
Example
Extract 3 characters from a string (starting from l-eft):
SELECT LEFT('SQL Server', 3) from
dual; Output :
SQL
Right() :
Extracts a number of characters from a string (starting from right)
Syntax :
Select right(‘string’, length) from table_name;
Example
Extract 3 characters from a string (starting from right):
SELECT RIGHT('SQL Server', 3) AS ExtractString from dual
Output :
ver
Concat() :
Adds two or more strings together.
Syntax:
select concat(‘str1’, ‘str2’) from table_name;
Example
Add two strings together:
SELECT CONCAT(‘SQL', ‘Database') from dual;
Output :
SQLDatabase
LPAD() :
Returns string1 left padded to length n with the character specified in string2.
Syntax :
Select lpad(‘str1’, n, ‘str2’) from table_name;
Example :
Select lpad(‘database’, 10, ‘*’);
Output :
**database
RPAD() :
Returns string1 right padded to length n with the character specified in string2.
Syntax :
Select rpad(‘str1’, n, ‘str2’) from table_name;
Example :
Select rpad(‘database’, 10, ‘*’);
Output :
Database**
LTRIM() :
It removes characters from the left (beginning) of the string.
Syntax :
Select ltrim(‘str1’, ‘str2’) from table_name;
Example :
Select ltrim(‘Welcome’, ‘W’) from dual;
Output :
elcome
RTRIM() :
It removes characters from the right of the string.
Syntax :
Select rtrim(‘str1’, ‘str2’) from table_name;
Example :
Select rtrim(‘Welcome’, ‘come’) from dual;
Output :
wel
TRIM() :
Removes all spaces from string (beginning and trailing spaces)
Syntax :
Select trim(‘string’) from table_name;
Example :
Select trim(‘ Welcome ‘) from dual;
Output :
Welcome
Replace() :
Replaces all occurrences of a substring within a string, with a new substring.
Replace function performs case sensitive match when searching for the specified
substring.
Syntax :
Select replace(‘string’, ‘Substring’, ‘new_string’) from table_name;
Example :
Select replace(‘welcome’, ‘wel’, ‘WEL’) from dual;
Output :
WELcome
Reverse() :
Reverses a string and returns the result.
Syntax :
Select reverse(‘string’) from table_name;
Example :
Reverse a string:
SELECT REVERSE('SQL Server’) from dual;
Output :
revreS LQS
Substr() :
Extracts some characters from a string.
Syntax :
SELECT SUBSTRING(string', position, no_of_characters) AS ExtractString from dual;
Example :
Extract 3 characters from a string, starting in position 1:
SELECT SUBSTRING('SQL Server', 1, 3) AS ExtractString from dual;
Output :
SQL
Arithmetic Functions :
• Mathematical function execute a mathematical operation usually based on input value.
• It returns numeric value as the result of the operation.
• Mathematical functions operates on numeric data such as decimal, integer, float,
real, smallint, and tinyint.

ABS() :
IT returns the absolute value of a number passed as an argument
Syntax :
Select ABS(value) from table_name;
Example :
Select ABS(-15) from dual;
Output :
15
POWER() :
This SQL POWER() function returns the value of a number raised to another,
where both of the numbers are passed as arguments.
Syntax :
Select POWER(m, n);
It is used to find the nth power of the number m.
Example :
Select POWER(5,3) from dual;
Output :
125
ROUND(X) :
This function returns the value of X rounded up the number upto nth digits.
Syntax :
Select ROUND(number, n);
Example :
Select ROUND(100.25638,2) from dual;
Output :
100.26
SQRT(X) :
This function returns the square root of X.
Syntax :
Select sqrt(number);
Example :
Select sqrt(25) from dual;
Output :
5
MOD(X,Y) :
The variable X is divided by Y and their remainder is returned.
Syntax :
Select MOD(X, Y);
Example :
Select MOD(9,2) from dual;
Output :
1
Greatest (num1, num2, num3……) :
This function returns greatest value in a list of values or expressions.
Syntax :
Select Greatest(num1, num2, num3……);
Example :
Select Greatest(8,15, 19,7,9);
Output :
19
Least (num1, num2, num3……) :
This function returns smallest value in a list of values or expressions.
Syntax :
Select Least(num1, num2, num3……);
Example :
Select Least(8,15, 19,7,9);
Output :
8
CEIL() :
This SQL CEIL() will rounded up any positive or negative decimal value within
the function upwards
Syntax :
Select ceil(expression);
An expression which is a numeric value or numeric data type.The bit data
type is not allowed.
Example :
Select CEIL(17.36) from dual;
Output :
18
FLOOR() :
This SQL CEIL() will rounded up any positive or negative decimal down to the
next least integer value.
Syntax :
Select floor(expression);
An expression which is a numeric value or numeric data type. The bit data
type is not allowed.
Example :
Select floor(17.36) from dual;
Output :
17
Aggregate Functions :
An aggregate function allows you to perform a calculation on a set of values
to return a single scalar value. We often use aggregate functions with the
GROUP BY and HAVING clauses of the SELECT statement.

COUNT() :
The COUNT() function returns the number of rows that matches a specified
criterion.
Syntax :
SELECT COUNT(column_name)
FROM table_name WHERE condition;
Example :
Get the no of rows in the department D1
Select count(name) From employee Where dept_id = ‘D1’;
COUNT(*) :
The COUNT(*) function returns a number of rows in a specified table or view that
includes the number of duplicates and NULL values.
Syntax :
Select count(*) from
table_name; Example :
Select count(*) from employee;

To return the number of rows that excludes the number of duplicates


and NULL values, you use the following form of the COUNT() function:
Count (distinct column_name);
SUM() :
calculates the sum of values.
The SUM() function returns the total sum of a numeric column.
Syntax :
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example :
Find the total of marks for all students
: Select SUM(marks)
From student;
AVG() :
The AVG() function returns the average value of a numeric column.
Syntax :
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example :
Find the average of marks for students.
: Select AVG(marks)
From students;
MAX() :
MAX() function is used to find the maximum value in a column.
Syntax :
Select MAX(DISTINCT or ALL expression)
From table_name;
Example :
Select max(marks)
From student;
MIN() :
MIN() function is used to find the minimum value in a column.
Syntax :
Select MIN(DISTINCT or ALL expression)
From table_name;
Example :
Select min(marks)
From student;
Date & time Functions :

SYSDATE() :
The most commonly used date function SYSDATE() returns the current
date and time in the format as MM-DD-YY
SYSDATE() used in conjunction with to_char().
Example :
to_char (SYSDATE, 'MM-DD-YYYY HH:MI:SS');

This Oracle date function returns a string containing not only the current
date, but also the current time down to the second.
CURRENT_DATE() :
Return the current date and time in the session time zone.
Syntax : Example :
SELECT CURRENT_DATE FROM dual;
Output :
25-AUG-2020 08:43:44
CURRENT_TIMESTAMP() :
Return the current date and time with time zone in the session time zone.

SELECT CURRENT_TIMESTAMP FROM dual;

25-AUG-17 08.26.52.742000000 AM -07:00


months_between (l,e) :
This date function returns the months between two dates.
Syntax :
Select months_between(date1, date2);
Example :

Months_between() function returns


the fraction of a month. You could
use trunc or round to make the
results more readable.
add_months (d,n) :
The add_months Oracle date function gives the same day, n number of months away.
The n can be positive or negative.
Syntax :
Select sysdate, add_months(sysdate, 1);
Example :
last_day (d) :
The last_day() function returns the last day of the month of the date d.
If you want to find the first day of the next month, simply add one to
the last_day results.
Syntax :
Select sysdate, last_day(sysdate);
Example :
next_day (d, day_of_week) :
The next_day Oracle date function returns the date of the day_of_week after
date d. day_of_week can be the full name or abbreviation.
Syntax :
Select sysdate, next_day(sysdate, ‘Monday’);
Example :
Group by Clause :
• The GROUP BY clause is a SQL command that is used to group rows that have
the same values.
• The GROUP BY clause is used in the SELECT statement . Optionally it is used
in conjunction with aggregate functions to produce summary reports from
the database.
• It does, summarizing data from the database.
• The queries that contain the GROUP BY clause are called grouped queries
and only return a single row for every grouped item.
Syntax :
SELECT statements...
GROUP BY column_name1[,column_name2,...] [HAVING condition];
Here,
• "SELECT statements..." is the standard SQL SELECT command query.
• "GROUP BY column_name1" is the clause that performs the grouping based
on column_name1.
• "[,column_name2,...]" is optional; represents other column names when the
grouping is done on more than one column.
• "[HAVING condition]" is optional; it is used to restrict the rows affected by the
GROUP BY clause. It is similar to the WHERE clause.
Example :
• Consider the table employee having attributes as
: emp_id, name, designation, salary,
dept_no
Select dept_no, sum(sal) from employee group by dept_no;

Select emp_id, name from employee group by dept_no;


Having Clause :
• The HAVING clause was added to SQL because the WHERE keyword could
not be used with aggregate functions.
• We can use HAVING clause to place conditions to decide which group will be
the part of final result-set.
• The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.
Syntax :
consider a customer table:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Example :
SELECT COUNT(CustomerID),
City FROM Customers
GROUP BY City
HAVING COUNT(CustomerID) > 5;
ORDER BY Keyword :
The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
The ORDER BY keyword sorts the records in ascending order by default.
To sort the records in descending order, use the DESC keyword.

Syntax :
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Example :
SELECT * FROM
Customers ORDER BY City;
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table,
sorted DESCENDING by the "City" column:
SELECT * FROM
Customers ORDER BY City
DESC;
Join :
• A SQL Join statement is used to combine data or rows from two or more
tables based on a common field between them.
• It is used for combining column from two or more tables by using
values common to both tables.
• JOIN Keyword is used in SQL queries for joining two or more tables.
• Minimum required condition for joining table, is (n-1) where n, is number of
tables. A table can also join to itself, which is known as, Self Join.
• Different types of Joins are:
o INNER JOIN
o LEFT JOIN
o RIGHT JOIN
o FULL JOIN
o SELF JOIN
Table 1 − Order Table
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

Table 2 - Customers table

CustomerI CustomerName ContactName Country


D
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Ana Trujillo Mexico
Emparedados y
helados
3 Antonio Moreno Antonio Moreno Mexico
Taquería

• The "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers"
table. The relationship between the two tables above is the "CustomerID" column.
INNER JOIN:
Returns records that have matching values in both tables
Syntax :
Select column_list from table_name 1
inner join table_name 2
on table_name 1.column_name = table_name.column_name

Example :
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

The same query can be written as :


SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders, Customers
Where Orders.CustomerID = Customers.CustomerID;
• The result will be :

OrderID CustomerName OrderDate


10308 Ana Trujillo Emparedados y helados 9/18/1996
10365 Antonio Moreno Taquería 11/27/199
6
10383 Around the Horn 12/16/199
6
10355 Around the Horn 11/15/199
6
10278 Berglunds snabbköp 8/12/1996
JOIN Three Tables :
Syntax :
Select column_list
from ((table_name 1
inner join table_name 2
on table_name 1.column_name = table_name.column_name )
Inner join table_name 3
on table_name 1.column_name = table_name 3.column_name)

Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
Outer join:
• Outer join is based on the tribe in both matched and unmatched data.
• An outer join is an extended form of the ordinary (inner) join.
• Outer join has three different type :
o Left outer join
o Right outer join
o Full outer join
LEFT (OUTER) JOIN:
• Returns all records from the left table, and the matched records from the
right table
• The result is NULL from the right side, if there is no match.
Table : Customers

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222
3 Antonio Antonio Mataderos México 05023 Mexico
Moreno Moreno 2312 D.F.
Taquerí
a

Table : Orders

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Syntax :
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Example :
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Result :

CustomerName OrderID
Alfreds Futterkiste null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Around the Horn 10355
Around the Horn 10383
B's Beverages 10289
Berglunds snabbköp 10278
Berglunds snabbköp 10280
Berglunds snabbköp 10384
Blauer See Delikatessen null
RIGHT (OUTER) JOIN:
• Returns all records from the right table, and the matched records from
the left table
• The result is NULL from the left side, when there is no match.
Table : Orders

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

Table : Employees

EmployeeID LastName FirstName BirthDate Photo


1 Davolio Nancy 12/8/1968 EmpID1.pic
2 Fuller Andrew 2/19/1952 EmpID2.pic
3 Leverling Janet 8/30/1963 EmpID3.pic
Syntax :
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Example :
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Result :

OrderID LastName FirstName


null West Adam
10248 Buchanan Steven
10249 Suyama Michael
10250 Peacock Margaret
10251 Leverling Janet
10252 Peacock Margaret
10253 Leverling Janet
FULL (OUTER) JOIN:
• Returns all records when there is a match in either left or right table
• FULL OUTER JOIN can return very large result-sets
Table : Customers

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222
3 Antonio Antonio Mataderos México 05023 Mexico
Moreno Moreno 2312 D.F.
Taquerí
a

Table : Orders

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Syntax :
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Example :
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Result :
• The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, if there are rows in "Customers"
that do not have matches in "Orders", or if there are rows in "Orders" that do
not have matches in "Customers", those rows will be listed as well.

CustomerName OrderID
Alfreds Futterkiste Null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Self JOIN
A self JOIN is a regular join, but the table is joined with itself.

Table : Customers

CustomerID CustomerName ContactName Address City PostalCode Country


1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222
3 Antonio Antonio Mataderos México 05023 Mexico
Moreno Moreno 2312 D.F.
Taquería
Syntax :
SELECT column_name(s)
FROM table1 T1, table1
T2 WHERE condition;

• T1 and T2 are different table aliases for the same table.

Example :
SELECT A.CustomerName AS
CustomerName1, B.CustomerName AS
CustomerName2, A.City FROM Customers A,
Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City =
B.City ORDER BY
A.City;
Result :

CustomerName1 CustomerName2 City


Drachenblut Delikatessend Drachenblut Delikatessend Aachen
Rattlesnake Canyon Grocery Rattlesnake Canyon Grocery Albuquerque
Old World Delicatessen Old World Delicatessen Anchorage
Galería del gastrónomo Galería del gastrónomo Barcelona
LILA-Supermercado LILA-Supermercado Barquisimeto
Magazzini Alimentari Riuniti Magazzini Alimentari Riuniti Bergamo
Alfreds Futterkiste Alfreds Futterkiste Berlin
Chop-suey Chinese Chop-suey Chinese Bern
Save-a-lot Markets Save-a-lot Markets Boise
Subquery :
• A query within another query is called as subquery.
• A Subquery or Inner query or a Nested query are is a query within another SQL
query.
• 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.
• Subqueries must be enclosed within parentheses.
• Subqueries are on the right side of the comparison operator.
• ORDER BY command cannot be used in a Subquery. GROUPBY command can be
used to perform same function as ORDER BY command.
• Use single-row operators with singlerow Subqueries. Use multiple-row
operators with multiple-row Subqueries.
Syntax :
Select column_list from table_name
WHERE column_name expression operator ( SELECT COLUMN_NAME from
TABLE_NAME WHERE ... );

Example :
Consider table stud_details

PHONE_NUM
NAME ROLL_NO LOCATION
BER
Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi 105 Kanchipuram 8989856868
Table STUDENT :

NAME ROLL_NO SECTION


Ravi 104 A
Sumathi 105 B
Raj 102 A

• To display NAME, LOCATION, PHONE_NUMBER of the students


from DATABASE table whose section is A
Select NAME, LOCATION, PHONE_NUMBER
from Stud_details
WHERE ROLL_NO IN (SELECT ROLL_NO from STUDENT where SECTION=’A’);
VIEWS :
• Views in SQL are kind of virtual tables.
• A view also has rows and columns as they are in a real table in the database.
• We can create a view by selecting fields from one or more tables present in the
database.
• A View can either have all the rows of a table or specific rows based on
certain condition.
• A view is actually a composition of a table in the form of a predefined
SQL query.
• A view can be created from one or many tables which depends on the
written SQL query to create a view.
CREATE VIEW :
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select
rows
• Creating View from a single table :
In this example we will create a View named DetailsView from the table
StudentDetails.
Query:
CREATE VIEW DetailsView
AS SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;

• To see the data in the View, we can query the view in the same manner as we
query a table.
SELECT * FROM DetailsView;
CREATE VIEW StudentNames
AS SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;

If we now query the view as,


SELECT * FROM
StudentNames;

Output:
Creating View from multiple tables:
• Create a View named MarksView from two tables StudentDetails and StudentMarks.
• To create a View from multiple tables we can simply include multiple tables in the
SELECT statement.
• Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

• To display data of View MarksView:


SELECT * FROM MarksView;
• Output:
DELETING VIEWS :
• If a created View is not needed any more then we can delete the view.
Obviously we will want to delete it.
• SQL allows us to delete an existing View.
• We can delete or drop a View using the DROP statement.
• Syntax:
DROP VIEW view_name;
• Example :
DROP VIEW MarksView;
UPDATING VIEWS :
There are certain conditions needed to be satisfied to update a view. If any one of
these conditions is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created
using multiple tables then we will not be allowed to update the view.
• We can use the CREATE OR REPLACE VIEW statement to add or remove fields from
a view.
• Syntax :
CREATE OR REPLACE VIEW view_name
AS SELECT column1,coulmn2,.. .
FROM table_name
WHERE condition;

• For example, if we want to update the view MarksView and add the field AGE to
this View from StudentMarks Table, we can do this as :
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME,
StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
• we retrieve all the data from MarksView
as: SELECT * FROM MarksView;
Output :
Uses of a View :
A good database should contain views due to the given reasons:
• Restricting data access –
Views provide an additional level of table security by restricting access to a
predetermined set of rows and columns of a table.
• Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
• Simplify commands for the user –
Views allows the user to select information from multiple tables without requiring
the users to actually know how to perform a join.
• Store complex queries –
Views can be used to store complex queries.
• Rename Columns –
Views can also be used to rename the columns without affecting the base
tables provided the number of columns in view must match the number
of columns specified in select statement. Thus, renaming helps to to hide
the names of the columns of the base tables.
• Multiple view facility –
Different views can be created on the same table for different users.

You might also like