0% found this document useful (0 votes)
15 views

Module 4

Uploaded by

sohamniwate90
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Module 4

Uploaded by

sohamniwate90
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

Chapter-4

Structured Query Language


(SQL) & Indexing
4.1.Overview of SQL
DDL,DML,DCL,TCL
4.2. Set and String operations, aggregate
function-group by, having.
Views in SQL, joins, Nested and
Complex queries, Integrity
constraints-key constraints, domain
constraints, Referential integrity,
check constraints, Triggers
Overview of SQL
• 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, Sybase, Informix, Postgres and
SQL Server use SQL as their standard database
language.
Why SQL?

SQL is widely popular because it offers the following advantages −


• 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 to embed within other languages using SQL modules,
libraries & pre-compilers.
• 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.
A Brief History of SQL

• 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the


father of relational databases. He described a relational
model for databases.
• 1974 − Structured Query Language appeared.
• 1978 − IBM worked to develop Codd's ideas and
released a product named System/R.
• 1986 − IBM developed the first prototype of relational
database and standardized by ANSI (American National
Standards Institute). The first relational database was
released by Relational Software which later came to be
known as Oracle.
SQL Commands

• The standard SQL commands to interact with


relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These
commands can be classified into the following
groups based on their nature −
DDL - Data Definition Language

• It is a language used for defining and modifying the


data and its structure.
• It is used to build and modify the structure of your
tables and other objects in the database.
• DDL commands are as follows,
1. CREATE
2. DROP
3. ALTER
4. RENAME
5. TRUNCATE
These commands can be used to add, remove or
modify tables within a database.
• DDL has pre-defined syntax for describing the data.
Data Types

• SQL Datatype is used to define the values that a


column can contain.
• Every column is required to have a name and
data type in the database table.

Data types mainly classified into three categories


for every database.
• String Data types
• Numeric Data types
• Date and time Data types
String Data types

• CHAR(size) : It is used to store character data within the


predefined length. It can be stored up to 2000 bytes.

• NCHAR(size) : It is used to store national character ( non-ASCII


characters) data within the predefined length. It can be stored
up to 2000 bytes.

• VARCHAR2(size): It is used to store variable string data within


the predefined length. It can be stored up to 4000 byte.

• VARCHAR(SIZE) : It is the same as VARCHAR2(size). You can also


use VARCHAR(size), but it is suggested to use VARCHAR2(size)

• NVARCHAR2(size) : It is used to store Unicode string (a


sequence of zero or more code points) data within the
Numeric Data Types

• NUMBER(p, s) : It contains precision p and scale s. The precision p


can range from 1 to 38, and the scale s can range from -84 to 127.

Ex: For example, the number 1234.56 has a precision of 6 and a


scale of 2. So to store this number, you need NUMBER(6,2).

• FLOAT(p) : It is a subtype of the NUMBER data type. The precision


p can range from 1 to 126.

• BINARY_FLOAT : It is used for binary precision( 32-bit). It requires


5 bytes, including length byte.

• BINARY_DOUBLE : It is used for double binary precision (64-bit).


It requires 9 bytes, including length byte.
Date and Time Data Types

• DATE : It is used to store a valid date-time format with a


fixed length. Its range varies from January 1, 4712 BC to
December 31, 9999 AD.

• TIMESTAMP : It is used to store the valid date in YYYY-


MM-DD with time hh:mm:ss format
Data Types

Point Base supports the following data types for its column and parameter
declarations.
• CHARACTER [(length)] or CHAR [(length)]
• VARCHAR (length)
• BOOLEAN
• SMALLINT
• INTEGER or INT
• DECIMAL [(p[,s])] or DEC [(p[,s])]
• NUMERIC [(p[,s])]
• REAL
• FLOAT(p)
• DOUBLE PRECISION
• DATE
• TIME
• TIMESTAMP
• CLOB [(length)] or CHARACTER LARGE OBJECT [(length)] or CHAR LARGE
OBJECT [(length)]
• BLOB [(length)] or BINARY LARGE OBJECT [(length)]
SQL Components

• 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, set permission for users.
Types of SQL Commands
1. Data Definition Language (DDL)
• 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
• ALTER
• DROP
• TRUNCATE
Types of SQL Commands
2. Data Manipulation Language
• 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:
• INSERT
• UPDATE
• DELETE
Types of SQL Commands

3. Data Control Language


• DCL commands are used to grant and take back
authority from any database user.

Here are some commands that come under DCL:


• Grant
• Revoke
Types of SQL Commands
4. Transaction Control Language
• TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
• These operations are automatically committed in the database
that's why they cannot be used while creating tables or
dropping them.

Here are some commands that


• come under TCL:
• COMMIT (Save changes)
• ROLLBACK ( undo transactions )
• SAVEPOINT (roll the transaction back to a certain point without
rolling back the entire transaction.)
Types of SQL Commands

5. Data Query Language


• DQL is used to fetch the data from the database.
It uses only one command:
• SELECT
CREATE COMMAND

• CREATE command is used for creating objects in the database.


• It creates a new table.
• Syntax:

CREATE TABLE <table_name>


( column_name1 datatype,
column_name2 datatype,
.
.
.
column_name_n datatype
);

Example : CREATE command


• CREATE TABLE employee
(
empid INT,
ename CHAR,
age INT,
city CHAR(25),
phone_no VARCHAR(20)
DROP COMMAND
• DROP command allows to remove entire database objects from the
database.
• It removes entire data structure from the database.
• It deletes a table, index or view.

Syntax:
DROP TABLE <table_name>;
OR
DROP DATABASE <database_name>;

Example : DROP Command


• DROP TABLE employee;
OR
DROP DATABASE employees;

• If you want to remove individual records, then use DELETE command of


the DML statement.
ALTER COMMAND

• An ALTER command allows to alter or modify the structure of the database.


• It modifies an existing database object.
• Using this command, you can add additional column, drop existing column
and even change the data type of columns.

Syntax:
ALTER TABLE <table_name>
ADD <column_name datatype>;

OR

ALTER TABLE <table_name>


CHANGE <old_column_name> <new_column_name>;

OR

ALTER TABLE <table_name>


DROP COLUMN <column_name>;
ALTER COMMAND
Example : ALTER Command
ALTER TABLE employee
ADD (address varchar2(50));

OR

ALTER TABLE employee


CHANGE (phone_no) (contact_no);

OR

ALTER TABLE employee


DROP COLUMN age;

To view the changed structure of table, use 'DESCRIBE' command.


For example:
DESCRIBE TABLE employee;
RENAME COMMAND

• RENAME command is used to rename an


object.
• It renames a database table.
• Syntax:
RENAME TABLE <old_name> TO <new_name>;

Example:
RENAME TABLE emp TO employee;
TRUNCATE COMMAND

• TRUNCATE command is used to delete all the rows


from the table permanently.
• It removes all the records from a table, including all
spaces allocated for the records.
• This command is same as DELETE command, but
TRUNCATE command does not generate any rollback
data.
• Syntax:
TRUNCATE TABLE <table_name>;

Example:
TRUNCATE TABLE employee;
What is constraints?

• A set of rules are defined to enforce the database integrity,


is called as Constraints.
• The main purpose of constraint is to permit or prohibit the
values in the columns.
• Following are the Types of Constraint,
1. Primary Key
2. Foreign Key
3. Unique Key
4. Check Constraint
5. Not Null
• The above constraints are associated only with the tables.
• These constraints are applied to the table at the time of
table creation.
Primar •It identifies each row or record uniquely in a database
y Key table.
•It can not have NULL values.
•A table can have only one primary key.
•It contains unique values.
•If a table has a primary key, then you cannot have two
records of same value.

For Example: Empid INT PRIMARY KEY,

In the above example, there is one Employee table


where Empid have a Primary Key.
•When multiple fields are used as a primary key, is called
as Composite key.

Syntax: PRIMARY KEY (column1, column2);


Primar Primary key in a CUSTOMERS table.
y Key
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) );

PRIMARY KEY constraint on multiple columns


CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) );
PRIMARY KEY (ID, NAME) );
Foreign •Foreign key is a logical rule about values in multiple
Key columns or in tables.
•It is a set of columns in a table.
•It requires to match at least one primary key of a row in
another table.
•It defines the relationship between the tables.
•The 'references' keyword is used while referencing the
column into the another table.

For example:
Empid INT PRIMARY KEY,
FOREIGN KEY (Empid) references Department
(Empid);

In the above example, there are two tables Employee


and Department. The 'Empid' in Employee table has a
primary key. In Department table, it takes reference of
'Empid' from Employee table using Foreign key with the
keyword 'references'.
Foreig CREATE TABLE Department (
n Key Dept_name varchar (120) NOT NULL,
Stud_Id int,
FOREIGN KEY (Stud_Id) REFERENCES Student (Stud_Id)
);

CREATE TABLE Department (


Dept_name varchar (120) NOT NULL,
Stud_Id int FOREIGN KEY REFERENCES Student (Stud_Id)
);
Unique •It prevents two records from having identical values
Key in a particular column.
•It identifies each record uniquely in a database
table.
•Primary key and Unique key both provide a
guarantee of uniqueness for a column.
•Primary key has a unique constraint automatically
defined on it.

Note: Important thing to understand about the


primary key and unique key, is that a table can have
many unique constraints, but only one primary key
can have per table.

Unique key is declared with 'NOT NULL' constraint


at the time of creating a table.
•It accepts only one NULL value.
•It is a unique non-clustered index.
Unique Below syntax shows the implementation of the unique key on CREATE Table:
Key CREATE TABLE Student (
Sid int NOT NULL,
Sname varchar(100) NOT NULL,
Course varchar(120),
Age int,
UNIQUE (Sid)
);
Below is another syntax for implementing the unique key on multiple columns in a
table:
CREATE TABLE Student (
Sid int NOT NULL,
Sname varchar(100) NOT NULL,
Course varchar(120),
Age int,
CONSTRAINT UC_StudId UNIQUE (Sid, Sname)
);
Check •It enables a condition to check the value being
Constrain entered into a record.
t
•Multiple Check constraints are used in a single
column.
•It returns true or false result based on the
logical operator according to Boolean (logical)
expression.
•For example: Age INT NOT NULL CHECK (Age >= 19)
•CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
•CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
Null

•Null is a reserved keyword in SQL that indicates a data value does not exist
in the database.
•It identifies the Null special marker.
•Null introduced by E. F. Codd, Creator of the relational database model.
•A Null value indicates that the value is unknown, not applicable and has no
value, but it does not mean that it has a zero value or a field which contains
spaces.
•It is used to represent a missing value.

For example:

CREATE TABLE employee(empid INT NOT NULL,


ename CHAR NOT NULL,
age INT NOT NULL,
city CHAR(25),
phone_no VARCHAR(20),
PRIMARY KEY (empid));
In the above example, NOT NULL indicates that the column
should accept explicit value of the given data type. There are
two columns 'address' and 'phone_no' which are not assigned
with the NOT NULL, which means that these columns could be
NULL.

Null is not a data value, but it is a marker of an absent value.

It can cause problems when selecting data, because when


comparing an unknown value to any other value, the result is
always unknown and not included in the final results.
IS NULL or IS NOT NULL is used to check for a NULL value.
Example of IS NOT NULL:

<employee> Table

SELECT empid, ename, age, city, phone_no


FROM employee
WHERE phone_no IS NOT NULL;

Output:

empid ename age city phone_no

001 ABC 28 Pune 12345678

002 XYZ 30 Mumbai 54687901

003 PQR 35 Kolhapur

empid ename age city phone_no

001 ABC 28 Pune 12345678

002 XYZ 30 Mumbai 54687901


Example of IS NULL:

SELECT empid, ename, age, city, phone_no


FROM employee
WHERE phone_no IS NULL;

Output:

All aggregate function (min, max, sum, count) ignores the NULL values except
count() function.

empid ename age city phone_no

003 PQR 35 Kolhapur


When not to use NULL?

• NULL is not specify explicitly in SELECT


statement. For eg. SELECT NULL.
• NULL is not specify explicitly as an operand of
scalar expression.
For example, X + NULL, it is illegal.
NULL is not specify explicitly as an operand of
a conditional expression.
For example, WHERE a = NULL, it is illegal.
DML (Data Manipulation Language)
• DML stands for Data Manipulation Language.
• It is a language used for selecting, inserting, deleting
and updating data in a database.
• It is used to retrieve and manipulate data in a
relational database.
• DML commands are as follows,
1. SELECT
2. INSERT
3. UPDATE
4. DELETE
DML performs read-only queries of data.
INSERT COMMAND

• INSERT command is used for inserting a data into a table.


• Using this command, you can add one or more records to any single
table in a database.
• It is also used to add records to an existing table.
• Syntax:
INSERT INTO <table_name> (`column_name1` , `column_name2` , . . . ,
`column_name_n` ) VALUES (`value1`, `value2`, . . . , `value n`);

Example:
INSERT INTO employee (`eid`, `ename`, `city`)
VALUES (`1`, `ABC`, `PUNE`);

• INSERT INTO Customers (CustomerName, ContactName, Address, City,


PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
UPDATE COMMAND

• UPDATE command is used to modify the records present in existing


table.
• This command updates existing data within a table.
• It changes the data of one or more records in a table.
• Syntax:
UPDATE <table_name>
SET <column_name = value>
WHERE condition;

Example : UPDATE Command


• UPDATE employee
SET salary=20000
WHERE ename='ABC';
DELETE COMMAND

• DELETE command is used to delete some or all records from the existing
table.
• It deletes all the records from a table.

Syntax:
DELETE FROM <table_name> WHERE <condition>;

Example : DELETE Command


• DELETE FROM employee
WHERE emp_id = '001';

If we does not write the WHERE condition, then all rows will get deleted.
DCL (Data Control Language )

• DCL stands for Data Control Language.


• DCL is used to control user access in a database.
• This command is related to the security issues.
• Using DCL command, it allows or restricts the user
from accessing data in database schema.
• DCL commands are as follows,
1. GRANT
2. REVOKE
It is used to grant or revoke access permissions from
any database user.
GRANT COMMAND
• GRANT command gives user's access privileges to the database.
• This command allows specified users to perform specific tasks.

Syntax:
GRANT <privilege list>
ON <relation name or view name>
TO <user/role list>;

Example : GRANT Command


• GRANT ALL ON employee
TO ABC;
[WITH GRANT OPTION]
• In the above example, user 'ABC' has been given permission to
view and modify the records in the 'employee' table.
REVOKE COMMAND

• REVOKE command is used to cancel previously granted or


denied permissions.
• This command withdraw access privileges given with the
GRANT command.
• It takes back permissions from user.
• Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user name>;

Example : REVOKE Command


• REVOKE UPDATE
ON employee
FROM ABC;
Difference between GRANT and REVOKE
command.
GRANT REVOKE
GRANT command allows a user to REVOKE command disallows a user
perform certain activities on the to perform certain activities.
database.
It grants access privileges for It revokes access privileges for
database objects to other users. database objects previously granted
to other users.
Example: Example:

GRANT privilege_name REVOKE privilege_name


ON object_name ON object_name
TO
FROM
{ {
user_name|PUBLIC|role_name user_name|PUBLIC|role_name
} }

[WITH GRANT OPTION];


TCL (Transaction Control Language)

• TCL stands for Transaction Control Language.


• This command is used to manage the changes
made by DML statements.
• TCL allows the statements to be grouped
together into logical transactions.
• TCL commands are as follows:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
4. SET TRANSACTION
COMMIT COMMAND
• COMMIT command saves all the work done.
• It ends the current transaction and makes
permanent changes during the transaction.
• Syntax:
commit;
SAVEPOINT COMMAND

• SAVEPOINT command is used for saving all the current


point in the processing of a transaction.
• It marks and saves the current point in the processing of a
transaction.

Syntax:
SAVEPOINT <savepoint_name>;

Example:
SAVEPOINT no_update;

It is used to temporarily save a transaction, so that you can


rollback to that point whenever necessary.
ROLLBACK COMMAND

• ROLLBACK command restores database to


original since the last COMMIT.
• It is used to restores the database to last
committed state.
• Syntax:
ROLLBACK TO SAVEPOINT <savepoint_name>;

Example:
ROLLBACK TO SAVEPOINT no_update;
SET TRANSACTION

• SET TRANSACTION is used for placing a name on a


transaction.

Syntax:
SET TRANSACTION [Read Write | Read Only];

You can specify a transaction to be read only or


read write.
• This command is used to initiate a database
transaction.
Difference between ROLLBACK and COMMIT
commands.

ROLLBACK COMMIT
ROLLBACK command is used The COMMIT command is
to undo the changes made by used to save the modifications
the DML commands. done to the database values by
the DML commands.

It rollbacks all the changes of It will make all the changes


the current transaction. permanent that cannot be
rolled back.

Syntax: Syntax:
DELETE FROM table_name COMMIT;
ROLLBACK
SELECT clause has many optional clauses are as follow;

Clause Description
FROM It is used for selecting a table name in a database.

WHERE It specifies which rows to retrieve.

GROUP It is used to arrange the data into groups.


BY
HAVING It selects among the groups defined by the GROUP
BY clause.
ORDER It specifies an order in which to return the rows.
BY
AS It provides an alias which can be used to
temporarily rename tables or columns.
SELECT
Syntax:
SELECT {* | column_name1, column_name2, . . . ,
column_name_n}
FROM <list_of_tablename>
WHERE <condition>;

Example
SELECT * FROM employee
WHERE salary >=10000;

OR

SELECT eid, ename, age, salary from employee


WHERE salary >=10000;
What is QUERY?
• A query is an operation that retrieves data
from one or more tables or views.
• SELECT statement can be used for retrieving
the data from various tables in a database.
Example:

<Employee> Table

Eid Ename Age City Salary

E001 ABC 29 Pune 20000

E002 PQR 30 Pune 30000

E003 LMN 25 Mumbai 5000

E004 XYZ 24 Mumbai 4000

E005 STU 32 Bangalore 25000


1. Selecting all columns (SELECT *)

SELECT * FROM Employee;

2. Displaying particular record with condition (WHERE)

SELECT Ename FROM Employee


WHERE City = 'Pune';

Output:

Ename
ABC
PQR
3. SELECT using DISTINCT
DISTINCT clause is used to eliminate the duplicate values from the
table.

Example:
SELECT DISTINCT city FROM Employee;

Output:

City

Bangalore

Mumbai

Pune
4. SELECT using IN
'IN' determines whether a specified value matches any value in a
sub-query or a list.

Example:
SELECT Eid, Ename FROM Employee
WHERE Salary IN (5000, 20000);

Output:

Eid Ename
E001 ABC
E003 LMN
5. SELECT using BETWEEN
'BETWEEN' is used to get those values who fall within a range.

Example:
SELECT Eid, Ename, Salary FROM Employee
WHERE Salary BETWEEN 5000 AND 30000;

Output:

Eid Ename Salary

E001 ABC 20000

E002 PQR 30000

E003 LMN 5000

E005 STU 25000


NOT BETWEEN

Example:
SELECT Eid, Ename, Age FROM Employee
WHERE Age NOT BETWEEN 24 AND 25;

Output:

Eid Ename Age

E001 ABC 29

E002 PQR 30

E005 STU 32
6. SELECT using LIKE
•LIKE clause is used for comparing a value with similar
values using wildcard operators (% and _ ).
•Suppose, if you want user name starts with 'S', then
use 'LIKE' clause as follows,
Example:
SELECT Eid,Ename, City, Salary FROM Employee
WHERE Ename LIKE 'S%';

Output:

Eid Ename City Salary

E005 STU Bangalore 25000


LIKE Statements

Note: In the below LIKE statements, instead of 'S' and 'P' you can
use any value according to your needs while writing the query. 'S'
and 'P' are examples, mentioned for understanding.

Statement Description
s
LIKE 'S%' It finds any value which starts with 'S'.
LIKE '%S%' It finds any value which have 'S' in any position.
LIKE '_SS It finds any value which have 'SS' in the second and
%' third positions.
LIKE 'S_%_ It finds any value which starts with 'S' and have at least
%' three characters in length.
LIKE '%S' It finds any value which ends with 'S'.
LIKE '_S It finds any value which have 'S' in the second position
%P' and ends with 'P'.
LIKE It finds any value in a five digit numbers which start with
'S___P' 'S' and ends with 'P‘.
6. SELECT using GROUP BY

GROUP BY clause is used to arrange the data into


groups.

SELECT column1, function_name(column2) FROM table_name


WHERE condition GROUP BY column1, column2 ORDER BY
column1, column2;

function_name: Name of the function used for


example, SUM() , AVG(). table_name: Name of
the table. condition: Condition used.
Employee

SELECT NAME, SUM(SALARY) FROM Employee GROUP


BY NAME;
Student

SELECT SUBJECT, YEAR, Count(*) FROM Student GROUP BY SUBJECT,


YEAR;
7. SELECT using ORDER BY
•ORDER BY clause specifies an order in which to return the rows.
•It is used to sort the data in ascending or descending order which is based on one or
more columns.
Syntax:
SELECT <column-list>
FROM <table_name>
WHERE <condition>
ORDER BY <column1, column2, .. column_n> <ASC | DESC>;

Example:
SELECT Eid, Ename FROM Employee
ORDER BY Ename asc;

Output:

Eid Ename
E001 ABC
E002 LMN
E003 PQR
E005 STU
E004 XYZ
MySQL HAVING Clause

MySQL HAVING Clause is used with GROUP BY clause. It always


returns the rows where condition is TRUE.
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
database table "employee";

id name dept age salary location

Rames
100 Electrical 24 25000 Bangalore
h

101 Hrithik Electronics 28 35000 Bangalore

Aeronautic
102 Harsha 28 35000 Mysore
s
Soumy
103 Electronics 22 20000 Bangalore
a

104 Priya InfoTech 25 30000 Mangalore


SELECT name, salary FROM employee ORDER BY salary;

name salary
---------- ----------
Soumya 20000
Ramesh 25000
Priya 30000
Hrithik 35000
Harsha 35000
SELECT dept, SUM (salary) FROM employee GROUP BY
dept
HAVING SUM (salary) > 25000

dept salary
------------- -------------

Electronics 55000

Aeronautics 35000
InfoTech 30000
8. SELECT using AND, OR and NOT
i. AND
AND requires that two conditions are true.

Syntax:
SELECT <list_of_column_name>
FROM <list_of_table_name>
WHERE <condition1> AND <condition2>;

Example:
SELECT * FROM Employee
WHERE Age= 30 AND City="Pune";

Output:

Eid Ename Age City Salary


E002 PQR 30 Pune 30000
ii. OR
OR requires that one of two conditions is true.

Syntax:
SELECT <list_of_column_name>
FROM <list_of_table_name>
WHERE <condition1> OR <condition2>;

Example:
SELECT * FROM Employee
WHERE City="Pune" OR City="Mumbai";

Output:

Eid Ename Age City Salary


E001 ABC 29 Pune 20000
E002 PQR 30 Pune 30000
E003 LMN 25 Mumbai 5000
E004 XYZ 24 Mumbai 4000
iii. NOT
NOT neglects the specified condition.

Syntax:
SELETE <list_of_column_name>
FROM <list_of_table_name>
WHERE NOT <condition>;

Example:
SELECT * FROM Employee
WHERE NOT City="Pune";

Output:

Eid Ename Age City Salary


E003 LMN 25 Mumbai 5000
E004 XYZ 24 Mumbai 4000
E005 STU 32 Bangalore 25000
SUB-QUERY

• Sub-query is a inner query within another query. It is used to return


data in the main query as a condition to retrieved the data.
• Sub-queries are nested SELECT statement.
• It is a query within a query.
• Sub-queries are mostly appear within the WHERE or HAVING clause
of another SQL statement.
• It defines with another SELECT statement with a FROM clause and
optional WHERE, GROUP BY and HAVING clauses.
• It produces a single column of data as its result.
• In a sub-query, ORDER BY clause cannot be specified. ORDER BY
clause is specified in the main query.
• Sub-query is always enclosed in parentheses.
• It cannot be a UNION, only a single SELECT statement is allowed.
• In a sub-query, 'SELECT *' cannot be used unless the referring table
has only one column and nested query is evaluated first.
Example:
SELECT Ename, Salary FROM Employee
WHERE Salary IN
(SELECT MAX (Salary) FROM Employee);

Output:

Ename Salary

PQR 30000
Following are the comparison operators where
sub-queries are expressed as one SELECT
statement connected to another,
Comparison Operator

Operator Description
= Equal to
< > or != Not equal to
> Greater than
< Less than
>= Greater than Equal to
<= Less than Equal to
Multiple-row Comparison Operator
Operator Description
IN Equal to any value retrieved in an Inner query.

NOT IN Not equal to any value retrieved in an inner


query.
= ANY Equal to any value retrieved in an inner query –
Logical OR.
> ANY, >= Retrieves any highest value.
ANY
< ANY, <= Retrieves any smallest value.
ANY
= ALL Equal to all values retrieved in an Inner query –
Logical AND.
> ALL, >= Retrieves all highest values.
What is aggregate functions?

• Aggregate functions perform a calculation on a set of


values and return a single value.
• Aggregate functions ignore NULL values except COUNT.
• It is used with the GROUP BY clause of the SELECT
statement.
• Following are the Aggregate functions:
1. AVG
2. MAX
3. MIN
4. SUM
5. COUNT()
6. COUNT(*)
Example

<Employee> Table

Eid Ename Age City Salary


E001 ABC 29 Pune 20000
E002 PQR 30 Pune 30000
E003 LMN 25 Mumbai 5000
E004 XYZ 24 Mumbai 4000
E005 STU 32 Bangalore 25000
Aggregate Description Syntax Example Output
Functions
AVG It returns the averageSELECT AVG SELECT AVG(Salary) AVG(Salary)
of the data values.<column_name> FROM Employee; 16800
FROM
<table_name>;
MAX It returns the SELECT MAX SELECT MAX(Salary) MAX(Salary)
maximum value for a <column_name> FROM Employee; 30000
column. FROM
<table_name>;
MIN It returns the SELECT MIN SELECT MIN(Salary) MIN(Salary)
minimum value for a <column_name> FROM Employee; 4000
column. FROM
<table_name>;
SUM It returns the sum SELECT SUM SELECT SUM(Salary) SUM(Salary)
(addition) of the data <column_name> FROM Employee 50000
values. FROM WHERE City='Pune';
<table_name>;
COUNT() It returns total SELECT COUNT SELECT COUNT(Emp
number of values in a <column_name> COUNT(Empid) id)
given column. FROM FROM Employee; 5
<table_name>;
COUNT(*) It returns the number SELECT COUNT(*) SELECT COUNT(*) COUNT(*)
of rows in a table. FROM FROM Employee; 5
<table_name>;
Introduction to Joins

• Combining the records from two or more


tables in a relational database is called as Join.
• Join is used to match or equate different fields
from two or more tables using a primary key
or a foreign key.
• It combines records from two tables.
• It creates a set that can be saved as a table or
used as it is.
• MySQL JOINS are used with SELECT statement. It is
used to retrieve data from multiple tables. It is
performed whenever you need to fetch records from
two or more tables.
• There are three types of MySQL joins:
• MySQL INNER JOIN (or sometimes called simple join)
• MySQL LEFT OUTER JOIN (or sometimes called LEFT
JOIN)
• MySQL RIGHT OUTER JOIN (or sometimes called
RIGHT JOIN)
MySQL Inner JOIN (Simple Join)

• The MySQL INNER JOIN is used to return all rows


from multiple tables where the join condition is
satisfied. It is the most common type of join.
• Syntax:
SELECT columns FROM table1
INNER JOIN table2
ON table1.column = table2.column;
• Image representation:
• Let's take an example:
• Consider two tables "officers" and "students",
having the following data.
• Execute the following query:
SELECT officers.officer_name, officers.address, students
.course_name
FROM officers INNER JOIN students
ON officers.officer_id = students.student_id;
Output….
MySQL Left Outer Join
• The LEFT OUTER JOIN returns all rows from the left hand table
specified in the ON condition and only those rows from the
other table where the join condition is fulfilled.
• Syntax:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
• Image representation:
• Let's take an example:
• Consider two tables "officers" and "students",
having the following data.
• Execute the following query:
SELECT officers.officer_name, officers.address, students.course_
name
FROM officers LEFT JOIN students
ON officers.officer_id = students.student_id;
Output….
MySQL Right Outer Join
• The MySQL Right Outer Join returns all rows from the
RIGHT-hand table specified in the ON condition and only
those rows from the other table where he join condition
is fulfilled.
• Syntax:
SELECT columns FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
Image representation:
Let's take an example:
Consider two tables "officers" and "students", having the following
data.
Query
SELECT officers.officer_name, officers.address, students.cou
rse_name, students.student_name FROM officers RIGHT
JOIN students
ON officers.officer_id = students.student_id;
Output….
Output….
Example:
<Employee> Table
<Department> Table
Eid Ename Age City Salary
E001 ABC 29 Pune 20000
E002 PQR 30 Pune 30000
E003 LMN 25 Mumbai 5000
E004 XYZ 24 Mumbai 4000
E005 STU 32 Bangalore 25000

Deptid Eid DeptName


D001 E001 Finance
D002 E002 Production
D003 E003 Sales
D004 E005 Marketing
D005 E005 Human Resource
Types of JOINS:
Join Type Description Syntax Example
Simple It finds name and SELECT SELECT Ename,
Join department name of <list_of_column> FROM DeptName FROM
employee who have <table_name1>, Employee,
been allotted a <table_name2> WHERE Department
department. <table_name1>. WHERE
<column_name1> = Employee.Eid =
<table_name2>. Department.Eid;
<column_name1>

Inner/ Equi It extracts data that SELECT SELECT * FROM


/ Natural meets the join <list_of_column> FROM Employee INNER
Join conditions only. <table_name1> INNER JOIN Department
A JOIN is by default JOIN <table_name2> WHERE
INNER unless WHERE Employee.Eid=Dep
OUTER keyword is <table_name1>. artment.Eid;
specified for an <column_name1> =
OUTER JOIN. <table_name2>.
<column_name1>
Outer It SELECT DISTINCT SELECT DISTINCT *
Join include <list_of_column> FROM FROM Employee LEFT
s non <table_name1> LEFT OUTER OUTER JOIN
matchi JOIN <table_name2> WHERE Department WHERE
ng <table_name1>. Employee.Eid=Depart
rows. <column_name1> = ment.Eid
<table_name2>.
<column_name1>
Self It joins SELECT DISTINCT SELECT DISTINCT
Join a table <list_of_column> FROM e1.Ename, e1.City,
to <table_name1> AS e1.Salary, e1.Eid
itself. <alias_name1> FROM Employee AS
<table_name1> AS e1, Employee AS e2
<alias_name2> WHERE WHERE e1.Eid =
<alias_name1>.<column_name e2.Eid ORDER BY
1> = e1.Eid, e1.Ename;
<alias_name2>.<column_name
1>ORDER BY
<alias_name1>.<column_name
1>,
<alias_name1>.<column_name
Alias
• Alias is a shorthand for a table name or a column name.
• It reduces the amount of typing required to enter a query.
• Using alias, complex queries are easier to read.
• The alias name is only exists for the duration of the query.
• Alias names are useful for Aggregate functions and Joins.
• Syntax:
SELECT <column_name> AS <alias_name>
FROM <table name> <alias_name> WHERE <condition>;
• Aliases for columns:
SELECT first_name AS Name FROM student_details;
or
SELECT first_name Name FROM student_details;
In the above query, the column first_name is given
a alias as 'name'. So when the result is displayed the column
name appears as 'Name' instead of 'first_name'.
Alias
• Output:
• Name
-------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra
• Aliases for tables:
SELECT s.first_name FROM student_details s;
In the above query, alias 's' is defined for the table
student_details and the column first_name is selected from the
table.
Introduction to Views
• View is a virtual table that contains rows and columns, just like a real
table.
• It is used to hide complexity of query from user.
• A virtual table does not exist physically, it is created by a SQL statement
that joins one or more tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
• CREATE VIEW emp_dept_view
AS
SELECT Ename, DeptName
FROM Employee, Department
WHERE Employee.Eid=Department.Eid;
Example:
<Employee> Table
<Department> Table
Eid Ename Age City Salary
E001 ABC 29 Pune 20000
E002 PQR 30 Pune 30000
E003 LMN 25 Mumbai 5000
E004 XYZ 24 Mumbai 4000
E005 STU 32 Bangalore 25000

Deptid Eid DeptName


D001 E001 Finance
D002 E002 Production
D003 E003 Sales
D004 E005 Marketing
D005 E005 Human Resource
You can now see the view using following query,
SELECT * FROM emp_dept_view;

Ename DeptName
ABC Finance
PQR Production
LMN Sales
XYZ Marketing
STU Human Resource

SQL Dropping a View


Syntax
DROP VIEW view_name
Types of View

• Standard Views
• Indexed Views
• Partitioned Views
Advantages of View
• View provides data security for the same base tables.
• It allows different users to view the same data in
different ways at the same time.
• It is used to represent additional information like
derived columns.
• It is used to hide complex queries.
• It presents a consistent, unchanged image of the
database structure, even if the tables are split or
renamed.
• It does not allow direct access to the tables of the
data dictionary.
Disadvantages of View

• We cannot use DML operations on View, if there


is more than one table.
• When table is dropped view becomes inactive.
• View is a database object, so it occupies the
space.
• Without table, view will not work.
• Updating is possible for simple view but not for
complex views, they are read only type of views.
Introduction to Stored Procedure
• Stored Procedure is a set of Structured Query Language
(SQL) statements.It is a group of SQL statements which can
be executed repeatedly.
• It is a subroutine available to applications that access a
Relational Database Management System (RDBMS).
• Stored procedure is assigned with the name that's stored in
the database in compiled form, so that it can be shared by a
number of programs.
• It is helpful in controlling to access the data, preserving data
integrity and improving productivity.
• PL/SQL - Procedures (tutorialspoint.com)
Advantages of a Stored Procedure

• Stored procedures are easier to maintain and


troubleshoot as they are modular.
• It enables better tuning for performance.
• It is much easier from a GUI end than
building/using complex queries.
• It helps in reducing the network usage.
• It provides more scalability to an application.
• It is reusable and hence reduces the code.
Q. Write a PL/SQL block to define Variable (adding two numbers).
The following program describes, how to define a variable by adding two numbers.

Declare
Var1 integer;
Var2 integer;
Var3 integer;
Begin
Var1:=&var1;
Var2:=&var2;
Var3:=var1+var2;
Dbms_output.put_line(var3);
End;
/

Note: PL/SQL block can be nested within other PL/SQL blocks with the help of
BEGIN and END keyword. The code starts with DECLARE and it is used to define
all variables, cursors, subprograms and other elements which can be used in the
program.
Output:
Q. Write a Pl/SQL block to obtain factorial of a number.
Answer:
Factorial number: The factorial of a non-negative integer 'n' is denoted by n!. It is the
product of all positive integers less then or equal to 'n'.
For example:
3! = 3*2*1 = 6

Declare
num number;
fact number:= 1;
temp number;
begin
temp :=& num;
while (num > 0)
loop
fact := fact * num;
num := num - 1;
end loop;
Dbms_Output.Put_line('factorial of ' || temp || ' is ' || fact);
end;
/
The above program will compute the factorial of a given number.

Output:
Q. Write a PL/SQL block to obtain Fibonacci series.
Answer:
Fibonacci series: It is a series of a numbers, in which each number is the sum of
two previous numbers.
For example:
1, 1, 2, 3, 5, 8, 13, 21.........etc.
The following code will calculate the Fibonacci series of a given
number.

declare
a number(3):=1;
b number(3):=1;
c number(3);
n number(3):=&n;
begin
Dbms_output.put_line('the fibinocci series is:');
while a<=n
loop
dbms_output.put_line(a);
c:=a+b;
a:=b;
b:=c;
end loop;
end;
Output:
/
Introduction to Trigger
• A trigger is a special kind of stored procedures
that automatically executes when an event
occurs in the database server.
• Triggers executes when a user tries to modify
data through a data manipulation language
(DML) event, such as Insert, Delete, Update.
• These triggers fire when any valid event is fired.
• A Trigger that contains statement which causes
the other triggers are known as Cascading
Triggers.
Difference between Trigger and Stored
Procedure
Trigger Stored Procedure
Trigger is an act which is Stored procedure is a set of
performed automatically before functionality which is executed
or after an event occurs. when it is explicitly invoked.

It cannot accept parameters. It can accept parameters.


A trigger cannot return any A stored procedure can return
value. a value.

It is executed automatically on It needs to be explicitly called.


some event.

Triggers are used for insertion, Stored procedures are often


update and deletion. using independently in the
database.
Row level and Statement level trigger

• Row level Trigger :Row level trigger get fired once


for each row in a table affected by the statements.
• These triggers are useful if the code in the trigger
action depends on the data provided by the
triggering statement or rows that are affected.
• Row Level Trigger is fired each time when row is
affected by Insert, Update or Delete command.
• If statement doesn’t affect any row, then no
trigger action happens.
Statement level Trigger
• Statement level trigger gets fired once for each
triggering statement.
• This kind of trigger fires when a SQL statement
affects the rows of the table.
• The trigger activates and performs its activity
irrespective of number of rows affected due to
the SQL statement.
• These triggers are useful if the code in the trigger
action does not depend on the data provided by
the triggering statement or the rows affected.
Introduction to Cursor
• Cursor is a temporary work area created in the system
memory when a SQL statement is executed.
• It contains information on a SELECT statement and the
rows of data accessed by it.
• It can hold more than one row, but can process only one
row at a time.
• Cursor is used to access the result set present in the
memory.
• This result set contains the records returned on execution
of a query.
• There are two types of Cursor,
1. Explicit
2. Implicit
Explicit Cursor

• Explicit cursor is created when you are executing


a SELECT statement that returns more than one
row.
• It stores multiple records. Only one record can
be processed at a time, which is called as
Current Row.
• When you fetch a row the current row position
moves to the next row.
2. Implicit Cursor

• PL/SQL creates an implicit cursor whenever an SQL


statement is executed through the code, unless
the code employs an explicit cursor.
• The developer does not explicitly declare the
cursor, thus, known as Implicit Cursor.
• If the oracle engine has opened a cursor for its
internal processing, then it is implicit cursor.
• These cursors are automatically created by Oracle
whenever an SQL statement is executed, when
there is no explicit cursor for the statement.
Attributes of Explicit cursor

Attributes Description

%FOUND True, if the SQL statement has changed any


rows.

%NOTFOUN True, if record was not fetched successfully.


D

%ROWCOUN The number of rows affected by the SQL


T statement.

%ISOPEN True, if there is a SQL statement being


associated to the cursor or the cursor is open.
Drawbacks of Cursor
• Cursor allows row by row processing of record set. For
every row, a network roundtrip is made unlike in a
SELECT query, where there is just one network
roundtrip.
• Cursor needs more I/O and temporary storage
resources, thus it is slower.
• Implicit cursors are less efficient than explicit cursors.
• Implicit cursors are more vulnerable to data errors.
• Poorly written cursors can completely decrease
available memory.
Cursor Variable
• A cursor variable is a pointer that distinguishes the current row in a
resultset from a multi-row query.
• These variables allow cursors to be opened independently of being
processed.
• It can be passed as parameters between the application layers and the
server side components.
• These variables can be used to reduce the client-server network traffic.
• In case of a cursor, Oracle opens an anonymous work area that stores
processing information.
• This area can be accessed by cursor variable which points to this area.
• One must define a REF CURSOR type, and then declare cursor variables
of that type to do so.
Example
/* Create the cursor type. */
TYPE company_curtype IS REF CURSOR RETURN company
%ROWTYPE;

/* Declare a cursor variable of that type. */


company_curvar company_curtype;

• Why are cursor variables easier to use than cursors?

Cursor variables are preferred over a cursor for following reasons.


• A cursor variable is not tied to a specific query.
• One can open a cursor variable for any query returning the right
set of columns. Thus, more flexible than cursors.
• A cursor variable can be passed as a parameter.
• A cursor variable can refer to different work areas.
Consider the following Relation Tables:
student(Roll-no,name,address)
Subject(Sub_code,Sub_name)
Marks(Roll-no,Sub-code,marks)

Solve the following queries using SQL


i)Find out average marks of each student,along
with the name of student
ii)Find how many students have passed in the
subject “DBMS”
Consider following Relational Tables:

Instructor (ID,name,dept name)


student(ID,dept_name,tot_cred)
Takes(ID,course-id,sec-id,semester,year)
Course(course-id,title,dept-name,credits)
Dept(Dept-id,dept-name)

Solve following queries using SQL


Design above relation using SQL DDL
statement ,primary key and Foreign key

You might also like