Unit-III-SQL RDBMS: A Lalitha Associate Professor Avinash Degree College
Unit-III-SQL RDBMS: A Lalitha Associate Professor Avinash Degree College
RDBMS
A LALITHA
ASSOCIATE PROFESSOR
AVINASH DEGREE COLLEGE
SQL(Structured Query Language)
What is SQL?
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 and SQL Server use SQL as their standard database language.
Why SQL?
Allows users to access data in the relational database management systems.
Allows users to describe the data.
Allows users to define the data in a database and manipulate that data.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views
Data Types: It specifies what type of values to be stored for a particular attribute for a relation.
CHAR
VARCHAR
NUMBER
DATE
SQL Commands
DDL COMMANDS(CREATE,DROP,ALTER,TRUNCATE,DESC,RENAME)
• 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:
CREATE It is used to create a new table in the database.
Syntax: CREATE TABLE TABLE_NAME
(
COLUMN_NAME1 DATATYPES(size),
COLUMN_NAME2 DATATYPES(size),
………
);
Example: CREATE TABLE EMPLOYEE
(
Name VARCHAR2(20),
Email VARCHAR2(100),
DOB DATE
);
ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics of an existing
attribute or probably to add a new attribute.
Syntax: ALTER TABLE table_name ADD column_name COLUMN-definition;
EX:ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax: TRUNCATE TABLE table_name;
Ex: TRUNCATE TABLE EMPLOYEE;
DROP: It is used to delete both the structure and record stored in the table.
Syntax: DROP TABLE Table_name;
Ex :DROP TABLE EMPLOYEE;
DML COMMANDS(Insert, Select,Update and Delete)
DML commands are used to modify the database. It is responsible for all form of changes in the database.
INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
Syntax: INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
Ex: INSERT INTO employee VALUES (101,‘leela’,200000);
UPDATE: This command is used to update or modify the value of a column in the table.
Syntax: UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION] ;
Ex: UPDATE students SET address = ‘KPHB' WHERE Student_Id = '3‘;
• DCL commands which mainly deals with the rights, permissions and other controls of the database System.
GRANT-gives user’s access privileges to database.
syntax: GRANT privilege_name ON object_name
TO {user_name | PUBLIC | role_name} [with GRANT option];
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.
Public is used to grant rights to all the users.
With Grant option: allows users to grant access rights to other users.
Ex:GRANT SELECT ON employee TO user1
SAVEPOINT:This command is used to temporarily save a transaction so that you can rollback to that point whenever required.
Syntax: SAVEPOINT savepointname;
Ex: SAVEPOINT ss1;
SQL clauses
Order by clause: The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Syntax: SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Ex: SELECT * FROM Customers ORDER BY Country;
Where Clause: The WHERE clause is used to filter records.The WHERE clause is used to extract only those records that fulfill a specified
condition.
Syntax: SELECT column1, column2, ... FROM table_name WHERE condition;
Ex: SELECT * FROM Customers WHERE Country='Mexico';
GROUP BY CLAUSE
The SQL GROUP BY clause is used to group the result set based on common value present in the result set.
Syntax: SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s);
ORDER BY column_name(s);
Ex: SELECT Name, AVG(Mark) AS Average FROM Grades GROUP BY Name
Grades
Name Code Mark
Name Average
Teja FIT 56
Teja FOC 72 Teja 64
Durga FIT 60 Durga 57
Durga FOC 54 Malik 57
Malik FIT 60
Malik FOC 54
SQL Aggregate functions
• SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns a single value.
• It is also used to summarize the data.
Different Aggregate functions are as follows:
1. COUNT( ):COUNT() is used to Count the number of rows in a database table. It can work on both numeric and non-numeric data types.
Ex:SELECT COUNT(*) FROM Employee;
2. SUM( ) :Sum() is used to calculate the sum of all selected columns. It works on numeric fields only.
Ex: SELECT SUM(sal) FROM Employee;
3.AVG( ) :The AVG() is used to calculate the average value of the numeric type.
Ex: SELECT AVG(sal) FROM Employee;
Operator Description
= Equal to
> Greater than
Ex: SELECT sal from emp where sal>=5000;
< Less than
>= Greater than
equal to
<= Less than equal
to
<> Not equal to
3.Logical operators(AND,OR,NOT)
Set operators combine sets of rows returned by queries, instead of individual data items. All set operators have equal precedence.
UNION: Returns all distinct rows selected by either query.
Ex: Select * from emp1 UNION Select * from emp2;
• The DUAL is special one row, one column table present by default in all Oracle databases.
• The owner of DUAL is SYS (SYS owns the data dictionary, therefore DUAL is part of the data dictionary.) but DUAL can be accessed by every
user.
• The table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'.
4) SQL Unique Key:This constraint ensures that a column or a group of columns in each row have a distinct value. A column(s) can have a null value but the values cannot be
duplicated.
Ex:CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
deptname char(10),
age number(2),
salary number(10),
location char(10) UNIQUE);
5) SQL Check Constraint :This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint can be applied for a single column or a
group of columns.
Ex:CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
deptname char(10),
age number(2),
gender char(1) CHECK (gender in ('M','F')),
salary number(10),
location char(10));
SEQUENCES
• Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to produce unique values on demand.
• A sequence is a user defined schema bound object that generates a sequence of numeric values.
CREATE SEQUENCE
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value MAXVALUE maximum value ;
Ex: CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0 maxvalue 100 ;
MODIFY SEQUENCE
Ex: ALTER SEQUENCE sequence_1 INCREMENT 2 MAXVALUE 200;
DROP SEQUENCE
Ex: DROP SEQUENCE sequence_1;
SQL VIEW
Ex: CREATE VIEW Brazil_customers AS
SELECT CustomerName, Contact Name
FROM Customers
WHERE Country = 'Brazil';
CREATE OR REPLACE VIEW
Syntax: CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Ex:CREATE OR REPLACE VIEW [Brazil_customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
DROP VIEW
Syntax: DROP VIEW VIEW_NAME;
Ex: DROP VIEW Brazil_customers;
INDEXES
An index is a schema object. It Is used by the server to speed up the retrieval of rows by using a pointer.
Create an index
Syntax: CREATE INDEX index ON TABLE column;
Ex: CREATE INDEX EMP_ENAME_IDX ON EMP(ENAME);
Remove an index
Syntax: DROP INDEX index;
Ex: DROP INDEX EMP_ENAME_IDX;
SYNONYMS
It permits short names or alternative names for objects.
Create Synonym
Syntax: CREATE SYNONYM synonym_name FOR tablename;
Ex: CREATE SYNONYM D30 FOR Employee;
Remove Synonym
DROP SYNONYM D30;
Nested Query
• A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.
There are a few rules that subqueries must follow −
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its
selected columns.
• An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be
used to perform the same function as the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery.
Nested Query( cont…)
• An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
Basic SQL Join Types
There are four basic types of SQL joins:
1. INNER,
2. LEFT,
3. RIGHT AND
4. FULL.
• The easiest and most intuitive way to explain the difference between these four types is by using a Venn diagram, which shows all possible
logical relations between data sets.
• Let’s say we have two sets of data in our relational database: table A and table B, with some sort of relation specified by primary and foreign
keys.
• The result of joining these tables together can be visually represented by the following diagram:
• The extent of the overlap, if any, is determined by how many records in Table A match the records in Table B.
Depending on what subset of data we would like to select from the two tables, the four join types can be visualized by highlighting the
corresponding sections of the Venn diagram:
Select all records from Table A Select all records from Table A, Select all records from Table B, Select all records from Table A
and Table B, where the join along with records from Table B along with records from Table A and Table B, regardless of
condition is met. for which the join condition is for which the join condition is whether the join condition is
met (if at all). met (if at all). met or not.
STUDENT
STUDENTCOURSE
• The relationship between Student and Studentcourse table is specified with a common column ‘ROLL_NO’ , which is a primary key in Student table
and foreign key in Studentcourse table.
Inner Join
• This query will show the names and age of students enrolled in different courses.
• This would be a perfect fit for an inner join, since an inner join returns records at the intersection of the two tables.
Ex: SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student INNER JOIN StudentCourse ON Student.ROLL_NO =
StudentCourse.ROLL_NO;
Left Join
SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
Right Join
SELECT Student.NAME, StudentCourse.COURSE_ID FROM Student RIGHT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
Full Join
• For a list of all records from both tables, we can use a full join.
Ex: SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student FULL JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
ORACLE BUILT IN FUNCTIONS
1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric values as input and return numeric values as output. Few of the
Numeric functions are:
Examples
Function name Return Value
2) Character Functions:
Function Name Examples Return Value
Character or text functions are used to
manipulate text strings. LOWER(string_value) LOWER('GOOD MORNING') good morning
• These are functions that take values that are of datatype DATE as input and return values of datatypes DATE, except for the
MONTHS_BETWEEN function, which returns a number as output.
Function Name Examples Return Value
ADD_MONTHS ('16-Sep-
ADD_MONTHS ( ) 16-Dec-81
81', 3)
MONTHS_BETWEEN ('16-
MONTHS_BETWEEN( ) 3
Sep-81', '16-Dec-81')
Conversion Functions:
Function Name Examples Return Value
These are functions that help us to convert a value in one form to another form.
TO_CHAR (3000,
$3000
'$9999')
TO_CHAR () Monday, June
TO_CHAR (SYSDATE,
2008
'Day, Month YYYY')