Professional Documents
Culture Documents
DBMS-4
DBMS-4
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.
1970 − Dr. Edgar F. "Ted" Codd’s of IBM is known as the father of relational
databases. He described a relational model for databases.
1978 − IBM worked to develop Codd's ideas and released a product named
System/R.
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.
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.
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:
2. ALTER:
4. TRUNCATE:
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:
This command is used to select the attributes from the rows in one or more
tables or views
3. UPDTE:
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 take back the permission from the users.
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
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 );
2. ALTER TABLE
The ALTER TABLE statement is used to modify structure of an existing table. There are
three different syntaxes
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;
2. TRUNCATE TABLE:
Truncate command will delete all the records permanently in a specified table but
structure of the table will not be deleted.
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.
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,...);
2. SELECT:
a) The select command is used to retrieve all records from the tables.
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;
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;
***********************************************************************************
1. GRANT
SQL Grant command is used to grant privileges on the database objects to the
users.
2. REVOKE
The revoke command removes user privileges to the database objects.
*************************************************************************
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
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.
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.
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.
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');
EX:
CREATE TABLE Persons (ID int NOT NULL PRIMARY KEY, LastName varchar2(25) NOT NULL, FirstName
varchar2(25), Age int);
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));
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.
Q) 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
Examples:
3. Logical Operators
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.
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
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. 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;
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.
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.
Q) AGGREGATIVE FUNCTIONS:
These functions take more than one row as input and returns one row as output.
1. COUNT ([Distinct] A) :
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
Output:- 10
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.
Output:- 670
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.
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.
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.
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;
************************************************************************
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them. Lets look at a selection from the "Orders" table and
Customers table:
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.
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
SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);
This would produce the following result:
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);
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
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.
*****************************************************************************
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
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.
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.
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.
Once the view is created, it can be queried with a SELECT statement as if it were a table.
emp ;
The same record will be inserted into base table also and Vice versa
1 row created
The record will not be visible in view because the record does not satisfy the
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.
abc 1000 10
def 2000 10
jkl 4000 10
htg 4500 10
**********************************************************************************
**
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
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
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
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