You are on page 1of 27

RDBMS UNIT III BCOM III SEM

STRUCTURES QUERY LANGUAGE (SQL): Meaning – SQL commands - Data Definition Language
- Data Manipulation Language - Data Control Language - Transaction Control Language - Queries
using Order by – Where - Group by - Nested Queries. Joins – Views – Sequences - Indexes and
Synonyms - Table Handling

Introduction to SQL

SQL is a language which is used to interact with relational database management system.

Q1)What is a database

Database is a organized collection of data. For example a database of a college would be having a
collection of data such as –
1. Personal records of Students
2. Student’s performance history
3. Teacher’s data
4. Financial department data etc.

Database Management System (DBMS)

A database management system is a software application which is used for managing different
databases. It helps us to create and manage database. With the help of DBMS we take care following
tasks –
1. Data Security
2. Data Backup
3. Manages huge amount of data
4. Data export & import
5. Serving multiple concurrent database requests
6. Gives us a way to manage the data using programming languages.

Types of Databases

There are two types of databases –


1. Relational Database
2. Non-relational Database

Non-relational databases:

Data is not organized in form of tables. Data is stored in form of key & value pairs. The examples of
non-relational databases are: JSON & XML.

We cannot interact with non-relational databases using SQL.

Shweta K /Swapna A Page 1


RDBMS UNIT III BCOM III SEM
Relational Databases:

In relational database, data is organized in form of tables. A table contains rows and columns of
data. Table has a unique key to identify each row of the table.

SQL is used to interact with relational databases. We often refer relational database as SQL
database.

Q2) What is SQL?


A)
▪ SQL stands for Structured Query Language.
▪ It is designed for managing data in a relational database management system (RDBMS).
▪ SQL is a database language, it is used for database creation, deletion, fetching rows and
modifying rows etc.
▪ SQL has reduced the need for lengthy programming to access data.
▪ The SQL user does not need to know how data is stored. The query language (SQL) takes care
of retrieving, replacing, adding, and deleting data.
▪ A procedural programming language needs every specification about data. SQL is simpler in
operation than procedural languages like C/C++ for database management.
▪ DBMS like MySQL, Oracle, MS Access, Sybase, Informix, Postgres and SQL Server use SQL as
standard database language.

Why SQL is required?


SQL is required:
▪ To create and drop databases and tables.
▪ To Update, Retrieve, Delete, records in a database.
▪ To set permissions on tables, procedures and views.
▪ To define the data in a database and manipulate that data.
▪ To access data in the relational database management systems.
▪ To create view, stored procedure, functions in a database.

Shweta K /Swapna A Page 2


RDBMS UNIT III BCOM III SEM

Brief History of SQL

Here, are important landmarks from the history of SQL:

• 1970 - Dr. Edgar F. "Ted" Codd described a relational model for databases.
• 1974 - Structured Query Language appeared.
• 1978 - IBM released a product called System/R.
• 1986 - IBM developed the prototype of a relational database, which is standardized by ANSI.
• 1989- First ever version launched of SQL
• 1999 - SQL 3 launched with features like triggers, object-orientation, etc.
• SQL2003- window functions, XML-related features, etc.
• SQL2006- Support for XML Query Language
• SQL2011-improved support for temporal databases

Q3) What is schema?


A database schema is considered the “blueprint” of a database which defines how data is organized within a
relational database; this is inclusive of logical constraints such as, table names, fields, data types, and the
relationships between these entities. However, the schema does not actually contain data.

Q 4)What is a Query ?

A) A Query is a set of instruction given to the database management system, which tells RDBMS
what information you would like to get from the database. For e.g. to fetch the employee name from
the database table EMPLOYEE, we write the SQL Query like this:

SELECT employee_namefrom EMPLOYEE;

Shweta K /Swapna A Page 3


RDBMS UNIT III BCOM III SEM

Q5: Explain SQL Data types.


• The data type is a label and a guideline for SQL to understand what type of data is expected
inside of each column.

Data type Explanation


This Data type used to store characters of fixed length. The size in the
brackets determines the number of characters. The maximum n.of
characters this data type can hold is 255.
Synatax:-
char <Columnname > char(size)
Example:-
Studentname char(20)
The term varchar refers to a data type of a field (or column) in a database
management system which can hold letters and numbers. Maximum of
8,000 characters. For example, VARCHAR(n) can accept any length of
Varchar character string up to n characters in length
Syntax:-
<Columnname> varchar(size)
Example:
StudentName varchar(20)
Exact numerical, precision p, scale s. The maximum precision depends
on the DBMS. For example, the number 1234.56 has a precision of 6, a
Number(p.s) scale of 2. and would be defined as NUMBER(6,2).
Syntax:
<Columnname> number(size)
Example:
StudPercentage number (20)
The TIME data type accepts time values. No parameters are required
when declaring a TIME data type. TIME values should be specified in the
form: HH-MM:SS.
Time Syntax:-
<Columnname> time
Example:-
TimeofAdmit Time

The DATE data type accepts date values. No parameter are required
when declaring a DATE datatype. DATE values should be specified in the
form: MM-DD-YY.
Syntax:-
<columnname> DATE
Example:-
DOB Date
Date
Create table TABLENAME(Rno number(10), name varchar(10),DOJ date,JoiningTime
Time);

Shweta K /Swapna A Page 4


RDBMS UNIT III BCOM III SEM

Types of SQL Commands

Q6) What is a SQL? Explain types of SQL COMMANDS with example.


A) SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is the
standard language for relational database management systems. SQL statements are used to
perform tasks such as update data on a database, or retrieve data from a database.
Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft
SQL Server, Access, Ingres, etc. Most database systems use SQL.

There are five types of SQL commands:

1. Data Definition Language (DDL)

2. Data Manipulation Language (DML)

3. Data Control Language (DCL)

4. Transaction Control Language (TCL), and

5. Data Query Language (DQL)

Shweta K /Swapna A Page 5


RDBMS UNIT III BCOM III SEM

v.v.IMP Q7) Explain Data Definition Language (DDL)


A) 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:

I. CREATE
II. ALTER
III. DROP
IV. TRUNCATE
V. RENAME

I.CREATE
The "create" command is used to create Tables. It defines each column of the table uniquely. In SQL
each column has minimum of 3 attributes.
1. Name
2. Data type
3. Size(size means column width)
Each column name is separated from the other by a comma. Finally the SQL statement is terminated
with a semicolon;

Syntax:-
create table TABLENAME(columnName1 datatype(size), columnName2
datatype(size)....... columnNameN datatype (size));

Example:-
Create table STUDENT (rno number(10), name varchar(20), age
number(10));

The above query creates a table with the name "STUDENT’’ and with the given column
names(rno,name,age)

II. ALTER
ALTER command is used for altering the table structure, such as,
• to add a column to existing table
• to rename any existing column
• to change datatype of any column or to modify its size.
• to drop a column from the table.

ALTER Command: Add a new Column

Shweta K /Swapna A Page 6


RDBMS UNIT III BCOM III SEM
syntax,
ALTER TABLE table_name ADD(column_name datatype(size));

Example
ALTER TABLE student ADD(address VARCHAR(200));

The above command will add a new column address to the table student, which will hold data of
type varchar of length 200.

III. TRUNCATE
TRUNCATE command removes all the records from a table. But this command will not destroy the
table's structure. When we use TRUNCATE command on a table its (auto-increment) primary key is
also initialized.
Syntax,
TRUNCATE TABLE table_name;

Example
TRUNCATE TABLE student;
The above query will delete all the records from the table student.

IV.DROP
DROP command completely removes a table from the database. This command will also destroy the
table structure and the data stored in it.
Syntax,
DROP TABLE table_name;

Example
DROP TABLE student;
The above query will delete the Student table completely. It can also be used on Databases, to
delete the complete database. For example, to drop a database,

V .RENAME
This command is used to set a new name for any existing table.
Syntax
RENAME TABLE old_table_name to new_table_name;

Example
RENAME TABLE student to students_info;
The above query will rename the table student to students_info.

Shweta K /Swapna A Page 7


RDBMS UNIT III BCOM III SEM

V.IMP Q8) Data Manipulation Language(DML)


o DML commands are used to modify the database. It is responsible for all form of changes in
the database.
o 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:

I. INSERT
II. UPDATE
III. DELETE

I. INSERT: Insert command is used to insert data into a table.

Syntax:-
Insert into TABLENAME values(data1,data2,data3,………);

Example:-
Insert into STUDENT values(101,’RAM’,35);

The above command will insert a record into STUDENT table.


Rno Name Age
101 Ram 35

• Insert value into only specific columns

We can use the INSERT command to insert values for only some specific columns of a row. We can
specify the column names along with the values to be inserted like this,

INSERT INTO student(Rno, Name) values(102, 'Alex');

The above SQL query will only insert id and name values in the newly inserted record.

II.UPDATE
UPDATE command is used to update any record of data in a table. Following is its general syntax,

UPDATE table_name SET column_name = new_value WHERE some_condition;

WHERE is used to add a condition to any SQL query, we will soon study about it in detail.

Shweta K /Swapna A Page 8


RDBMS UNIT III BCOM III SEM
Lets take a sample table student,

S_id Name Age


101 Adam 15
102 Alex 20
103 chris 14

UPDATE student SET Age=18 WHERE student_id=102;

S_id Name Age


101 Adam 15
102 Alex 18
103 chris 14
In the above statement, if we do not use the WHERE clause, then our update query will update age
columns of 102 S_id to 18.

UPDATE Command: Incrementing Integer Value

UPDATE student SET age = age+1;

As you can see, we have used age = age + 1 to increment the value of age by 1.

III.DELETE
DELETE command is used to delete data from a table.

Syntax:

DELETE FROM table_name;

Example: Delete all Records from a Table

DELETE FROM student;

Example: Delete a particular Record from a Table

DELETE FROM student WHERE s_id=103;

Shweta K /Swapna A Page 9


RDBMS UNIT III BCOM III SEM

Q9)DATA QUERY LANGUAGE(DQL)


SELECT SQL Query
SELECT query is used to retrieve data from a table. It is the most used SQL query. We can retrieve
complete table data, or partial by specifying conditions using the WHERE clause.

Syntax of SELECT query

SELECT column_1,column_2,column_3,column_n FROM table_name;


Consider the following student table,

s_id name age address


101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai

SELECT s_id, name, age FROM student;


Output is

s_id name age


101 Adam 15
102 Alex 18
103 Abhi 17
104 Ankit 22

Select all records from a table

A special character asterisk * is used to address all the data(belonging to all columns) in a
query. SELECT statement uses * character to retrieve all records from a table, for all the columns.

SELECT * FROM student;

s_id name age address


101 Adam 15 Chennai
102 Alex 18 Delhi
103 Abhi 17 Banglore
104 Ankit 22 Mumbai

Select a particular record based on a condition: We can use the WHERE clause to set a
condition,
SELECT * FROM student WHERE name = 'Abhi';
103 Abhi 17 Rohtak

you can also perform simple mathematical operations on the data too using the SELECT query to
fetch data from table.

Shweta K /Swapna A Page 10


RDBMS UNIT III BCOM III SEM

Q10) Explain DATA CONTROL LANGUAGE(DCL)


These SQL commands are used for providing security(privileges)(Authorization) to database
objects (tables). These commands are GRANT and REVOKE.
Grant
This command is used to give user access privileges to database.
(A) To allow a user to create table

Grant create table to username;

(B) To grant permission to create any table

Grant create any table to username;


(C) To grant permission to DROP any table

Grant drop any table to username;


Revoke
This command is used to take back permissions from user.
(A) To take back permissions

revoke create table from username;

Q11) TRANSACTION CONTROL LANGUAGE(TCL)


Transaction Control Language(TCL) commands are used to manage transactions in the database.
These are used to manage the changes made to the data in a table by DML statements. It also allows
statements to be grouped together into logical transactions.
These commands are COMMIT, SAVEPOINT, ROLLBACK.
COMMIT : Commit command is used to permanently save any transaction into database.
Syntax:-
Commit;
SAVEPOINT :Save point command is used to temporarily save a transaction so that you can
rollback to that point whenever necessary.
Syntax:-
Savepoint savepointname;
Example:-
Savepoint X;

ROLLBACK

Shweta K /Swapna A Page 11


RDBMS UNIT III BCOM III SEM
This command restores the database to last committed state. It is also use with savepoint command
to jump to a savepoint in a transaction.
Syntax:-
Rollback to savepointName;
Example:-
Rollback to X;

{EXAMPLE :Working of Savepoint and Rollback


(Note: just for understanding purpose no need to write in exam)

Following is the table class,


id name
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
INSERTINTO class VALUES(5,'Rahul');

COMMIT;
UPDATE class SET name ='Abhijit'WHERE id ='5';
SAVEPOINT A;
INSERTINTO class VALUES(6,'Chris');
SAVEPOINT B;
INSERTINTO class VALUES(7,'Bravo');
SAVEPOINT C;
SELECT*FROM class;

NOTE: SELECT statement is used to show the data stored in the table.
The resultant table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to the savepoint B.

ROLLBACK TO B;

SELECT * FROM class;

Shweta K /Swapna A Page 12


RDBMS UNIT III BCOM III SEM

Now our class table will look like,


id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to the savepoint A
ROLLBACKTO A;
SELECT * FROM class;
Now the table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
So now you know how the commands COMMIT, ROLLBACK and SAVEPOINT works.}

Q12) Explain clauses in SQL


1. WHERE Clause
WHERE Clause is used to specify condition, while retrieving data from table.WHERE Clause is used
mostly with SELECT, UPDATE and DELETE Query.
Syntax:

SQL>Select * from Table_name where condition;

Example:
Consider the following table-STUDENT
Rno. Name Age Address
1 Ram 18 Hyderabad
2 Ali 17 Secunderabad
3 John 16 Chennai
4 Goutham 15 Mumbai

SQL>Select * from STUDENT where mo=1;


Rno. Name Age Address
1 Ram 18 Hyderabad

Shweta K /Swapna A Page 13


RDBMS UNIT III BCOM III SEM

2.LIKE CLAUSE

LIKE clause is used in the condition in SQL query with the WHERE clause. LIKE clause compares
data with an expression using wildcard operators to match pattern given in the condition.
There are two wildcard operators that are used in LIKE clause.

• Percent sign %: represents zero, one or more than one character.


• Underscore sign _: represents only a single character.

Consider the following Student table.


s_id s_Name age
101 Adam 15
102 Alex 18
103 Abhi 17
104 Eric 18

Example 1
SELECT * FROM Student WHERE s_name LIKE 'A%';
The above query will return all records where s_name starts with character 'A'.
s_id s_Name age
101 Adam 15
102 Alex 18
103 Abhi 17

Example 2
SELECT*FROM Student WHERE s_name LIKE'_d%';
The above query will return all records from Student table where s_name contain 'd' as second
character.
s_id s_Name age
101 Adam 15

3. ORDER BY Clause
Order by clause is used with SELECT statement ,and it is used to sort the data in ascending (or)
descending order. SQL sorts query results in ascending order by default.To sort data in descending
order DESC keyword is used with Order by clause
Syntax
SELECT column-list|* FROM table-name ORDER BY ASC | DESC;

Consider the following Emp table

Eid Name Salary

Shweta K /Swapna A Page 14


RDBMS UNIT III BCOM III SEM
1 Ram 5000
2 Srivani 3000
3 Ganesh 9000

Example: 1
SQL>Select * from EMPLOYEE order by salary; Eid Name Salary
The above query will return result in ascending order of the salary. 2 Srivani 3000
1 Ram 5000
3 Ganesh 9000
Example: 2
SQL>Select * from EMPLOYEE order by salary DESC;
Eid Name Salary
The above query will return result in ascending order of the 3 Ganesh 9000
salary. 1 Ram 5000
2 Srivani 3000

4.Group by Clause
Group by clause is used to group the results of a SELECT query based on one or more columns. It
is also used with SQL functions to group the result from one or more tables.

Syntax for using Group by in a statement.

SELECTcolumn_name,function(column_name) FROMtable_nameWHERE condition


GROUPBYcolumn_name;

Example: Consider the following Emp table.


EID NAME DEPT SALARY
101 Ram Computers 53000
103 Dhanvi Commerce 43000
102 Srivani Commerce 33000
104 Ganesh Computers 28000

DEPT SALARY
SQL>Select dept, sum(salary)from EMP GROUP BY dept;
Computers 81000
Commerce 76000

5. HAVING Clause
Having clause is used with SQL Queries to give more precise condition for a statement. It is used to
mention condition in Group by based SQL queries, just like WHERE clause is used
with SELECT query.

SYNTAX
Shweta K /Swapna A Page 15
RDBMS UNIT III BCOM III SEM
SELECT column, function(column) FROM table_name WHERE column condition
GROUP BY column HAVING function(column) condition

The HAVING clause must follow the GROUP BY clause in a query and must also precedes the
ORDER BY clause if used.
Example
EID NAME DEPT SALARY
101 Ram Electronics 55000
103 Dhanvi Aeronautics 35000
102 Srivani Electronics 20000
104 Ganesh Info Tech 30000

If you want to select the department that has total salary paid for its employees more than 25000,
the SQL query would be like;

SELECT dept, SUM(salary)from EMPLOYEE GROUP BY dept HAVING


SUM (salary)>25000;
The output would be like:
Dept Salary
Electronics 55000
Aeronautics 35000
InfoTech 30000

When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the
WHERE clause is processed first, then the rows that are returned after the WHERE clause is
executed are grouped based on the GROUP BY clause.

Q13) Explain VIEWS


A VIEW in SQL is a logical subset of data from one or more tables. 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. View is used to restrict data access

Creating a VIEW

Syntax

CREATE VIEW view_name AS SELECT column_name(s) FROM table_name


WHERE condition;
Consider following Sale table,

oid order_name previous_balance customer

Shweta K /Swapna A Page 16


RDBMS UNIT III BCOM III SEM
11 ord1 2000 Alex
12 ord2 1000 Adam
13 ord3 2000 Abhi
14 ord4 1000 Adam
15 ord5 2000 Alex
SQL Query to Create a View from the above table will be,

CREATE VIEW sale_view AS SELECT * FROM Sale WHERE customer = 'Alex';


The data fetched from SELECT statement will be stored in another object called sale_view.

Operations on view
(1)Displaying the rows from the view:
Syntax:
Select * from view_name;
Example:
Select * from sale_view;

(2)Updating views:-
Syntax:
Update viewname set condition where condition;
Example:
Update sale_view set customer=’Adam’ where oid=11;

(3) Inserting values into view:-


Syntax:
Insert into viewname values(value1,value2…);
Example:
Insert into sale_view values(16,’ord6’,);

(4)Deleting values from views:-


Syntax:
Delete from viewname where condition;
Example:
Delete from sale_view where oid=11;
(5)Dropping views:-
Syntax:
Drop view viewname;
Example:
Drop view sale_view;

Read-Only VIEW:We can create a view with read-only option to restrict access to the view.

Syntax

Shweta K /Swapna A Page 17


RDBMS UNIT III BCOM III SEM
CREATE FORCE VIEW view_name AS SELECT column_name(s) FROM table_name
WHERE condition WITH read-only;
The above syntax will create view for read-only purpose, we cannot Update or Insert data into
read-only view. It will throw an error.

Q14) What are SQL Functions?


A) SQL provides many built-in functions to perform operations on data. These functions are useful
while performing mathematical calculations, string concatenations, sub-strings etc. SQL functions
are divided into two
categories,
SNo. Aggregate
1. Aggregate Functions
Functions 1 Count() Calculates no. of records in a column.
2 Min() Finds minimum value of the column.
3 Sum() Calculates sum of the values in a column.
4 Avg() Calculates average of a column.
5 Max() Finds maximum value of the column.

SNo. String
Functions
2. Scalar Functions 1 Upper( ) Converts the given column to capital letters.
2 Lower( ) Converts the given column to small lettres
3 initcap( ) Makes first letter capital for all text values in
the column.
4 Concat( ) The CONCAT function combines two or more
Strings into one string.
5 Length( ) The LENGTH( ) Function returns Number of
character in string.
6 Round() used to round a numeric field to number of nearest
integer

Aggregate Functions: These functions return a single value after performing


calculations on a group of values. Following are some of the frequently used Aggregate
functions.

Consider the following Emp table


Eid name age salary
401 Anu 22 9000
402 Shane 29 8000
403 Rohan 34 6000
404 Scott 44 10000
405 Tiger 35 8000

1. AVG() Function: Average returns average value after calculating it from values in a numeric
column.
syntax
SELECT AVG(column_name) FROM table_name

Shweta K /Swapna A Page 18


RDBMS UNIT III BCOM III SEM

Example
SELECT avg(salary) from Emp;
avg(salary)
8200

2.COUNT() Function: Count returns the number of rows present in the table either based on
some condition or without condition.
syntax,
SELECT COUNT(column_name) FROM table-name;
Example
SELECT COUNT(name) FROM Emp WHERE salary = 8000;
count(name)
2

3. COUNT(distinct): DISTINCT clause eliminates the repetitive appearance of the same data.

Example
SELECT COUNT(DISTINCT salary) FROM emp;
o/p
count(distinct salary)
4

4.MAX() Function
MAX function returns maximum value from selected column of the table.
Syntax
SELECT MAX(column_name) from table-name;
Example

SELECT MAX(salary) FROM emp;


MAX(salary)
10000

5.MIN() Function: MIN function returns minimum value from a selected column of the table.

Syntax
SELECT MIN(column_name) from table-name;

Example
SELECT MIN(salary) FROM emp;
MIN(salary)
6000

6.SUM() Function
SUM function returns total sum of a selected columns numeric values.

Shweta K /Swapna A Page 19


RDBMS UNIT III BCOM III SEM
Syntax
SELECT SUM(column_name) from table-name;

Example
SELECT SUM(salary) FROM emp;
SUM(salary)
41000

Scalar Functions
Scalar functions return a single value from an input value. Following are some frequently used
Scalar Functions in SQL.

1.UPPER() Function
UPPER function is used to convert value of string column to Uppercase characters.

Syntax
SELECT UPPER(column_name) from table-name;

Example
SELECT UPPER(name) FROM emp;
UPPER(name)
ANU
SHANE
ROHAN
SCOTT
TIGER

2.LOWER() Function
LOWER function is used to convert value of string columns to Lower case characters.

Syntax
SELECT LOWER(column_name) FROM table-name;
Example
SELECT LCASE(name) FROM emp;
LOWER(name)
anu
shane
rohan
scott
tiger

3.Initcap() Function :The initcap( ) function is used to make the first letter capital values of the
selected fields in the given column:
Syntax:

Shweta K /Swapna A Page 20


RDBMS UNIT III BCOM III SEM
Select initcap(columnName) from Tablename;
Example:
Select initcap(Name) from EMPLOYEE;
OUTPUT:-
Initcap(name)
Anu
Shane
Rohan
Scott
Tiger

4. Concat () Function:The CONCAT function combines two or more strings into one string.
Syntax:
Select CONCAT(column1,column2) from TABLENAME;
Example:
Select CONCAT(eno,name) from employee;
OUTPUT:-
CONCAT(ENO,'NAME')
101Anu
102Shane
103Rohan
104Scott
105Tiger

5.Length() Function: The LENGTH( ) function returns Number of characters in string


Syntax:
SQL>select Length(column) from tablename;
Example:
SQL> Select Length(name) from employee;
OUTPUT:-
LENGTH(name)
3
5
5
5
5
6.ROUND() Function:ROUND function is used to round a numeric field to number of nearest
integer. It is used on Decimal point values.
Syntax
SELECT ROUND(column_name, decimals) from table-name;

Shweta K /Swapna A Page 21


RDBMS UNIT III BCOM III SEM

Using ROUND() function


Consider the following Emp table

eid name age salary


401 anu 22 9000.67
402 shane 29 8000.98
403 rohan 34 6000.45
404 scott 44 10000
405 Tiger 35 8000.01
SQL query is,

SELECT ROUND(salary) from emp;


Result will be,

ROUND(salary)
9001
8001
6000
10000
8000

Q15) Explain SQL JOINS in detail.


A SQL joins is a structural query language(SQL) instruction to combine data from two tables. A join
is a means for combining fields from two tables by using values common to each other
There are four types of SQL joins:
They are:
1. Inner join
2. Left outer join
3. Right outer join
4. Full outer join
Consider following two tables CUSTOMER AND ORDER
CUSTOMER
Cid name address ORDER
10 Ram Hyderabad orderid orderdate cid
20 Shyam Secundrabad 1 18/08/2016 40
30 Dhanvi Chennai 2 27/09/2016 20
40 Sai Goa 3 22/09/2016 50
50 Ganesh Null 4 24/10/2016 10
60 Harsha Vizag 5 10/10/2016 null

1. INNER JOIN:

Shweta K /Swapna A Page 22


RDBMS UNIT III BCOM III SEM
This is most common type of SQL join and also called EQUI join. SQL inner join returns all rows
from multiple tables where the join condition is meet.
Inner join

Syntax:

Select columns from TABLEA Inner join TableB on TableA.column=TableB.column;

Example:

Select customerid, order.orderid, orders.orderdate from CUSTOMERS innerjoin ORDER ON


cutomerid.cid=order.cid order by customer.cid;

This example would return all rows from the CUSTOMER and ORDER tables where there is
matching cid values in both the CUSTOMERS and ORDER tables
Output:
cid orderid orderdate
10 4 24/10/2016
20 2 27/09/2016
40 1 18/08/2016
50 3 22/09/2016

2.LEFT OUTER JOIN


The left outer join returns a resultset table with the matched data from the two tables and then the
remaining rows of the left table and null from the right table's columns.
Left join

Syntax:

Select columns from TABLEA LEFT OUTER JOINTableB on TableA.column=TableB.column;

Example:

Select customerid , order.orderid, orders.orderdate from CUSTOMERS LEFT OUTER


joinORDER ON cutomerid.cid=order.cidorder bycustomer.cid;

Shweta K /Swapna A Page 23


RDBMS UNIT III BCOM III SEM
Output:
cid orderid orderdate
10 4 24/10/2016

20 2 27/09/2016

30 NULL NULL
40 1 18/08/2016
50 3 22/09/2016
60 NULL NULL

3.RIGHT OUTER JOIN


The right outer join returns a resultset table with the matched data from the two tables being
joined, then the remaining rows of the right table and null for the remaining left table's columns.

Right join

Syntax:

Select columns from TABLEA RIGHT OUTER JOINTableB on TableA.column=TableB.column;

Example:

Select customerid , order.orderid, orders.orderdate from CUSTOMERS RIGHT OUTER JOIN


ORDER ON cutomerid.cid=order.cid order by customer.cid;

Output:
Orderid Orderdate Cid
5 10/10/2016 NULL

4 24/10/2016 10
2 27/9/2016 20
1 18/8/2016 40
3 22/9/2016 50

4.FULL OUTER JOIN:


The full outer join returns a resultset table with the matched data of two table then remaining
rows of both left table and then the right table.

Shweta K /Swapna A Page 24


RDBMS UNIT III BCOM III SEM
Full outer join

Syntax:

Select columns from TABLEA FULL OUTER JOINTableB on TableA.column=TableB.column;

Example:

Select customer.cid, order.orderid, orders.orderdate from CUSTOMERS FULL OUTER JOIN


ORDER ON cutomer.cid=order.cid order by customer.cid;

Q16) What is an SQL Sequence?


A) Sequence is a feature supported by some database systems to produce unique values on
demand. Some DBMS like MySQL supports AUTO_INCREMENT in place of Sequence.

AUTO_INCREMENT is applied on columns, it automatically increments the column value by 1 each


time a new record is inserted into the table.

Sequence is also some what similar to AUTO_INCREMENT but it has some additional features too.

Creating a Sequence
Syntax

CREATE SEQUENCE sequence-name STARTWITH initial-value INCREMENT BY increment-value


MAXVALUE maximum-value CYCLE| NOCYCLE;
• The initial-value specifies the starting value for the Sequence.
• The increment-value is the value by which sequence will be incremented.
• The maximum-value specifies the upper limit or the maximum value upto which sequence
will increment itself.
• The keyword CYCLE specifies that if the maximum value exceeds the set limit, sequence will
restart its cycle from the begining.
• And, NO CYCLE specifies that if sequence exceeds MAXVALUE value, an error will be
thrown.

Using Sequence in SQL Query


Let's start by creating a sequence, which will start from 1, increment by 1 with a maximum value
of 999.
CREATE SEQUENCE seq_1 START WITH 1 INCREMENT BY 1 MAXVALUE 999
CYCLE;
Below we have a class table,

ID NAME

Shweta K /Swapna A Page 25


RDBMS UNIT III BCOM III SEM
1 abhi
2 adam
4 alex
The SQL query will be,

INSERT INTO class VALUES(seq_1.nextval,'anu');


Resultset table will look like,

ID NAME
1 abhi
2 adam
4 alex
5 anu
Once you use nextval the sequence will increment even if you don't Insert any record into the table.

Q17 )explain INDEX


The create index statement is used to create indexes in the table
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.
Syntax:

Create IndexName ON TABLENAME(Clumn1, coulumn2,….);

Example:

Create Idxpname ON persons(LastName, FirstName);

Q:- What is Query?


A Query is a command to perform specific task over database to generate certain information from
the table

Q18):- What is Nested Query?


Nested Query:
• Nested Query also Known as inner queries (or) Sub queries.
• Nested Query is another query within SQL Query and embedded (Surrounded) within the
WHERE clause
• Nested Queries are a tool of performing operations in multiple steps.
• SQL executes innermost sub query first, then next level.
Rules
✓ Subqueries must be enclosed within parentheses.
✓ A subquery can have only one column in the SELECT clause
✓ Nested queries are most frequently used with the SELECT statement

Shweta K /Swapna A Page 26


RDBMS UNIT III BCOM III SEM
Syntax:

Select ColumnName, From TABLENAME Where ColumnName Operator (Select ColumnName from
TABLENAME);

Eno. Ename DOJ Salary Dept

1 Shakthi 10-march-96 12000 Marketing


2 Kranthi 11-april-87 15000 Sales
3 Khyathi 12-may-91 9000 EDP
4 Preethi 13-june-98 20000 Sales
5 Keerthi 28-aug-89 10000 Finances

Example:-

Select * from EMPLOYEE where salary=(Select min(Salary) from EMPLOYEE);

Here sub query finds out who is getting minimum salary


Output:

Eno. Ename DOJ Salary Dept

3 Khyathi 12-may-91 9000 EDP

Shweta K /Swapna A Page 27

You might also like