Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DBMS - Unit Iv

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

UNIT - IV

Introduction:

 SQL (Structured Query Language) is a language that provides an interface to relational database
systems.

 SQL was developed by IBM in 1970s for use in System R.  SQL is an ANSI (American National
Standards Institute) standard

 SQL is used to perform all type of data operations in RDBMS.

Features of SQL:

 SQL can be easily used by a range of users with little or no knowledge of programming.
 It is a non-procedural language
 It reduces the amount of time required for modifying SQL statements.
 It is an English like language and easy to understand.

Table:
The data in an RDBMS is stored in database objects which are called as tables. This table is basically a
collection of related data entries and it consists of numerous columns and rows. Remember a table is the
most common and simplest form of data storage in a relational database. The following program is an
example of a CUSTOMERS table

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |

+ + + + + +
|1|Ramesh|32|Ahmedabad|2000.00|

|2|Khilan|25|Delhi|1500.00|
|3| kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|

+ + + + + +

Field or Column:
Every table is broken up into smaller entities called fields(also called as attributes).A field is a column in
a table that is designed to maintain specific information about every record in the table. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.

Record or a Row:
A record is also called as a row of data is each individual entry that exists in a table. For example, there
are 7 records in the above CUSTOMERS table.
SQL Commands
• SQL commands are instructions used to communicate with the database to perform specific task that
work with data.
• SQL commands can be used not only for searching the database but also to perform various other
functions like, for example, you can create tables, add data to tables, or modify data, drop the table,
set permissions for users.
• SQL commands are grouped into four major categories depending on their functionality:

1. Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and
dropping the structure of database tables. The commands are CREATE, ALTER, DROP, RENAME, and
TRUNCATE.

2. Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.

3. Transaction Control Language (TCL) - These SQL commands are used for managing changes
affecting the data. These commands are COMMIT, and ROLLBACK.

4. Data Control Language (DCL) - These SQL commands are used for providing security to database
objects. These commands are GRANT and REVOKE.

Data Definition Language (DDL)- These SQL commands are used for creating, modifying and dropping
the structure of database tables. The commands are:
CREATE, ALTER, DROP, RENAME, and TRUNCATE.

1. Create Statement: This command is used for creating the structure of a table; Using this command
we specify the details like name of the column, datatype, size and constraints

Syntax:- Create table table-name(columnname1 datatype(size) constraint, columname2 datatype(size), ..);


Eg: Question: Create a table with the following fields
EMPLOYEES (Employee_Id, First_Name, Last_Name, Email, Phone_Number, Hire_Date, Job_Id, Salary,
Commission_Pct, Manager_Id, Department_Id)

Ans:- Create table EMPLOYEES(Employee_Id number(4) primary key , First_Name varchar2(20) not null,
Last_Name varchar2(20) not null, Email varchar2(40) unique, Phone_Number number(10), Hire_Date
date not null, Job varchar2(20) not null, Salary number(10,2) not null , Commission_Pct number(3),
Manager_Id number(4) references EMPLOYEES(Employee_Id), Department_Id number(2));

2. Alter statement: This command is used for changing the structure of a table.
• Using this command we can add a new constraint or a new column to table.
• We can also modify the datatype and size of the column.
• We can increase the size of a column but not decrease.

Syntax: Alter table table-name add/modify(column-name datatype(size));

Eg1: Adding a column to the table.


Question: Add a column called Grade which takes only “A” or “B” or “C”
Ans: - SQL> alter table faculty add(grade varchar2(1),check(grade in('A','B','C'))); Eg2:
Modifying the size of a column in the table.
Question: Increase the size of the column fname from 10 to 20 Ans:- SQL>
alter table faculty modify(fname varchar2(20));

3. Drop statement: This command is used for deleting the table structure permanently from the
database. When this command is used the data present in the table and the structure of table is
deleted permanently from the database.
Syntax: drop table table-name;
Eg:- delete table student from the database SQL> drop
table student;

4. Rename Statement: This command is used for changing the name of a table.

Syntax: Rename tablename to newtablename; Eg:-


Change the name of table student to newstudent Ans:-
SQL> rename student to newstudent;

5. Truncate:

• This command is used for permanently deleting complete data present in the table.
• The structure of the table is retained.
Syntax: SQL>TRUNCATE TABLE table_name; Eg:-
Delete the data present in Student table. Ans:-
SQL>truncate table student;

Data Manipulation Language (DML)

• These SQL commands are used for storing, retrieving, modifying, and deleting data.
• These commands are INSERT, UPDATE, DELETE and SELECT.
• After using DML commands we need to use commit statement to save the changes
permanently in the table.

1. Insert:
• The SQL INSERT Statement is used to add a new row of data into a table in the database.

• There are two basic syntaxes of INSERT statement as follows:


Inserting data for required fields only
Syntax:-
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which you want to
insert data.

Inserting data into all the columns:


Syntax:-
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example: Inserting data for specified columns into customer table INSERT INTO
CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,'Ramesh',32,'Ahmedabad',2000.00);

We need not specify the column(s) name in the SQL query if we are adding values for all the columns of
the table.But make sure the order of the values is in the same order as the columns in the table.

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1,'Ramesh',32,'Ahmedabad',2000.00);

Example: Inserting data into customer table


INSERT INTO CUSTOMERS VALUES (2,'Khilan',25,'Delhi',1500.00);

2. Update:
• The update query is used to change/modify/insert the data of a table for existing records.

• The UPDATE statement allows you to update a single record or multiple records in a table.
Syntax: UPDATE table SET column = newvalue WHERE condition;

Example: update all supplier names in the suppliers table from IBM to HP.
SQL>UPDATE suppliers SET name = 'HP' WHERE name = 'IBM';

3. Delete:
• The SQL DELETE Query is used to delete the existing records from a table.
• You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would
be deleted.
Syntax: DELETE FROM table_name WHERE [condition];
Example1: delete all the records of employee table Ans:
Delete from employee;

Example2: delete only specified records.


Delete the employee whose salary is greater than 2000. Ans:
Delete from emp where sal>2000;

4. Select Statement
• SQL SELECT statement is used to fetch the data from a database table which returns data in the form
of result table.

• These result tables are called result-sets.

• A query may retrieve information from specified columns or from all of the columns in the table.
Syntax of SQL SELECT Statement - global selection)
SELECT column_list FROM table_name
[WHERE Clause]
[GROUP BY clause]

[HAVING clause]
[ORDER BY clause];

• table-name is the name of the table from which the information is retrieved.

• column_list includes one or more columns from which data is retrieved.

• The code within the brackets is optional.


• FROM table-name clause of select statement is used for specifying the source tables from which data
need to be retrieved.

• [WHERE Clause] is used for filtering the data according to the given criteria

• [GROUP BY clause] is used for grouping the data according to the given column
• [HAVING clause] is used to apply filter on the rows obtained after group by clause.
• [ORDER BY clause] is used to sort the data in ascending or descending order according to the given
column.

• The different forms of select query:

1. Select Specified columns and all rows:


Q: display the employ number, ename and department of employee table Ans:
SQL> select empid, ename, dept from employee;

2. Select all columns and specified rows:


Q: display the details of employees whose salary is greater than 20000 Ans:
SQL> select * from employee where salary > 20000

3. Select Specified columns and specified rows: Q: display employee id and name whose dept is
“sales”
Ans: SQL> select empid,ename from employee where dept = „sales‟;

4. Select all columns and all rows:


Q: display all the records of employee table Ans:
SQL> select * from employee;

Example1: Display the names of employees who salary is more than 4000.
SQL>select ename from emp where sal>4000;

Example 3: Display employee details for employee in ascending order of their salary.
SQL> select * from emp where empid = 10;

Transaction Control Language (TCL)

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used while creating tables or
dropping them.

Here are some commands that come under TCL:

o
COMMIT o

ROLLBACK o

SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.

Syntax:

1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.
Syntax:

1. SAVEPOINT SAVEPOINT_NAME;

Data Control Language (DCL )

Data Control Language(DCL) is used to control privilege in Database. To perform any operation in the
database, such as for creating tables, sequences or views we need privileges. DCL commands are used
to enforce database security in a multiple database environment. Database Administrator's or owners of
the database object can provide/remove privileges on a database object.
DCL defines two commands,

• Grant: Gives user access privileges to database.

• Revoke: Take back permissions from user.

GRANT command:
SQL Grant command is used to provide access on the database objects to the users. The syntax
for the GRANT command is:
GRANT privilege_name ON object_name TO user_name;
Here, privilege_name: is the access right or privilege granted to the user.
object_name: is the name of the database object like table, view etc. user_name: is the
name of the user to whom an access right is being granted.

Revoke Command
The revoke command removes user access rights or privileges to the database objects. The syntax
for the REVOKE command is:
REVOKE privilege_name ON object_name FROM User_name;
Example: (a) SQL>GRANT SELECT ON employee TO user1
This command grants a SELECT permission on employee table to user1.
(b) SQL>REVOKE SELECT ON employee FROM user1
This command will revoke a SELECT privilege on employee table from user1.

1. To Allow a User to create Table grant


create table to username;

2. To Grant permission to Drop any Table


Grant drop ant table to username

3. To take back Permissions Revoke create


table from username
Data Constraints:

• Constraints are the rules enforced on the data columns of a table.


• These are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the database.
• Constraints could be either on a column level or a table level. The column level constraints are applied
only to one column, whereas the table level constraints are applied to more than one column.

• Following are some of the most commonly used constraints available in SQL.

• Constraints can be specified when a table is created with the CREATE TABLE statement or you can
use the ALTER TABLE statement to create constraints even after the table is created.

NOT NULL Constraint –


NOT NULL constraint restricts a column from having a NULL value.
Once NOT NULL constraint is applied to a column, you cannot pass a null value to that column. It enforces
a column to contain a proper value.
One important point to note about NOT NULL constraint is that it cannot be defined at table level.
Example: NOT NULL constraint on student table

Create table student (rollnum number(6) NOT NULL, sname char(20),


age number(3));
The above query will declare that the rollnum field of Student table will not take NULL value.

UNIQUE Constraint –

• UNIQUE constraint ensures that a field or column will only have unique values i.e each value if different
from other values.

• A UNIQUE constraint field will not have duplicate data.

• UNIQUE constraint can be applied at column level or table level.

Example1: UNIQUE constraint when creating a Table (column level) SQL>CREATE table student
(Rollnum number(3) UNIQUE, Sname char(20), Age number(3));

The above query will declare that the rollnum field of Student table will only have unique
values and won‟t take NULL value.

Example2:UNIQUE constraint when creating a Table (Table Level)


SQL>CREATE table student (Rollnum number(3), Sname char(20), Age number(3),
UNIQUE(Rollnum));
Example3: UNIQUE constraint after Table is created (Column Level) SQL> ALTER
table student add UNIQUE(rollnum);
PRIMARY Key –

• Primary key constraint uniquely identifies each record in a database.

• A Primary Key must contain unique value and it must not contain null value.

• Usually Primary Key is used to index the data inside the table.

Example1: PRIMARY KEY constraint at column level


SQL>CREATE table student(rollnum number(3) PRIMARY KEY, sname char(20) NOT NULL, Age
number(3));
In the above query rollnum field should contain some value and it should not be repeated.

Example2:PRIMARY KEY constraint at Table Level


SQL> CREATE table student(rollnum number(3), sname char(20) NOT NULL, Age number(3),
PRIMARY KEY(ROLLNUM));

Example3:PRIMARY KEY constraint after table is created (Column Level) ALTER table
student add PRIMARY KEY(rollnum);
The above command will creates a PRIMARY KEY on the rollnum.

FOREIGN Key –

• A FOREIGN KEY is a key used to link two tables together.

• A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another
table.
• In simpler words, the foreign key is defined in a second table, but it refers to the primary key or a
unique key in the first table.
• The table containing the foreign key is called the child table or detail table, and the table containing
the primary key/candidate key is called parent table or master table.
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
• The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
• For example, a table called Customer_Detail has a primary key called c_id. Another table called
Order_ Details has a foreign key which references c_id in order to uniquely identify the relationship
between both tables.

Customer_Detail Table :

c_id Customer_Name address


101 Adam Noida

102 Alex Delhi

103 Stuart Rohtak

Order_Detail Table :

Order_id Order_Name c_id

10 Order1 101

11 Order2 103

12 Order3 102

In Customer_Detail table, c_id is the primary key which is set as foreign key in
Order_Detail table. The value that is entered in c_id which is set as foreign key in Order_Detail table
must be present in Customer_Detailtable where it is set as primary key. This prevents invalid data to
be inserted into c_id column of Order_Detailtable.

Example1: FOREIGN KEY constraint at Table Level:


SQL>CREATE table Order_Detail(order_id number(5) PRIMARY KEY, order_name varchar2(20)
NOT NULL, c_id number(4) REFERENCES Customer_Detail(c_id));

In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id column of
Customer_Detail.

Example2: FOREIGN KEY constraint at Column Level after creating the table

SQL> ALTER table Order_Detail add FOREIGN KEY(c_id) REFERENCES


Customer_Detail(c_id);

CHECK Constraint –
• The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn't entered the table.

• CHECK constraint is used to restrict the value of a column between a range.

• It is like condition checking before saving data into a column.


Example1: CHECK constraint at creating a table
SQL> CREATE table student(rollnum number(4) NOT NULL CHECK(rollnum > 0), sname char(20) NOT NULL,
Age Number(3));
The above query will restrict the s_id value to be greater than zero. Example2:
CHECK constraint at Column Level after creating the table SQL> ALTER table
student add CHECK(rollnum > 0);

Dropping Constraints

• Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP
CONSTRAINT option.
• For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following
command.

ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;

Some implementations may provide shortcuts for dropping certain constraints. For example, to
drop the primary key constraint for a table in Oracle, you can use the following command.

ALTER TABLE EMPLOYEES DROP PRIMARY KEY;

SQL Operators:

An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations. These Operators are used to
specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.

• Arithmetic operators

• Relational operators

• Logical operators

• Special operators

1. SQL Arithmetic Operators:


Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operator Description Example

Adds values on either side of the operator. a + b will


+ (Addition) give 30

Subtracts right hand operand from left hand operand. a - b will


- (Subtraction) give -10
* Multiplies values on either side of the operator. a * b will
give 200
(Multiplication)

Divides left hand operand by right hand operand. b / a will


/ (Division) give 2

Divides left hand operand by right hand operand and b % a will


% (Modulus) returns remainder. give 0

2. Relational Operators:

Operator Description Example

Checks if the values of two operands are equal or not, if yes (a = b) is


= then condition becomes true. not true.

Checks if the values of two operands are equal or not, if values (a != b) is


!=<> are not equal then condition becomes true. true.

Checks if the value of left operand is greater than the value of


right operand, if yes then condition becomes true. (a > b) is
> not true.

Checks if the value of left operand is less than the value of (a < b) is
< right operand, if yes then condition becomes true. true.

Checks if the value of left operand is greater than or equal to (a >= b) is


the value of right operand, if yes then condition becomes true. not true.
>=

Checks if the value of left operand is less than or equal to the


value of right operand, if yes then condition becomes true. (a <= b) is
<= true.

3. SQL Logical Operators:


Sr.No. Operator & Description

AND

1 The AND operator allows the existence of multiple conditions in an SQL


statement's WHERE clause.

OR

2 The OR operator is used to combine multiple conditions in an SQL statement's


WHERE clause.

NOT
The NOT operator reverses the meaning of the logical operator with which it
3 is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.

ANY

4 The ANY operator is used to compare a value to any applicable value in the
list as per the condition.

BETWEEN

The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.

6 EXISTS
The EXISTS operator is used to search for the presence of a row in a
specified table that meets a certain criterion.

IN
The IN operator is used to compare a value to a list of literal values that have
7
been specified.

LIKE
The LIKE operator is used to compare a value to similar values using
8
wildcard operators.

SQL Data Types


Data types are used to represent the nature of the data that can be stored in the database table. For example, in a particular
column of a table, if we want to store a string type of data then we will have to declare a string data type of this column.
Data types mainly classified into three categories for every database.

o String Data types o

Numeric Data types o Date

and time Data types

Oracle Data Types


Oracle String data types

CHAR(size) It is used to store character data within the predefined length. It can be stored up
to 2000 bytes.

NCHAR(size)
It is used to store national character data within the predefined length. It can be
stored up to 2000 bytes.

VARCHAR2(size) It is used to store variable string data within the predefined length. It can be

stored up to 4000 byte.

VARCHAR(SIZE)
It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size)

NVARCHAR2(size)

It is used to store Unicode string data within the predefined length. We have to
must specify the size of NVARCHAR2 data type. It can be stored up to 4000 bytes.
Oracle Numeric Data Types

NUMBER(p, s) It contains precision p and scale s. The precision p can range from 1 to 38, and the
scale s can range from -84 to 127.

FLOAT(p) It is a subtype of the NUMBER data type. The precision p can range from 1 to 126.

BINARY_FLOAT It is used for binary precision( 32-bit). It requires 5 bytes, including length byte.

BINARY_DOUBLE
It is used for double binary precision (64-bit). It requires 9 bytes, including length
byte.
Oracle Date and Time Data Types

DATE It is used to store a valid date-time format with a fixed length. Its range varies from
January 1, 4712 BC to December 31, 9999 AD.

TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
JOIN EXPRESSIONS :

1. Sql join is used to fetch data from two or more tables, which is joined to appear as single set of data.
2. It is used for combining column from two or more tables by using values common to both tables.

3. 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.

4. A table can also join to itself, which is known as, self join.

Types of join

Following are the types of join that we can use in sql:

inner

outer

left

right

3.7.1 INNER JOIN OR EQUI JOIN

This is a simple join in which the result is based on matched data as per the equality condition specified in the sql query.

inner join syntax is,

select column-name-list from table-name1 inner join table-name2 where table-name1.column-name = table-name2.columnname;
example of inner join consider a class table,
id name

1 abhi

2 adam

3 alex

4 anu
and the class_info table,

id address 1

delhi

2 mumbai

3 chennai

inner join query will be, select * from class inner join class_info where

class.id = class_info.id; the result set table will look like,

id name id address 1 abhi 1

delhi

2 adam 2 mumbai

3 alex 3 chennai
NATURAL JOIN

Natural Join is a type of Inner join which is based on column having same name and same datatype present in both the tables
to be joined.

The syntax for Natural Join is, SELECT *

FROM table-name1 NATURAL JOIN table-

name2;

Example of Natural JOIN

Here is the class table,


ID NAME

1 abhi

2 adam

3 alex

4 anu
and the class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Natural join query will be,

SELECT * from class NATURAL JOIN class_info;

The result set table will look like,

ID NAME Address

1 abhi DELHI

2 adam MUMBAI

3 alex CHENNAI

In the above example, both the tables being joined have ID column(same name and same datatype), hence the records for which value
of ID matches in both the tables will be the result of Natural Join of these two tables.

OUTER JOIN

Outer join is based on both matched and unmatched data. outer joins subdivide further into,

left outer join

right outer join


full outer join

LEFT OUTER JOIN

The left outer join returns a resultset table with the matched data from the two tables and then the remaining rows of the left table
and null from the right table's columns.

syntax for left outer join is,

select column-name-list from table-name1 left outer join table-name2 on table-name1.column-name = table-name2.column-name; to
specify a condition, we use the on keyword with outer join.
left outer join syntax for oracle is,

select column-name-list from table-name1, table-name2 on table-name1.column-name = table-name2.column-name(+); example


of left outer join here is the class table,

id name 1 abhi
2 adam
3 alex
4 anu
5 ashish

and the class_info table,

id address 1
delhi
2 mumbai
3 chennai
7 noida
8 panipat

left outer join query will be,

select * from class left outer join class_info on (class.id = class_info.id);

the resultset table will look like,

id name id address
1 abhi 1 delhi
2 adam 2 mumbai
3 alex 3 chennai
4 anu null null
5 ashish null null

RIGHT OUTER
JOIN

The right outer join returns a resultset table with the matched data from the two tables being joined, then the remaining rows of the
right table and null for the remaining left table's columns.

syntax for right outer join is,

select column-name-list from table-name1 right outer join table-name2 on table-name1.column-name = table-name2.column-name;

right outer join syntax for oracle is,


select column-name-list from table-name1, table-name2 on table-name1.column-name(+) = table-name2.column-name; Database
Systems

example of right outer join once again the class table,

id name 1 abhi
2 adam
3 alex
4 anu
5 ashish

and the class_info table,

id address 1
delhi
2 mumbai
3 chennai
7 noida
8 panipat

right outer join query will be,

select * from class right outer join class_info on (class.id = class_info.id);

the resultant table will look like,

id name id address
1 abhi 1 delhi
2 adam 2 mumbai
3 alex 3 chennai
7 null null noida
8 null null panipat

FULL OUTER JOIN

The full outer join returns a resultset table with the matched data of two table then remaining rows of both left table and then the
right table.

syntax of full outer join is,

select column-name-list from table-name1 full outer join table-name2 on table-name1.column-name = table-name2.column-name;

example of full outer join is, the class table,

id name 1
abhi
2 adam
3 alex
4 anu 5 ashish
and the class_info table,
id address 1 delhi
2 mumbai
3 chennai
7 noida
8 panipat
full outer join query will be like,
select * from class full outer join class_info on (class.id = class_info.id);

the resultset table will look like, Database Systems

Compiled by: Arun Kumar.M Ph.D AP/CS BCSM,TNJ-5 Page 70

id name id address 1
abhi 1 delhi
2 adam 2 mumbai
3 alex 3 chennai
4 anu null null 5 ashish null null null null 7 noida null null 8 panipat Built-In Functions

SQL has many built-in functions for performing the calculation of data. SQL provides built-in functions to perform the
operations. Some useful functions of SQL are performing the mathematical calculations, string concatenation and
substring etc.

SQL functions are divided into two parts:

1. Aggregate Functions
2. Scalar Functions

SQL Aggregate Functions


SQL Aggregate functions return a single value which is calculated from the values.

o AVG(): It returns the average value of the

column. o COUNT(): It returns the number of rows

in the table. o FIRST(): It returns the first value of the

column.

o LAST(): It returns the last value o MAX():

It returns the largest value of the column. o MIN():

It returns the smallest value of the column. o SUM():

It returns the sum of rows of the table.

SQL Scalar functions


SQL Scalar functions returns the single value according to the input value.

Scalar functions:
o UCASE(): It converts the database field to uppercase.

o LCASE(): It converts a field to lowercase.

o MID(): It extracts characters from the text field. o

LEN(): It returns the length of a text field.


o ROUND(): It rounds a numeric field to the number of
decimals.

o NOW(): It returns the current date and time. o

FORMAT(): It formats how a field is to be

displayed.

Aggregate Functions

The aggregate functions return a single value after performing calculations on the group of values. Some of Aggregate
functions are explained below.

AVG Function

AVG () returns the average value of the database after calculating the values in numeric column.

Syntax :

SELECT AVG(column_name) FROM table_name

Using AVG() function

Consider the following Emp table:

The following SQL calculates the average salary of

the employees.

SELECT avg(salary) from Emp; Result:

COUNT() Function
Count returns the number of rows which are present in the database, and either it is based on the condition or without
condition.
Its basic syntax is,

1. SELECT COUNT(column_name) FROM table-name

Using COUNT() function

Consider the following Emp table:

SQL query to count the number of rows that satisfies the condition.

1. SELECT COUNT(name) FROM Emp WHERE salary = 10000;

Output:

Example of COUNT (distinct)

Consider the following Emp table:

The SQL query is:

SELECT COUNT(DISTINCT salary) FROM emp;

Output:

FIRST() Function

The function returns the first value of the specified column.

Syntax:
SELECT FIRST(column_name) FROM table-name;

Using FIRST() function

Consider the following Emp table:

The SQL query will be:

SELECT FIRST(salary) FROM EMP;

Output:

LAST() Function

The LAST function returns the return last value of the selected column.

Syntax of the LAST function is:

SELECT LAST(column_name) FROM table-name;

Using LAST() function

Consider the following Emp table:

SQL Query is:

SELECT LAST(salary) FROM emp;

Output:
MAX() Function

MAX() function returns the maximum value from the selected column of the table.

Syntax:

1. SELECT MAX(column_name) from table-name;

Consider the following Emp table:

The following SQL query fetch the maximum salary.

SELECT MAX(salary) FROM emp;

Output:

MIN() Function
MIN function returns the minimum value of selected column.

The syntax of MIN function:

SELECT MIN(column_name) from table-name;

Using MIN () function

Consider the below Emp table:


SQL query to find the minimum salary:

1. SELECT MIN(salary) FROM emp; Output:

SUM() Function
SUM () function returns the total of the specified columns.

The syntax for SUM:

1. SELECT SUM (column_name) from table-name;

See the following Emp table

SELECT SUM(salary) FROM emp;

Output:

Scalar Functions
Scalar functions return a single value from an input value. Some of the Scalar functions are given below:

UCASE () Function

UCASE () converts the value of the string column into the Uppercase (Capital) characters.

Syntax

SELECT UCASE(column_name) from table-name;

Using UCASE() function

Consider the below Emp table:


SQL query of UCASE:

SELECT UCASE(name) FROM emp;

Result:

LCASE() Function
LCASE() function is used to convert the value of string columns to Lowercase.

The syntax for LCASE:

SELECT LCASE(column_name) FROM table-name;


Using LCASE() function

Consider the following Emp table

SQL query for converting the string value to Lowercase:

SELECT LCASE(name) FROM emp;

Output:
MID() Function
MID() function is used to extract substrings from column values in the table.

The syntax for the MID function is:

SELECT MID(column_name, start, length) from table-name;

Using MID() function

Consider the following Emp table:

The following SQL query returns the substring start from the second character.

SELECT MID(name,2,2) FROM emp;

Output:

ROUND() Function
The ROUND() function is used to round a numeric field to a number of the nearest integer. It is used for decimal point.

Syntax:

SELECT ROUND(column_name, decimals) from table-name;

Using ROUND() function

Consider the following Emp table:


The following SQL query rounds the amount of salary column.

SELECT ROUND(salary) from emp;

Output:

SQL ORDER BY CLAUSE


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some
databases sort the query results in an ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column
should be in the column-list.

Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY −
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | +----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending order by NAME.
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

You might also like