0% found this document useful (0 votes)
111 views32 pages

Unit-III-SQL RDBMS: A Lalitha Associate Professor Avinash Degree College

- SQL is a language used to communicate with databases and manipulate the data within them. It allows users to store, retrieve, and modify data. - SQL commands are divided into DDL, DML, DCL categories. DDL includes CREATE, DROP, ALTER etc to define database schema. DML includes INSERT, SELECT, UPDATE, DELETE to manipulate data. DCL includes GRANT, REVOKE for access control. - SQL also supports clauses like WHERE, GROUP BY, ORDER BY. Aggregate functions like COUNT, SUM, AVG, MIN, MAX are used to perform calculations on data sets.

Uploaded by

lalitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views32 pages

Unit-III-SQL RDBMS: A Lalitha Associate Professor Avinash Degree College

- SQL is a language used to communicate with databases and manipulate the data within them. It allows users to store, retrieve, and modify data. - SQL commands are divided into DDL, DML, DCL categories. DDL includes CREATE, DROP, ALTER etc to define database schema. DML includes INSERT, SELECT, UPDATE, DELETE to manipulate data. DCL includes GRANT, REVOKE for access control. - SQL also supports clauses like WHERE, GROUP BY, ORDER BY. Aggregate functions like COUNT, SUM, AVG, MIN, MAX are used to perform calculations on data sets.

Uploaded by

lalitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit-III-SQL

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
);  

DESC: It is used to describe the table

Syntax: DESC table_name;

Ex: DESC EMPLOYEE;


DDL COMMANDS(CONT..)

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;  

RENAME: It is used to change the name of the selected table.


Syntax: RENAME TABLE tbl_name TO new_tbl_name;
Ex: RENAME TABLE emp_table to 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‘;  

DELETE: It is used to remove one or more row from a table.


Syntax: DELETE FROM table_name [WHERE condition];  
Ex: DELETE FROM javatpoint  WHERE Author="Sonoo";  

SELECT: It is used to retrieve data from a table in the database.


Syntax: SELECT column1, column2, ... FROM table_name;
Ex:SELECT CustomerName, City FROM Customers;
DCL Commands (Grant, Revoke)

• 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

REVOKE-withdraw user’s access privileges given by using the GRANT command.

Syntax:REVOKE privilege_name ON object_name FROM {User_name | PUBLIC | Role_name}


Ex:REVOKE SELECT ON employee FROM user1
TCL(Commit , Rollback, Savepoint)

COMMIT command is used to permanently save any transaction into the database.


Syntax: COMMIT;
Ex: COMMIT;

ROLLBACK: This command restores the database to last committed state.


Syntax: ROLLBACK;
Ex: ROLLBACK;

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;

4. MAX( ):MAX( ) is used to find the maximum value of a certain column.


Ex: SELECT MAX(sal) FROM Employee;

5. MIN( ):MIN() is used to find the minimum value of a certain column.


Ex: SELECT MIN(sal) FROM Employee;
SQL operators
Different types of operators are:
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Set Operators
1.Arithmetic operators: are the operators which are used for mathematical calculation like addition, subtraction etc.

Operator Description Example

Adds values on both sides of SELECT sal+1000 from emp


+ (Addition)
the operator. where sal<5000;

SELECT cost-100 from


Subtracts values on right
product where
-(Subtraction) side from the value on left
prod_name=‘keyboard’;
side of the operator.

Multiplies the values on both


*(Multiplication) SELECT sal* 5 from emp;
sides of the operator

Divides left hand side value


/(Division) SELECT sal/ 10 from emp;
by right hand side value.
2.Comparison Operators

A comparison operator is a mathematical symbol which is used to compare two values.

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)

"OR" Logical Operator:


If you want to select rows that satisfy at least one of the given conditions, you can use the logical operator, OR.
EX:SELECT first_name, last_name, subject FROM student_details WHERE subject = 'Maths' OR subject = 'Science‘

"AND" Logical Operator:


If you want to select rows that must satisfy all the given conditions, you can use the logical operator, AND.
EX:SELECT first_name, last_name, age FROM student_details WHERE age >= 10 AND age <= 15;

"NOT" Logical Operator:


If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results in the reverse of a condition. That is, if a
condition is satisfied, then the row is not returned.
EX:SELECT first_name, last_name, games FROM student_details WHERE NOT games = 'Football‘;
4.Set operators

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;

UNION ALL: Returns all distinct rows selected by either query.


Ex: Select * from emp1 UNION ALL Select * from emp2;

INTERSECT: Returns all distinct rows selected by either query.


Ex: SELECT * from orders_list1 INTERSECT SELECT * FROM order_list2;

INTERSECT ALL: Returns all distinct rows selected by either query.


Ex: SELECT * from orders_list1 INTERSECT ALL SELECT * FROM order_list2;

MINUS: Returns all distinct rows selected by either query.


Ex: Select * from emp1 MINUS Select * from emp2;
What is DUAL table?

• 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'.

The structure of DUAL table :


DESC DUAL;
Name Null? Type –
-------------------------- ------
DUMMY VARCHAR2(1)

The following command displays the content of the DUAL table :


SELECT * FROM DUAL;
You can also check the system date from the DUAL table using the following statement :
SELECT sysdate FROM DUAL ;
SYSDATE
---------
11-DEC-10
SQL INTEGRITY CONSTRAINTS
1) SQL Primary key: This constraint defines a column or combination of columns which uniquely identifies each row in the table.
Ex: CREATE TABLE employee
( EMPid number(5) PRIMARY KEY,
name char(20),
deptname char(10),
age number(2),
salary number(10),
location char(10)
);
2) SQL Foreign key or Referential Integrity :This constraint identifies any column referencing the PRIMARY KEY in another table. It establishes
a relationship between two columns in the same table or between different tables. 
Ex:CREATE TABLE employee
(EMPid number(5) PRIMARY KEY,
name char(20),
deptname char(10),
age number(2),
Mgr_id number(5) REFERENCES employee(id),
salary number(10),
location char(10)
);
SQL INTEGRITY CONSTRAINTS(cont…)
3) SQL Not Null Constraint :This constraint ensures all rows in the table contain a definite value for the column which is specified as not null. Which means a null value is
not allowed.
Ex: CREATE TABLE employee
( empid number(5),
name char(20) NOT NULL,
deptname char(10),
age number(2),
salary number(10),
location char(10));

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

• In SQL, a view is a virtual table based on the result-set of an SQL statement.


• A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
CREATE VIEW
Syntax: CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

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…)

Subqueries with the SELECT Statement:


• Subqueries are most frequently used with the SELECT statement.
• The subquery (inner query) executes once before the main query (outer query) executes.
• The main query (outer query) use the subquery result.
syntax: SELECT select_list FROM TABLE WHERE EXPR OPERATOR (SELECT select_list FROM table);
Ex: SELECT ID,FIRST_NAME FROM STUDENT_DETAILS WHERE FIRST_NAME IN
(SELECT FIRST_NAME FROM STUDENT_DETAILS WHERE SUBJECT=“SCIENCE”);
Subqueries with the INSERT Statement:
Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data
in the subquery can be modified with any of the character, date or number functions.
syntax: INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ];
Ex: INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN
(SELECT ID FROM CUSTOMERS) ;
Subqueries with the UPDATE Statement:
• The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the
UPDATE statement.
syntax :UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME)
[WHERE];
Ex: UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN
(SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
SQL JOINS

• 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

ABS (x) Absolute value of the number 'x' ABS(-1)=1


CEIL(2.83)=3
Integer value that is Greater than or
CEIL (x)
equal to the number 'x'
FLOOR(2.83)=2
Integer value that is Less than or equal
FLOOR (x)
to the number 'x'
TRUNC(125.456,1)=125.4
Truncates value of number 'x' up to 'y'
TRUNC (x, y)
decimal places
ROUND(140.234,2)
Rounded off value of the number 'x' up to
ROUND (x, y)
the number 'y' decimal places

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

UPPER(string_value) UPPER(‘good morning') GOOD


MORNING
LTRIM(string_value, trim_text) LTRIM ('Good Morning', 'Good’) Morning
RTRIM ('Good Morning', '
RTRIM (string_value, trim_text) Good
Morning')
SUBSTR (string_value, m, n) SUBSTR ('Good Morning', 6, 7) Morning
LENGTH (string_value) LENGTH ('Good Morning') 12
LPAD (string_value, n, pad_value) LPAD ('Good', 6, '*') **Good
RPAD (string_value, n, pad_value) RPAD ('Good', 6, '*') Good**
Date functions

• 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')

NEXT_DAY( ) NEXT_DAY ('01-Jun-08', 04-JUN-08


'Wednesday')

LAST_DAY( ) LAST_DAY ('01-Jun-08') 30-Jun-08

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')

TO_DATE () TO_DATE ('01-Jun-08') 01-Jun-08

NVL () NVL (null, 1) 1


THANK YOU

You might also like