Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 30

Page- 59

UNIT- IV
SQL (Structured query Language)

Introduction
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.

 SQL is the standard language for Relational Database System. All the Relational
Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase,
Informix, Postgres and SQL Server use SQL as their standard database language. SQL
is an ANSI (American National Standards Institute) standard.

A Brief History of SQL

 1970 − Dr. Edgar F. "Ted" Codd’s of IBM is known as the father of relational
databases. He described a relational model for databases.

 1974 − Structured Query Language appeared.

 1978 − IBM worked to develop Codd's ideas and released a product named
System/R.

 1986 − IBM developed the first prototype of relational database and


standardized by ANSI. The first relational database was released by Relational
Software which later came to be known as Oracle.

DBMS vs RDBMS

DBMS RDBMS
1. DBMS application stores data as file. 1. RDBMS application stores data in the form
of table.
2. Normalization is not applicable for DBMS. 2. Normalization is applied in RDBMS.
3. DBMS does not provide any security regarding 3. RDBMS defines the integrity constraint for
data manipulation. the purpose of ACID.
4. It does not support distributed database. 4. It supports distributed database.
5. DBMS is designed to handle small amount of 5. RDBMS is designed to handle large
data as compared to RDBMS and supports amount of data and provide support to
only single user. multiple users.

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 60

Q) SQL Commands
SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.

SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, and set permission for users.

SQL Commands are mainly classified into four types, which are DDL command, DML
command, TCL command and DCL command.

SQL is mainly divided into four sub language


1. Data Definition Language(DDL)
2. Data Manipulation Language(DML)
3. Transaction Control Language(TCL)
4. Data Control Language(DCL)

You can easily remember all these SQL command like below;
DDL Commands: "dr. cat" d-drop, r-rename, c-create, a-alter, t-truncate.
DML Commands: "sudi" s-select, u-update, d-delete, i-insert.
TCL Commands: “crs” Commit, Rollback, Save point

1. DDL Commands
It is used to create and modify the structure of data (Tables) in database. DDL changes
the structure of the table like creating a table, deleting a table, altering a table, etc.

All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
Here are some commands that come under DDL:
1. CREATE:

This is used to create a new table in the user’s database.


i. Create index: creates an index for a table
ii. Create view: creates a dynamic subset of columns/row from one or more
tables.

2. ALTER:

This is used modify a tables definition.


3. DROP:

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 61

It is used to permanently delete a table.


i. Drop index: an index.
ii. Drop view: delete a view.

4. TRUNCATE:

It is used to delete a table for permanently.


5. RENAME:

It is used to rename the table as a old name to new name.

2. DML COMMANDS:

DML commands are used to modify the data in the database. It is responsible for all
form of changes in the database. The command of DML is not auto-committed that
means it can't permanently save all the changes in the database. They can be rollback.
Here are some commands that come under DML:
1. INSERT INTO:

It is used to insert new row(s) into a table.


2. SELECT:

This command is used to select the attributes from the rows in one or more
tables or views
3. UPDTE:

This command is used to modify values in one or more table rows.


4. DELETE:

This command is used to delete one or more rows in a table.

3. DCL COMMANDS:
DCL commands are used to grant and take back authority from any database user.
Here are some commands that come under DCL:
1. Grant:

This command is used to grant system permission to the users.


2. Revoke

This command is used to take back the permission from the users.

4. TCL (Transaction Control Language)COMMANDS

Transaction Control (TCL) statements are used to manage the changes made by DML
statements.
1. COMMIT:
To make the changes permanent in the database
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 62

2. SAVEPOINT:
Saving point in a transaction to which you can later roll back

3. ROLLBACK:
Restore database to original since the last COMMIT

Q). Data Definition Language (DDL):


It is used to create and modify the structure of data (Tables) in database. DDL changes
the structure of the table like creating a table, deleting a table, altering a table, etc.

All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
Here are some commands that come under DDL:
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME.
1. CREATE TABLE
The CREATE TABLE command is used to create a new table in the database.
Syntax: CREATE TABLE table_name(column_name1 data_type (size) constraint,
column_name2 data_type (size) constraints, );

Ex: create table student (sname varchar2(20) notnull, rollno number(10) not
null, dob date );

Here the student table has created that is.

sname rollno dob

2. ALTER TABLE

The ALTER TABLE statement is used to modify structure of an existing table. There are
three different syntaxes

a) ALTER TABLE ADD


This command is used to add a new column in to existing table syntax:

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 63

Syntax: ALTER TABLE table_name ADD(column_name data_type(size),


column_name data_type, ) ;
Ex: alter table student add(address varchar2(20), phone_no
number(10));
here the table has altered.
sname rollno dob address phone_no

b) ALTER TABLE MODIFY


This command is used to change the data type and size of an existing column in to an
existing table

Syntax: ALTER TABLE table_name MODIFY (old_column_name


new_data_type(new_size);

Ex: alter table student modify (address varchar2(40));


The table has altered.

c) ALTER TABLE DROP


To delete a column in a table, use the following syntax
Syntax: ALTER TABLE table_name DROP COLUMN column_name1,
;

Ex: alter table student drop phone_no;


The table altered.

sname rollno dob address

3. DROP:
This command is used to delete the structure of the table as well as records in the
relation.
Syntax : DROP TABLE table_name;
Ex: Drop table student;
The student table das dropped
4. RENAME
RENAME command is used to rename the table.
Syntax: Rename old_table_name to old_table_name;
EX: Rename student to student1;

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 64

2. TRUNCATE TABLE:
Truncate command will delete all the records permanently in a specified table but
structure of the table will not be deleted.

Syntax: TRUNCATE TABLE TableName;


EX: TRUNCATE TABLE student;
******************************************************************************

Q). DML COMMANDS:

DML commands are used to modify the database. It is responsible for all form of
changes in the database. The command of DML is not auto-committed that means it
can't permanently save all the changes in the database. They can be rollback.
Here are some commands that come under DML:
1. INSERT INTO
2. SELECT
3. UPDTE
4. DELETE
1. INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table. There are
different forms of insert commands are used to insert records into a table.

i) The first form of insert is used to insert values for all columns in a table.

Syntax: INSERT INTO table_name VALUES (value1,value2,value3,...);

EX: INSERT INTO STUDENT VALUES (101,’joel’,’surya’);

SNO SNAME COLLEGE


101 Joel surya

ii) The second form of insert is used to insert values for some columns of a record
in a table.
Syntax: INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...);

EX: INSERT INTO STUDENT (SNO, SNAME) VALUES (102 ,’Reema’);

SNO SNAME COLLEGE


101 Joel Surya
102 Reema
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 65

2. SELECT:
a) The select command is used to retrieve all records from the tables.

Syntax: SELECT * FROM table_name;


Ex: select * from student;

SNO SNAME COLLEGE


101 Joel Surya
102 Reema

b) The select command is used to retrieve some column by using where


condition
Syntax: SELECT set of fields FROM table_name [WHERE condition];
Ex: select sno, sname, college from student where college=’surya’;

SNO SNAME COLLEGE


101 Joel Surya

3. UPDATE:
The UPDATE Query is used to modify the existing records in a table. We can use
WHERE clause with UPDATE query to update selected rows otherwise all the
rows would be affected.
Syntax:
Syntax 1-
UPDATE Table_Name SET ColumnName1=Expression1,
ColumnName2=Expression2, .;

Syntax 2
UPDATE Table_Name SET ColumnName1=Expression1,
ColumnName2=Expression2, WHERE Condition;

Ex:1 UPDATE student SET total = sub1+sub2+sub3;


EX:2 UPDATE student SET total = sub1+sub2+sub3 WHERE sno = 10;

4. DELETE:
The SQL DELETE Query is used to delete the existing records from a table. We can
use WHERE clause with DELETE query to delete selected rows, otherwise all the
records would be deleted.

Syntax:
Syntax 1: DELETE FROM Table Name;
Example: DELETE from student;

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 66

Syntax 2: DELETE FROM Table Name WHERE Condition;


Example: DELETE from student WHERE address=’JRG’;

***********************************************************************************

Q). DCL COMMANDS:


DCL commands are used to grant and take back authority from any database user.
Here are some commands that come under DCL:
3. Grant
4. Revoke

1. Create users in the Database


Syntax: create user username identified by password;
EX: create user satyam identified by jrg;

2. Grant all privileges to user


Syntax: grant all privileges to user
EX: grant all privileges to satyam

3. Revoke all privileges from user


Syntax: revoke all privileges from user
EX: revoke all privileges from satyam

1. GRANT
SQL Grant command is used to grant privileges on the database objects to the
users.

Syntax: GRANT privilege_name ON object_name TO user_name ;

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

EX: GRANT SELECT ON employee TO satyam ;

2. REVOKE
The revoke command removes user privileges to the database objects.

Syntax: REVOKE privilege_name ON object_name FROM User_name ;


Ex: REVOKE SELECT ON employee FROM satyam;
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 67

*************************************************************************

Q). TCL (Transaction Control Language)COMMANDS

Transaction Control (TCL) statements are used to manage the changes made by DML
statements.
1. COMMIT - To make the changes permanent in the database
2. SAVEPOINT - saving point in a transaction to which you can later roll back

Syn: savepoint savepoint_name;


Ex: savepoint emp123;

3. ROLLBACK - Restore database to original since the last COMMIT

Q) Data Types
When you create table in SQL*PLUS, you must specify the type of data that may
appear in each column. Some of the common data types are listed below.

Data Type Command Description


CHAR(size)  Fixed length character data.
 Size written in the bracket determines the length of
data that can be stored.
Character  Default size is 1 and maximum size is 255.
VARCHAR2(siz  Variable length character string having maximum
e) length size in bytes.
 Maximum size is 2000 bytes.
 Size must be specified.
Integer Int  Default size is 38
NUMBER(p,s)  Used to store variable length numeric data.
 P determines the total number of digits possible to
the left of decimal point.
Number  S determines the total number of digits possible to
the right of decimal point.
NUMBER(size)  Fixed point number with precision size and scale 0.
 This data type is used to store data and time
Date DATE information.
 Default format is DD-MON-YY.
 To enter the dates other than standard format, use
the appropriate functions.
 Variable length character strings containing upto2
Long LONG GB.
 Table cannot have more than one Long type of data
field.
 It cannot be used with SQL function.
 It cannot appear in WHERE, GROUP BY, ORDER BY,
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 68

clauses.
Raw RAW(size)  Raw binary data, size byte long.
 Maximum size is 255 bytes.

Q) SQL Constraints
The constraint is a mechanism used by oracle to prevent invalid data into the table. SQL
constraints are used to specify rules for the data in a table.

Constraints can be column level (or) table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:

No Constraint Descrip
Name tion
1 NOT NULL It ensures that a column cannot accept NULL values.
2 UNIQUE It ensures that each row and column have a unique value.
3 CHECK It ensures that the values in a column satisfies the condition.
4 DEFAULT Defines a default value for a column.
5 PRIMARY KEY It is a combination of a NOT NULL and UNIQUE.
6 FOREIGN KEY It is used to connect two tables together.foreign key is the reference
of primary key.

1.NOT NULL Constraint:


1. By default, a column can hold NULL values.
2. The NOT NULL constraint enforces a column to not accept NULL values.
3. You cannot insert a new record, or update a record without adding a value to this field.

EX: CREATE TABLE Persons (ID int NOT NULL, LastName varchar2(25) NOT NULL, FirstName varchar2(25)
NOT NULL, Age int);

2.UNIQUE Constraint
1. The UNIQUE constraint ensures that all values in a column are different.
2. The UNIQUE constraint is used to ensure that each row and column have a unique
value.

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 69

EX: CREATE TABLE Persons (ID int NOT NULL UNIQUE, LastName varchar2(25) NOT NULL, FirstName
varchar2(255), Age int);

3.Check Constraint
1. The CHECK constraint is used to limit the value range that can be placed in a column.
2. If you define a CHECK constraint on a single column it allows only certain values for this
column.

Ex:
CREATE TABLE Persons (ID int NOT NULL,LastName varchar2(25) NOT NULL, FirstName varchar2(25), Age
int CHECK (Age>=18));

4.DEFAULT Constraint
1. The DEFAULT constraint is used to provide a default value for a column.
2. The default value will be added to all new records IF no other value is specified.

EX:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar2(25) NOT NULL, FirstName varchar(255), Age
int, City varchar(255) DEFAULT 'Sandnes');

Note: Use 2nd form insert command(skipping some columns)

5. PRIMARY KEY Constraint


1. The PRIMARY KEY constraint uniquely identifies each record in a database table.
2. Primary keys must contain UNIQUE values, and cannot contain NULL values.
3. A table can have only one primary key, which may consist of single or multiple fields.

EX:
CREATE TABLE Persons (ID int NOT NULL PRIMARY KEY, LastName varchar2(25) NOT NULL, FirstName
varchar2(25), Age int);

6. FORIEGN KEY Constraint(Foreign key is the reference of Primary key)

To establish a parent child relationship between two tables having a same column.
To implement this we should define the column in the parent table as a primary key and the
same column in the child table as a foreign key referencing to the corresponding parent
Table.
Parent table(Dept table)
CREATE table dept(dept_no number(5) primary key, dept_name varchar2(20), dept_loc
varchar2(20));

Child table(Emp table)


Create table emp(eno number(5) primary key, name varchar2(10), sal number(8,2), designation
varchar(10), dept_no number(5) references dept(dept_no));

7. INDEX
1. The CREATE INDEX statement is used to create indexes in tables.
2. Indexes are used to retrieve data from the database very fast. The users cannot see the
indexes, they are just used to speed up searches/queries.

Syn: CREATE INDEX index_name ON table_name (column1, column2, ...);


EX: create index emp114 on emp(eno,ename);

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 70

Q) OPERATORS :

Q) What is an Operator in SQL?

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.
1. Arithmetic operators
2. Comparisons operators
3. Logical operators

1. Arithmetic operators
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Operato Description Example
r
+ It adds the value of both operands. a+b will give
30
- It is used to subtract the right-hand operand from the left-hand a-b will give
operand. 10
* It is used to multiply the value of both operands. a*b will give
200
/ It is used to divide the left-hand operand by the right-hand a/b will give
operand. 2
% It is used to divide the left-hand operand by the right-hand a%b will give
operand and returns reminder. 0

Examples:
1) Display annualsalary of all the employees from emp table?
A) Select eno, ename, salary , salary*12 as annualsal from emp;

2) Display to find out the gross salary of all the employees from emp table?
A) select Select eno,ename,salary ,salary+comm as grosssal from emp;

2.Comparision Operators
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 71

Operator Description Example


= It checks if two operands values are equal or not, if the (a=b) is not
values are queal then condition becomes true. true
!= It checks if two operands values are equal or not, if (a!=b) is true
values are not equal, then condition becomes true.
<> It checks if two operands values are equal or not, if (a<>b) is true
values are not equal then condition becomes true.
> It checks if the left operand value is greater than right (a>b) is not
operand value, if yes then condition becomes true. true
< It checks if the left operand value is less than right (a<b) is true
operand value, if yes then condition becomes true.
>= It checks if the left operand value is greater than or (a>=b) is not
equal to the right operand value, if yes then condition true
becomes true.
<= It checks if the left operand value is less than or equal (a<=b) is true
to the right operand value, if yes then condition
becomes true.
!< It checks if the left operand value is not less than the (a!=b) is not
right operand value, if yes then condition becomes true
true.
!> It checks if the left operand value is not greater than (a!>b) is true
the right operand value, if yes then condition becomes
true.

Examples:

1) Display the employees whose name is satyam?


A) select * from emp where ename =’satyam’;

2) Display all employees whose name is not satyam?


A) select * from emp where ename! =’satyam’;

3) Display all employees whose salary is above 17000?


A) select * from emp where salary>17000;

4) Display all employees whose salary is below 17000?


A) select * from emp where salary<17000;

3. Logical Operators

Here is a list of all the logical operators available in SQL.


Show Examples
Sr.No. Operator & Description

Operator Description
ALL It compares a value to all values in another value set.
AND It allows the existence of multiple conditions in an SQL
statement.
ANY It compares the values in the list according to the condition.

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 72

BETWEEN It is used to search for values that are within a set of values.
IN It compares a value to that specified list value.
NOT It reverses the meaning of any logical operator.
OR It combines multiple conditions in SQL statements.
EXISTS It is used to search for the presence of a row in a specified
table.
LIKE It compares a value to similar values using wildcard operator.

ORDER BY Clause

The order by clause to sort the rows retrieved by a query. The ORDER BY clause may
specify one or more columns on which to sort the data

select * from customers order by first_name ASC , last_name DESC;

The above query sort the rows retrieved from the customers table by ascending
first_name and descending last_name.

*****************************************************************

Q) SQL FUNCTIONS
The Oracle implementation of SQL provides a number of functions that can be used in
SELECT statements. Functions are typically grouped into the following:

1) Single row functions - Operate on column values for each row returned by a
query.
2) Group functions - Operate on a collection (group) of rows.

1. SINGLE ROW FUNCTIONS


CHARACTER FUNCTIONS: Characters functions accept character input, which may
come from a column in a table (or) from any expression. This input is processed and
a result returned.

1. ASCII()
The function ASCII(x) to get the ASCII value of for the character x.
select ASCII('a') from dual;
2. CHR()
The function CHR(x) to get the character with ASCII value of x.
select CHR(95) from dual;

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 73

3. CONCAT()
The function CONCAT(x,y)to append y to x and then return the new string.
Select concat(‘bvraju’,’college’) from dual;
4. INITCAP()
The function INITCAP(x) to convert the initial letter of each word in x to uppercase.
Select initcap(‘a description of modern science’) from dual;
5. INSTR()
The function INSTR(x,find_string[,start] [,occurrence]) to search for find_string in x. This
functrion returns the position at which find_string occurs. We can supply optional start position
to begin the search.
Select instr(‘modern science’, ‘science’) from dual;
6. LENGTH()
The function LENGTH(x) to get the number of characters in x.
select length(‘rama’) from dual;

7. LOWER()
The function LOWER(x) to convert the letters in x to lower case.
select lower(‘RAMA’)from dual;
8. UPPER()
The function UPPER(x) to convert the letters in x to upper case.
select upper(‘rama’) from dual;
9. LTRIM()
The function LTRIM(x[,trim_string]) to trim characters from the left to x. we can specify
optional trim_string , which specifies the characters to trim. If no trim_string is supplied spaces
are trimmed by default.
select ltrim(‘Hello’) from dual;

10. RTRIM()
The function RTRIM(x[,trim_string]) to trim characters from the right to x. we can specify
optional trim_string , which specifies the characters to trim. If no trim_string is supplied spaces
are trimmed by default.
select rtrim(‘hello‘,’o’) from dual;
11. REPLACE()
The function REPLACE(x,search_string,replace_string)to search x for search_string and replace
it with replace_string.
Select replace (‘modern science’,’science’,’physics’) from dual;

***************************************************************************

Q) NUMERIC FUCTIONS
These functions accept an input number , which may come from a numeric column
or any expression that evaluates to a number. A calculation is then performed and
a number is returned.
1. ABS()
The function ABS() to get the absolute value of x. The absolute value of a
number is that number without any positive or negative sign.
SELECT ABS(10), ABS(-10) FROM dual;
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 74

2. MOD()
The function MOD(x,y) to get the remainder when x is divided by y.
select mod(8,3) from dual;

3. POWER()
The function POWER(x,y) to get the result of x raised to the power y.
select power(2,3) from dual;

4. ROUND()
The function ROUND(x[,y]) to get the result of rounding x to an optional y
decimal places. If y is omitted x is rounded to zero decimal places.
select round(5.75) ,round(5.75,1) from dual;

5. SIGN()
The function SIGN(x) to get the sing of the x. SIGN() returns -1 if x is negative , 1
if x is positive , or 0 if x is zero.
select sign(-5) , sign(5) , sign(0) from dual;

6. SQRT()
The function SQRT(x) to get the square root of x.
select sqrt(9 ) from dual;

7. TRUNC()
The function TRUNC(x[,y]) to get the result of truncating the number x to an
optional y decimal places.. if y is omitted ,x is truncated to zero decimal places.
select trunc(5.75),turnc(5.75,1) from dual;

*********************************************************************

Q) CONVERSION FUNCTONS
These functions are used to convert a value from one data type to another.
1. TO_CHAR()
The function TO_CHAR(x[,format]) to convert x to a string. The format is
optional.
SELECT TO_CHAR(12345.67) FROM DUAL;
SELECT TO_CHAR(12345.67,’99,999.99’)FROM DUAL;

2. TO_NUMBER()
The function TO_NUMBER(x[,format]) to convert x to a number.
SELECT TO_NUMBER(‘970.13’) FROM DUAL;
SELECT TO_NUMBER(’12,345.67’,’99,999.99’)FROM DUAL;

****************************************************************************
Q) DATE&TIME FUNCTIONS
These functions are used to get or process date times and timestamps.
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 75

1. ADD_MONTHS()
The function ADD_MONTHS(x, y) returns the result of adding y months to x.
SELECT ADD_MONTHS(’01-JAN-2007’ , 13) from dual;

2. LAST_DAY()
The function LAST_DAY(x) returns the date of the last day of the month of x.
SELECT LAST_DAY (’01-JAN-2008’) FROM DUAL;

3. MONTHS_BETWEEN ()
The function MONTHS_BETWEEN(x,y) returns the number of months between x and y.
SELECT MONTHS_BETWEEN (’25-may-2008’,’15-jan-2008’) FROM DUAL;

4. NEXT_DAY ()
The function NEXT_DAY(x,day) returns the date of the next day following x.
SELECT NEXT_DAY(’01-JAN-2008’,’SATURDAY’) FROM DUAL;

5. ROUND()
The function ROUND(x[,unit]) rounds x, by default, to the beginning of the nearest
day. If you supply an optional unit string , x is rounded to that unit.

SELECT ROUND(TO_DATE(’25-OCT-2008’),’YYYY’) FROM DUAL; SELECT ROUND(TO_DATE( ’25-


MAY-2008’),’MM’)FROM DUAL;
6. SYSDATE
The SYSDATE return the current datetime set in the database server ’s operating
system.
SELECT SYSDATE FROM DUAL;

7. TRUNC()
The function TRUNC(X[,unit]) truncates x. By default, x is truncated to the beginning
of the day. If you supply the optional unit string, x is truncated to that unit.

SELECT TRUNC(TO_DATE(’25-OCT-2020’),’YYYY’) FROM DUAL; SELECT TRUNC(TO_DATE( ’25-


MAY-2020’),’MM’)FROM DUAL;

Q) AGGREGATIVE FUNCTIONS:

These functions take more than one row as input and returns one row as output.

1. COUNT ([Distinct] A) :

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 76

COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.

COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Consider the following PRODUCT_MAST Table

PRODUCT COMPANY QTY RATE COST


Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120

Syntax: select count(column_name) from table name ;


Eg : SELECT COUNT(*) FROM PRODUCT_MAST;

Output:- 10

Example: COUNT with WHERE

SELECT COUNT(*) FROM PRODUCT_MAST WHERE RATE>=20;

Output:- 7

3. SUM (A) :
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only. The sum of all values in the A column.

Syntax: select sum(column_name) from table name ;


Eg. SELECT SUM(COST) FROM PRODUCT_MAST;

Output:- 670

Example: SUM() with WHERE

SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3;

Output:- 320

4. AVG (A) :
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values. The average of all values in the A
column.

Syntax: select avg(column_name) from table name ;


Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 77

Eg. SELECT AVG(COST) FROM PRODUCT_MAST;


Output:- 67.00

5. MAX (A) :
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column. The maximum values
in the A column.

Syntax: select max(column_name) from table name ;


Ex: SELECT MAX(RATE) FROM PRODUCT_MAST;

Output:- 30

6. MIN (A) :
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column. The minimum
value in the A column.

Syntax: select min(column_name) from table name ;


Eg: SELECT MIN(RATE) FROM PRODUCT_MAST;

Output:- 10

Order By Clause
The ORDER BY clause is used in a SELECT statement to sort results either in ascending
(or) descending order. Oracle sorts query results in ascending order by default.
Syntax
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1 [,
column2, .. columnN] [DESC]];
EX: SELECT PRODUCT, COST FROM PRODUCT_MAST ORDER BY COST desc;

GROUP BY Clause:
The GROUP BY clause is used to group the rows based on some column, normally
group by clause return only one row. Group by clause is used with GROUP BY
FUNCTIONS only.
Syntax
SELECT column_name (or) aggregate_function(column_name) FROM table_name WHERE condition
GROUP BY column_name ORDER BY column_name ;
EX: SELECT Product, sum(cost) FROM Product_mast WHERE QTY= ’2 ’ GROUP BY Product ORDER BY
Product;

GROUP BY HAVING Clause:


Having clause is used to filters the rows return by group by clause.
Syntax
SELECT column_name (or) aggregate_function(column_name) , FROM table_name WHERE condition
GROUP BY column_name HAVING condition;
EX: SELECT job , sum(sal) FROM emp WHERE address=’bvrm’ GROUP BY job HAVING JOB= ’CLEARK ’ ;

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 78

************************************************************************

Q) Different types of SQL JOINS

A JOIN clause is used to combine rows from two or more tables, based on a related
column between them. Let’s look at a selection from the "Orders" table and
“Customers” table:

OrderID CustomerID OrderDate


10308 2 2016-09-18
10309 37 2016-09-19
10310 77 2016-09-20

CustomerID CustomerName ContactName Country


1 Vijay Chinna Bhimvaram
2 Satyam Murali Tanuku
3 Nani Vamsi Tadepalligudem
4 Ramu Raveendra Bhimavaram
There are Five Types of Joins in Sql
1. Inner Join
2. Left (outer)Join
3. Right(outer)Join
4. Full Join(outer)join
5. Self Join

1. Inner join
The INNER JOIN keyword selects records that have matching values in both tables.
Syntax:
SELECT column_name(s) FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 79

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

2. Left Join
The LEFT JOIN keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right
side, if there is no match.

Syntax:
SELECT column_name(s) FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
EX:
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN
Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY
Customers.CustomerName;

3. Right Join
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side,
when there is no match.
Syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name =
table2.column_name;
EX:
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName FROM Orders RIGHT
JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER BY
Orders.OrderID;

4. Full Join

The FULL OUTER JOIN keyword return all records when there is a match in either left
(table1) or right (table2) table records.

Note: FULL OUTER JOIN can potentially return very large result-sets!

Syntax:
SELECT column_name(s) FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
EX:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers FULL OUTER JOIN Orders ON
Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;

5. Self Join
A self JOIN is a regular join, but the table is joined with itself.
Syntax:
SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition;
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 80

EX:
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;

**************************************************************************

Q). Subquery
Subquery or Inner query or Nested query is a query in a query. It is the one of the most
powerfull feature in nested query. SQL subquery is usually added in the WHERE Clause
of the SQL statement.

Most of the time, a subquery is used when you know how to search for a value using a
SELECT statement, but do not know the exact value in the database.

Subqueries are an alternate way of returning data from multiple tables.

There are few rules that subquery must follow:


1. Subqueries must be enclosed within parentheses.
2. A subquery can have only one column in the SELECT clause, unless
multiple columns are in the query for the subquery to compare its selected
columns.
3. A subquery cannot be immediately enclosed in a set function.
Subqueries can be used with the following SQL statements along with the
comparision operators like =, <, >, >=, <= etc.
1. SELECT
2. INSERT
3. UPDATE
4. DELETE
1. Subqueries with the Select Statement
SQL subqueries are most frequently used with the Select statement.

Syntax
SELECT column_name FROM table_name WHERE column_name expression operator( SE
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 81

LECT column_name from table_name WHERE ... );


Example
Consider the EMPLOYEE tables have the following records:

ID NAME AGE ADDRESS SALARY


1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
6 Harry 42 China 4500.00
7 Jackson 25 Mizoram 10000.00
The subquery with a SELECT statement will be:

SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);
This would produce the following result:

ID NAME AGE ADDRESS SALARY


4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
7 Jackson 25 Mizoram 10000.00
2. Subqueries with the INSERT Statement

 SQL subquery can also be used with the Insert statement. In the insert statement,
data returned from the subquery is used to insert into another table.
 In the subquery, the selected data can be modified with any of the character, date
functions.

Syntax:
INSERT INTO table_name (column1, column2, column3....)
SELECT * FROM table_name WHERE VALUE OPERATOR
Example
Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.
Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP
table.

INSERT INTO EMPLOYEE_BKP SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement

The subquery of SQL can be used in conjunction with the Update statement. When a
subquery is used with the Update statement, then either single or multiple columns in a
table can be updated.

Syntax
UPDATE table SET column_name = new_value WHERE VALUE OPERATOR (SELECT COLUMN_NAM
E FROM TABLE_NAME WHERE condition);
Example

UPDATE EMPLOYEE SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMER
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 82

S_BKP WHERE AGE >= 29);


This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY


1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 1625.00
5 Kathrin 34 Bangalore 2125.00
6 Harry 42 China 1125.00
7 Jackson 25 Mizoram 10000.00
4. Subqueries with the DELETE Statement

The subquery of SQL can be used in conjunction with the Delete statement just like
any other statements mentioned above.

Syntax

DELETE FROM TABLE_NAME WHERE VALUE OPERATOR (SELECT COLUMN_NAME FROM TABLE_NAME W
HERE condition);

Example:
DELETE FROM EMPLOYEE WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY


1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
7 Jackson 25 Mizoram 10000.00

*****************************************************************************

Q). SQL- Views(Virtual Tables)

In the SQL language, a view is a representation of one or more tables. A view can be
used to hide the complexity of relationships between tables (or) to provide security for
sensitive data in tables.

In the following example, a limited view of the emp table is created. When a view is
defined, a SQL statement is associated with the view name. Whenever the view is
accessed, the SQL statement will be executed.

SQL> create table emp(empno number(5), ename varchar2(10), salary number(5), desg
varchar2(10), dno number(3));
Table Created

SQL> insert into emp values(101, ’abc ’, 1000, ’acc ’,


10);
Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science
Page- 83

insert into emp values(102, ’def’, 2000, ’clk’, 10);


insert into emp values(103, ’ghi’, 3000, ’gar ’,
20);
insert into emp values(104, ’jkl’, 4000, ’acc’, 10);
insert into emp values(105, ’mno’,5000, ’clk’, 20);
5 rows created

Note : Insert the records in EMP likewise

SQL> Select * from emp;

EMPNO ENAME SALARY DESG DNO


101 abc 1000 acc 10
102 def 2000 clk 10
103 ghi 3000 gar 20
104 jkl 4000 acc 10
105 mno 5000 clk 20

In the following example, the view emp_1 is created as a limited number of columns (Empno,
Ename, salary) and limited set of data ( WHERE salary > 3000 ) from the EMP table.

SQL> CREATE VIEW emp_1 AS SELECT Empno, Ename, salary FROM emp WHERE salary >
3000;

View created.

Once the view is created, it can be queried with a SELECT statement as if it were a table.

SQL> SELECT * FROM emp_1 ;


EMPNO ENAME SALARY
104 jkl 4000
105 mno 5000

Views can be dropped in a similar fashion to tables. The DROP VIEW command provides
this facility. In the following example, the view just created is dropped.

SQL> DROP VIEW emp_1;


View dropped.

View can be again created with the same name emp_1 as a limited number of columns
(Empno, Ename, salary, dno) and limited set of data ( WHERE dno=10 ) from the EMP
table.

SQL> CREATE VIEW emp_1


AS SELECT Empno, Ename, salary, dno FROM emp WHERE dno=10;
View created.

Once the view is created, it can be queried with a SELECT statement as if it were a table.

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 84

SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY DNO


101 abc 1000 10
102 def 2000 10
104 jkl 4000 10

SQL> Insert into emp_1 values (106,’xyz’,4500,10);


1 row created
SQL> SELECT * FROM emp_1 ;

EMPNO ENAME SALARY DNO


101 abc 1000 10
102 def 2000 10
104 ewd 4000 10
106 xyz 4500 10

Do the same with EMP table

SQL> SELECT * FROM

emp ;

EMPNO ENAME SALARY DESG DNO


101 abc 1000 acc 10
102 def 2000 clk 10
103 ghi 3000 gar 20
104 jkl 4000 acc 10
105 mno 5000 clk 20
106 xyz 4500 10

The same record will be inserted into base table also and Vice versa

SQL> Insert into emp_1 values (107,’wqa’,3500,20);

1 row created

SQL> SELECT * FROM emp_1 ;


EMPNO ENAME SALARY DNO
101 abc 1000 10
102 def 2000 10
104 jkl 4000 10
106 xyz 4500 10

The record will not be visible in view because the record does not satisfy the

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 85

WHERE dn0=10 condition, but it will be inserted in base table EMP

SQL> SELECT * FROM emp ;

EMPNO ENAME SALARY DESG DNO


101 abc 1000 acc 10
102 def 2000 clk 10
103 ghi 3000 gar 20
104 jkl 4000 acc 10
105 mno 5000 clk 20
106 xyz 4500 10
107 wqa 3500 20

Actually this record must not be accepted while inserted in view EMP_1 because it does
not hold the condition.
So we can enable this condition by including WITH CHECK OPTION in View creation.

SQL> Drop view emp_1;


View droped.

SQL> CREATE VIEW emp_1


AS SELECT Empno, Ename, salary, dno FROM emp
WHERE dno=10 WITH CHECK OPTION;
View created.
SQL> SELECT * FROM emp_1 ;
EMPNO ENAME SALARY DNO
101 abc 1000 10
102 def 2000 10
104 jkl 4000 10
106 xyz 4500 10

SQL> Insert into emp_1 values (108,’okl’,7500,20);


Error: Record not inserted because CHECK constraint violated.

We can make the view read only by the following rules


1) Key fields must not be included in view definition
2) NOT NULL fields must not be included in view
definition
3) SQL> alter table emp add PRIMARY KEY(empno);
Table altered
SQL> CREATE VIEW emp_2
AS SELECT Ename, salary, dno FROM emp WHERE dno=10 WITH CHECK
OPTION;
View created.
SQL> SELECT * FROM emp_2 ;
ENAME SALARY DNO

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 86

abc 1000 10
def 2000 10
jkl 4000 10
htg 4500 10

SQL> Insert into emp_2 values (’okl’,7500,10);


Error: NULL values cannot inserted in PRIMARY KEY field EMP.EMPNO
This view cannot accept insertion because when it inserts a record it is trying to insert
NULL into primary key field of Base table EMP.

**********************************************************************************
**

Q) SQL SET Operators

SET operators are behave same like mathematical sets, these sql set operators are classified
into four types, which is given below;
1. Union
2. Union all
3. Minus
4. Intersect

1. Union
Union operator return all the value from all the table excluding duplicate values, it means
it not return duplicate values.

 The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
 In the union operation, all the number of data type and columns must be same in both the
tables on which UNION operation is being applied.
 The union operation eliminates the duplicate rows from its result set

Example

SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST UNION


SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_DESIGN;

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 87

2. Union all
 Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.
 Union all operator returns all the value from all the table including duplicate
values.

Example

SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST UNION ALL


SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_DESIGN;

3. Intersect
 It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
 In the Intersect operation, the number of data type and columns must be the
same.
 It has no duplicates and it arranges the data in ascending order by default

Intersect operator return the common value from all the variables.

Example

SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST


INTERSECT
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science


Page- 88

4. Minus
 It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
 It has no duplicates and data arranged in ascending order by default.

Minus operator return the values which are not available in first table but not available
in second table.

Example

SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM EMP_TEST


MINUS
SELECT EMP_ID, EMP_NAME, EMP_ADDRESS, EMP_SSN FROM

Prepared By: M.VENKAT (MCA, M-Tech) Lecturer in Computer science

You might also like