Unit 3
Unit 3
Unit 3
Introduction to SQL
Every data table that we have created so far has stored data for us. All this data would server
very little purpose if it could not be retrieved. In order to retrieve this data one needs to be
able to talks to the tables. The SQL allow user of the database to communicate with the
database.
Advantages of SQL:
1. Database management (using queries, tables).
2. Window based.
3. Can hold millions of data.
4. easy to access.
5. Extremely powerful and flexible.
6. Compatible with every major database engine.
Types of SQL:
1. Interactive SQL:
It is used for interactive directly with the database where the output of
operation is used for human consumption. Once a command is specified it is executed
and the output can be immediately viewed by the user.
2. Embedded SQL:
In this commands are SQL commands that are written in some other
languages such as COBOL, C, visual basic, java etc.
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.
Components of SQL
DDL Commands
DML Commands:
DCL Commands:
DQL Commands:
DDL Commands:
The DDL commands are as follows
1. CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Tables are organized into rows and columns; and each table must have a name.
Syntax:
CREATE TABLE <table_name >
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
Example
CREATE TABLE Persons
( PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Optput: Persons
Syntax
1. ALTER TABLE table_name ADD column_name datatype
Example
The DROP TABLE statement is used to delete a table definition from the database.
Once the command executed the table definition uis removed from the system and your table
does not exist any more
Syntax:
DROP TABLE table_name
Example
Drop table book
5. TRUNCATE TABLE Statement
To delete all the rows from the table i.e. making table empty is done by using
truncate table command.
Syntax:
TRUNCATE TABLE table_name
Example:
Truncate table book
6 .Desc Commands
The table structure can be seen with the help of describe command.
Syntax:
Desc <table name>
Example
Desc emp
DML Commands:
The DML commands are as follows
1. INSERT COMMAND
It is used to add new rows to your table.
Syntax:
Insert into <table name> (columan_name1, column_name2…..column_nameN)
Values (value1, value2, …...valueN)
Example
Insert into Emp (Emp_id,Emp_name,Salary,Deptno) values(1,’xyz’,10000,10)
2. UPDATE COMMAND
It is used to change or modify the data values in the table.
Syntax:
Update <table name> set <column-name=value1> where <condition>
Example
Update Emp set Emp_name=’ABC’ where emp_id=1
3. DELETE COMMAND
It is used to delete rows permanently that satisfy yiur where condition.It does not
remove your table definition
Syntax:
DCL Command
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. Privileges are of two types,
System: creating session, table etc are all types of system privilege.
Object: any command or query to work on tables comes under object privilege.
DCL defines two commands,
1. Grant:
This command is used to give permission to user to do operations on the other
user‘s object.
2. Revoke:
This command is used to withdraw the privileges that have been granted to a user.
Syntax: Revoke <object privileges>on<object name>from <username> ;
TCL command
Transaction Control Language (TCL) commands are used to manage transactions
in database. These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.
Commit command
Commit command is used to permanently save any transaction into database.
Following is Commit command's syntax,
commit;
Rollback command
This command restores the database to last committed state. It is also use with
savepoint command to jump to a savepoint in a transaction.
Following is Rollback command's syntax,
rollback to savepoint-name;
Savepoint command
savepoint command is used to temporarily save a transaction so that you can
rollback to that point whenever necessary.
Following is savepoint command's syntax,
savepointsavepoint-name;
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
INSERT into class values(5,'Rahul');
commit;
UPDATE class set name='abhijit' where id='5';
savepointA;
INSERT into class values(6,'Chris');
savepointB;
INSERT into class values(7,'Bravo');
savepointC;
SELECT * from class;
The resultant table will look like,
ID NAME
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now rollback to savepoint A
rollback to A;
SELECT * from class;
ID NAME
1 Abhi
2 Adam
4 Alex
5 Abhijit
DQL Command:
SELECT COMMAND
It is used to display all/particular records from the table. The basic structure of
an SQL expression consist of three clauses; SELECT, FROM, WHERE.
SELECT => It corresponds to the projection operation of the relational algebra. It is
used
to list the attributes desired in the result of query.
FROM => It corresponds to Cartesian product operation of relational algebra. It
lists
the relation to be scanned in the elevation of experiments.
WHERE => It corresponds to selection predicate of relational algebra. It consist of
predicate involving attributes at the relation that appear in the from
clause.
Synatax:
Select * from <table name>;
Select < column_name1,……column_nameN) from <table name>
Select < column_name1,……column_nameN) from <table name> where <condition>
Example
Select * from Emp;
Select Emp_id,Salary from Emp;
Select Emp_id,salary from Emp where salary >10000
SQL Operators:
1. Arithmetic operation
Arithmetic operators are used to perform mathematical functions in
SQL.
Operator Definition
+ Addition
- Subtraction
* Multiplication
/ Division
Example
Select Emp_id , salary+500. From Emp
Select Emp_id , salary-bonus from Emp
Select Emp_id , salary*5 from Emp
Select Emp_id , salary/10 from Emp
2. Logical Operator
These operators compare two conditions at a time to determine whether a row can
be selected for output when retrieving data.
Example
Select * from Emp where salary>=5000 AND salary>=50000
Select * from Emp where job=’clerk’ OR job=’manager’
Select * from Emp where not job=’clerk’
3. Comparison Operator
These are used to compare one expression with another. The result of
comparison are true, false or unknown
Operator Definition
= Equality
!=,<> Inequality
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Example
Operator Description
IN Equal to any members of
NOT IN Not equal to any members of
IS NULL Tests for NULL
LIKE Return true when first expression
matches second
NOT LIKE Display all rows from table where data
does not match with condition
ALL Compare a value to every value in the
list
ANY,SOME Compare a value to each value in the
list
BETWEEN X and Y >=X and <=Y
EXITS True if sub query returns at least one
row
Example
Select * from Emp where job IN (‘clerk’,’ manager’)
Select * from Emp where salary NOT IN (5000, 10000)
Select * from Emp where job = ANY (‘clerk’, ’manager’)
Select * from Emp where job = SOME (‘clerk’, ’manager’)
Select * from Emp where Emp_name LIKE ‘xy%’
Select * from Emp where salary IS NULL
Select * from Emp where Emp_name NOT LIKE ‘xy%’
Select * from Emp where salary > ALL (5000, 10000)
Select * from Emp where salary BETWEEN 5000 and 30000
Set Operators
It combines the results of two separate queries into a single result. The set
operators are presented by special keywords Union, Union all, Intersection, Minus.
Union
UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and datatype
must be same in both the tables.
Example of UNION
ID Name
2 adam
1 abhi
3 Chester
2 adam
ID NAME
1 abhi
2 adam
3 Chester
Union All
This operation is similar to Union. But it also shows the duplicate rows.
Example of Union All
1 abhi
2 adam
2 adam
3 Chester
Intersect
ID NAME
2 adam
Minus
Minus operation combines result of two Select statements and return only those
result which belongs to first set of result..
Example of Minus
ID NAME
1 abhi
Clauses
SQL WHERE Clause
Syntax
Example
Syntax:
Example
SELECT * FROM Emp ORDER BY Emp_name;
SELECT * FROM Emp ORDER BY salary DESC;
GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to
group the result-set by one or more columns.
Syntax:
Example
Select deptno,sum(salary) from Emp GROUP By Deptno;
Syntax:
Example
Select deptno,SUM(salary) from Emp GROUP BY deptno HAVING SUM(salary)>15000
SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based
on a common field between them.
Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Example
Syntax:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Nested Query
In SQL, a nested query involves a query that is placed within another query.
Output of the inner query is used by the outer query. A nested query has two
SELECT statements: one for the inner query and another for the outer query.
The basic syntax of a nested query involves placing one query inside of
another query. Inner query or subquery is executed first and returns a set of
values that are then used by the outer query. The syntax for a nested query
is as follows:
SELECT column1, column2, ...
FROM table1
WHERE column1 IN ( SELECT column1
FROM table2
WHERE condition )
Examples
1 John 1
2 Mary 2
3 Bob 1
4 Alice 3
5 Tom 1
dept_id dept_name
1 Sales
2 Marketing
3 Finance
1 1 1000
2 2 2000
3 3 3000
4 1 4000
5 5 5000
6 3 6000
7 2 7000
Required query
SELECT emp_name
FROM employees
WHERE dept_id IN (SELECT dept_id
FROM departments
WHERE dept_name = 'Sales');
Output
emp_name
John
Bob
Tom
Example 2: Find the names of all employees who have made a sale
Required query
SELECT emp_name
FROM employees
WHERE EXISTS (SELECT emp_id
FROM sales
WHERE employees.emp_id = sales.emp_id);
Output
emp_name
John
Mary
Bob
Alice
Tom
This query selects all employees from the "employees" table where there
exists a sale record in the "sales" table for that employee.
Functions
Numeric functions
SQL numeric functions are used primarily for numeric
manipulation and/or mathematical calculations. The following
table details the numeric functions –
Sr.N
Function & Description
o.
ABS()
1
Returns the absolute value of numeric expression.
ACOS()
2 Returns the arccosine of numeric expression. Returns
NULL if the value is not in the range -1 to 1.
ASIN()
3 Returns the arcsine of numeric expression. Returns
NULL if value is not in the range -1 to 1
ATAN()
4
Returns the arctangent of numeric expression.
ATN2()
5 Returns the arctangent of the two variables passed to
it.
CEILING()
Returns the smallest (closest to negative infinity)
6
integer value that is greater than or equal to this
value.
COS()
7
Returns the trigonometric cosine of the given value.
COT()
8 Returns the trigonometric cotangent of the given
value.
DEGREES()
9 Returns numeric expression converted from radians to
degrees.
EXP()
10 Returns the base of the natural logarithm (e) raised to
the power of passed numeric expression.
FLOOR()
11 Returns the largest integer value that is not greater
than passed numeric expression.
LOG()
12 Returns the natural logarithm of the passed numeric
expression.
LOG10()
13 Returns the base-10 logarithm of the passed numeric
expression.
PI()
14
Returns the value of pi
POWER()
15 Returns the value of one expression raised to the
power of another expression
16 RADIANS()
Returns the value of passed expression converted
from degrees to radians.
RAND()
17
Returns the random value between 0 and 1.
ROUND()
Returns numeric expression rounded to an integer.
18
Can be used to round an expression to a number of
decimal points
SIGN()
19 Returns the sign of a number, indicating whether it is
positive, negative, or zero.
SIN()
20 Returns the sine of numeric expression given in
radians.
SQRT()
21 Returns the non-negative square root of numeric
expression.
TAN()
22 Returns the tangent of numeric expression expressed
in radians.
String Function:
Character functions accept character as a input and return either character or
number values.
Sr no.
Function Description
1
Initcap(str) Converts first letter of string to capital
letter. Example: Select initcap(‗rdbms‘)
from dual;
2
Lower(char) Converts a string to all lowercase
characters. Example: Select
lower(‗RDBMS‘) from dual;
5
Ltrim(char,set) It trim from the left of character string.
Example: Select Ltrim(‗manas khan‘,
‗manas‘) from dual;
6
Rtrim(char,set) It trim from the Right of character string.
Example: Select Rtrim(‗manas khan‘,
‗khan‘) from dual;
7
Translate(char,fromstring,to It returns expr with all occurrences of each
string) character in from string replaced by its
corresponding character in to_string.
Example: Select
translate(Hickory,‘H‘,‘D‘) from dual
8
Replace(char,searchstring, It returns character string with each
[repstring]) occurrences of search string replaced with
[repstring] Example: Select replace(‗Tick
and Tock‘,‘T‘,‘Cl‘) from dual;
9
Substr(char,m,n) It returns substring of character string that
stack at m character and is of length n
Example: Select substr(Triangle‘4,5) from
dual;
10
Concatenation() It merges two or more strings or a string
and a data value together Example: Select
(‗Branch is‘|| branch_name) from
table_name;
11
Lpad(char1,length, It returns char1, left-padded to given
char2) length with the sequence of characters in
char2. Example: Select Lpad(‗SKY‘, 8,
‗*‘) from dual;
12
Rpad(char1,length ,char2 It returns char1, right-padded to given
) length with the sequence of characters in
char2. Example: Select Lpad(‗SKY‘, 8,
‗*‘) from dual;
Date functions
Date functions take values that are of data type DATE as input and return values of
datatype DATE except months_between which return number as output.
Sr no.
Function Description
1
months_between(d1,d2) Used to find number of months
Where, d1 and d2 are dates between d1 and d2. If d1 later date
then d2 ans is positive If d1 earlier
than d2 answer is negative Example:
Select months_between(‘05-MAY-
1996‘,‘05-JAN-1996‘) from dual;
2
add_months(d,n) Where,d is Returns date after adding the number
date, n no of months to be added of months specified with the function.
Example: Select
add_months(sysdate,2) from dual;
3
Next_day(d,char) Where d is Returns the date of the first weekday
date, char- day of week named ‗char‘ that is after the date
named by date. Example: Select
next_day(‘01-FEB-
2006‘,‘Wednesday‘) from dual;
4
Last_day(d) Where, d is date Returns the last day of the month that
contains date ‗d‘. Example: Select
last_day(sysdate) from dual
5
Round(date,[fmt]) Where, fmt Returns date rounded to the unit
format model Month Day Year specified by the format model ‗fmt‘.
Example: Select round(sysdate,‘day‘)
from dual;
6
Trunc(date([fmt]) Where, fmt Returns date with the time portion of
format model Month Day Year the day truncated to the unit specified
by the format model fmt. Example:
Select trunc(sysdate,‘day‘) from dual;
Aggregate function:
The aggregate functions are function that takes a collection of values as input
and returns single value as output. The general syntax of aggregate function is
Syntax:
Aggregate_function name (expression)
Views
It can be defined as logical part of total data present in the table. It can be created
with the help of select command. Views are created for security reasons. Instead of coping
same table multiple times for different requirements, views can be created. View is a logical
copy of physical table. It doesn‘t exist physically. With the help of view, we can give
restricted access to users. When view is used, underlying table is invisible, thus increasing
security. Views can be used to see, insert, update and delete data from base table.
Advantages of Views:
1. Views restrict access to the data because the view can display selective columns from the
table.
2. Views can be used to make simple queries to retrieve the results of complicated queries.
3. Views provide data independence for adhoc users and application programs. One view can
be used to retrieve data from several tables.
4. Views provide groups of users to access to data according to their particular criteria. Thus
implements security and authorization.
Example
Create view v1 as select * from Emp;
Create view v1 as select Emp_id,Emp_ name,deptno from Emp;
Update view:
It can be used to update data from the table as well as view.
Example
Delete view:
It can be used to delete data from the table as well as view.
Example
Dropping views:
Drop view command is used to drop the view
Syntax
Drop view <view name>
Example
Drop view v1
SEQUENCE
Definition:
A sequence refers to a database object that is capable of generating unique and
sequential integer values.
Use:
1. It saves a time by reducing application code.
2. It is used to generate unique sequential integers.
3. It is used to create an auto number fields.
4. Sequence can be use for many tables/relations
Syntax:
Create sequence <seq_name> [increment by num] [start with num] [maxvalue num]
[minvalue
num][cycle/nocycle][cache num/nocache];
Where,
Start with num: States the first sequence numbers that needs to be generated.
Minvalue num: This is used to state the minimum value of the sequence.
Cycle: Cycle indicates that the sequence will be continued for generating the values from the
starting after reaching either its maximum value or minimum value.
Cache: The cache option is used to pre-allocate a set of sequence numbers and keep these
numbers in the memory so that they can be accessed.
No Cache: This states that there is no pre-allocation for the values of sequence.
Example:
Altering Sequences
Syntax:
Dropping Sequences:
Syntax:
INDEX:
An index is a schema object that can speed up the retrieval of rows by
using pointer. An index provides direct and fast access to rows in a table. Indexes are created
explicitly Or automatically. Indexes are used to speed up searches/queries.
Types of Index:
Simple index (Single column): An index created on single column of a table is called a
Simple Index.
Composite (concatenated): An index created on multiple column of a single table is called a
Composite Index.
Unique indexes: They are used not only for performance, but also for data integrity. A
unique index does not allow any duplicate values to be inserted into the table.
Syntax:
Creating simple index
Create index <index name > on <table name> <column name>
Example
Create index idx1 on Emp (Ename)
Creating multiple index
Create index <index name > on <table name> <column name1, column name2>
Example
Create index idx2 on Emp (Ename,Salary)
Creating Unique index
Create unique index <index name > on <table name> <column name>
Example
Create unique index idx3 on Emp (Ename)
Dropping Index
E.g. .
SYNONYMS
It is a name given to the table, view, sequence, stored procedure, function for the
user’s conveniences to use.
Creating synonyms:
Create synonyms command is used to create the synonyms.
Syntax
To view synonym:
Dropping synonym:
Syntax