Unit 3 - Interactive SQL & Advanced SQL (1) (1)949
Unit 3 - Interactive SQL & Advanced SQL (1) (1)949
• 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;
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.
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
• 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;
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
Table : Orders
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
Table : Employees
Example :
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Result :
Table : Orders
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
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 :
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 :
• 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;
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;
• 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.