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

Unit-2 SQL Updated

Uploaded by

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

Unit-2 SQL Updated

Uploaded by

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

STRUCTURED QUERY

LANGUAGE (SQL)

MBA-17 Batch (2020-22)


BACKGROUND
 Query Language is a language in which a user requests information from
the db.
 These languages are on a level higher than that of standard programming
language.
 2 types:
a) Procedural Language
b) Non- Procedural Language
Procedural Language: In this language, the user instructs the system to
perform a sequence of operations on the db to compute the desired
results.
Non- Procedural Language: In this language, the user describes the
desired information without giving a specific procedure for obtaining that
information.
 Most commercial DBMS offers a query language that includes elements of
both the procedural and non-procedural approaches. The most widely
used query language is SQL.
MBA-17 Batch (2020-22)
CONTD…
 IBM developed the original version of SQL, called as SEQUEL (Structured
English Query Language) as part of System R project in the early 1970s at
the IBM San Jose Research Laboratory.
 Renamed as Structured Query Language (SQL).
 In 1986, SQL was declared as the Standard Relational Database Language
by the ANSI (American National Standards Institute) & ISO.
 ANSI (American National Standards Institute) and ISO (International
Standards Organization) standard SQL are :
 SQL-86
 SQL-87- IBM’s own Corporate SQL Standard
 SQL-89
 SQL-92
 SQL:1999 (language name became Y2K compliant!)
 SQL:2003
 SQL:2005

MBA-17 Batch (2020-22)


SQL DATA TYPES
 The SQL standard supports a variety of built-in domain types which
includes:

 char(n). Fixed length character string, with user-specified length


n.
 varchar(n). Variable length character strings, with user-specified
maximum length n.
 int. Integer (a finite subset of the integers that is machine-
dependent).
 smallint. Small integer (a machine-dependent subset of the
integer domain type).
 numeric(p,d). Fixed point number, with user-specified precision
of p digits, with n digits to the right of decimal point.
 real, double precision. Floating point and double-precision
floating point numbers, with machine-dependent precision.
 float(n). Floating point number, with user-specified precision of
at least n digits.
MBA-17 Batch (2020-22)
SQL DATA DEFINITION LANGUAGE
(DDL)
 DDL provides commands for defining relation
schemas, deleting relations, and modifying
relation schemas.
 These commands are used to create, alter and
drop tables/relations.
 Following are DDL commands:
- CREATE Table
- ALTER Table
- DROP Table

MBA-17 Batch (2020-22)


CREATE TABLE CONSTRUCT
 An SQL relation is defined using the create table
command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk));
 r is the name of the relation
 each A is an attribute name in the schema of relation r
i
 D is the data type of values in the domain of attribute A
i i

 Example:
create table branch
(branch_namechar(15) not null,
branch_city char(30),
assets integer);
MBA-17 Batch (2020-22)
INTEGRITY CONSTRAINTS IN
CREATE TABLE
 not null
 primary key (A1, ..., An )

 Example: Declare branch_name as the


primary key for branch
create table branch
(branch_name char(15),
branch_city char(30),
assets integer,
primary key (branch_name));

MBA-17 Batch (2020-22)


EXAMPLE

MBA-17 Batch (2020-22)


EXAMPLE

MBA-17 Batch (2020-22)


ALTER TABLE CONSTRUCT
 The alter table command is used to add attributes to
an existing relation:
alter table r add A D;
where A is the name of the attribute to be added to
relation r and D is the data type of A.
 All tuples in the relation are assigned null as the value for the
new attribute.
 The alter table command can also be used to drop
attributes of a relation:
alter table r drop column A;
where A is the name of an attribute of relation r.
 Dropping of attributes are not supported by many databases.

MBA-17 Batch (2020-22)


ALTER DATABASE CONSTRUCT
 The alter database command can be used to change
the data type and size of an existing attribute/column:
alter table r modify A new_data_ type (new_size);
where A is the name of the existing attribute in
relation r.

MBA-17 Batch (2020-22)


DROP TABLE CONSTRUCT
 The drop table command deletes all information
about the relation from the database.

Drop table r;

MBA-17 Batch (2020-22)


SQL DATA MANIPULATION
LANGUAGE (DML)
 It provides commands for inserting, deleting
and modifying data or tuples in the database.
 DML commands are:
 INSERT
 DELETE
 UPDATE

MBA-17 Batch (2020-22)


INSERT COMMAND
 Used to add new tuple/row to a relation.
 The syntax for INSERT command is given as;
 INSERT INTO (Table_name) [(Attribute_name)]

VALUES (‘Attribute_name 1’, ‘Attribute_name 2’,


…., ‘Attribute_name n’);
 In the above syntax, Attribute_name with table
name is optional.

MBA-17 Batch (2020-22)


CONTD…

 Examples:
 Insert into CUSTOMERS values

(‘XXX’, ‘20-feb-2003’, ‘mumbai’,


‘YYY’, ‘21-mar-2004’, ‘delhi’);
- Insert into ITEMS (Item_no, Desc) values
(30, ‘clips’,35, ‘staplers’);

MBA-17 Batch (2020-22)


EXAMPLE OF INSERT

MBA-17 Batch (2020-22)


DELETE COMMAND
 Is used to delete or remove tuples or rows
from a relation.
 The syntax for DELETE command is given as;
 DELETE FROM (Table_name) WHERE Predicate(s));

 Examples:
 Delete from ITEMS where Item_no=25;
 Delete from ITEMS;
 Delete from STORE where Item_no IN (select Item_no
from ITEMS where weight=4);

MBA-17 Batch (2020-22)


UPDATE COMMAND
 Is used to modify attribute values of one or
more selected tuples or records by a predicate
in WHERE clause and the new values for the
attributes can be mentioned by SET clause.
 The syntax for UPDATE command is given as;
 UPDATE (Table_name)

SET (target_value_list)
WHERE (predicate);

MBA-17 Batch (2020-22)


CONTD…
 Examples:
 Update CUSTOMERS

set DOB= ‘20-feb-2003’,


CUST_CITY= ‘Mumbai’
where CUST_NAME= ‘XXX’;

- Update STORE
set QTY_HELD= 700
where ITEM_NO in (select ITEM_NO from
ITEMS where WEIGHT=>6);

MBA-17 Batch (2020-22)


EXAMPLE OF UPDATE

MBA-17 Batch (2020-22)


SQL DATA QUERY LANGUAGE (DQL)
 Commonly used SQL statements that enable
the users to put their queries to retrieve
information from one or more relations.
 A typical SQL query has the form:

select A1, A2, ..., An


from r1, r2, ..., rm
where P;
 A represents an attribute
i
 R represents a relation
i
 P is a predicate/condition

MBA-17 Batch (2020-22)


CONTD…
 The select clause list the attributes desired in the
result of a query.
 Example: Find the names of all branches in the loan
relation:
select branch_name
from loan;

MBA-17 Batch (2020-22)


CONTD…
 SQL allows duplicates in relations as well as in query
results.
 To force the elimination of duplicates, insert the
keyword distinct after select clause.
 Example: Find the names of all branches in the loan
relation, and remove duplicates
select distinct branch_name
from loan;
 The keyword all specifies that duplicates are not
removed from the resultant relation.
select all branch_name
from loan;

MBA-17 Batch (2020-22)


CONTD…
 An asterisk (*) in the select clause denotes “all attributes”
select *
from loan;
 The select clause can contain arithmetic expressions
involving the operations +, –, *, and /, and are operating
on constants or attributes of tuples.
 The query:
select loan_number, branch_name, amount * 100
from loan;
would return a relation that is same as the loan relation,
except that the value of the attribute amount is multiplied
by 100.

MBA-17 Batch (2020-22)


DUPLICATION OF RECORDS
QUERY
 Counting the duplicate records in the table
->Inserting the data using insert query (NOT
DEFINING S_id AS A PRIMARY KEY IN THIS CASE)]
Before :-
mysql> select * from customer;
+------+---------+------------+
| s_id | s_name | s_phn |
+------+---------+------------+
| 1 | Anchal | 6363444659 |
| 1 | Anchal | 6363444659 |
| 2 | Dazzy | 1234577 |
+------+---------+------------+
MBA-18 Batch (2021-23)
QUERY TO FIND DUPLICATE
RECORDS & COUNT
 mysql> select s_id, s_name, s_phn, COUNT(1)
as CNT from customer group by s_id, s_name,
s_phn having COUNT(1)>1;

OUTPUT:-
+------+---------+------------+-----+-------+-
| s_id | s_name | s_phn | CNT |
+------+---------+------------+-----+--------+-
| 1 | Anchal | 6363444659 | 2 |
+------+---------+------------+-----+---------+
CONT…..
MBA-17 Batch (2020-22)
 Inserting one more same name(Dazzy) with
different phone number in previous table &
again counting the duplicate records.
mysql> insert into
customer(s_id,s_name,s_phn)values(003,‘Dazzy'
,1234588);
mysql> select * from customer;
+------+---------+------------+------+
| s_id | s_name | s_phn |
+------+---------+------------+-------+
| 1 | Anchal | 6363444659 |
| 1 | Anchal | 6363444659 |
| 2 | Dazzy | 1234577 |
| 2 | Dazzy | 1234588 |
MBA-17 Batch (2020-22)
CONT…
Again applying the query of duplicate records

select s_id, s_name, s_phn, COUNT(1) as CNT
from customer group by s_id, s_name, s_phn
having COUNT(1)>1;
OUTPUT:-
+------+---------+------------+-----+-----+
| s_id | s_name | s_phn | CNT |
+------+---------+------------+-----+------+
| 1 | Anchal | 6363444659 | 2 |
| 2 | Dazzy | 1234577 | 2 |-
change in phone number(Dazzy-1234588) than
also it is counting the name as same & giving
the count 2.
CONT…
SOLUTION:-
 mysql> select s_id, s_name,count(s_phn)
from customer group by s_id;
 +------+---------+--------------+------+
 | s_id | s_name | count(s_phn) |
 +------+---------+--------------+------+
 | 1 | Anchal | 2 |
 | 2 | Dazzy | 1 |
 | 3 | Dazzy | 1 |
 +------+---------+--------------+-----+

MBA-17 Batch (2020-22)


CONTD…
 The where clause specifies conditions that the result
must satisfy.
 Example: To find out all loan number for loans made at
the Perryridge branch with loan amounts greater than
$1200.
select loan_number
from loan
where branch_name = 'Perryridge' and amount >
1200;
 Comparison results can be combined using the logical
connectives and, or, and not.
 Comparisons can be applied to the results of
arithmetic expressions.
MBA-17 Batch (2020-22)
EXAMPLE OF OR

MBA-17 Batch (2020-22)


EXAMPLE OF AND

MBA-17 Batch (2020-22)


EXAMPLE OF NOT EQUAL

MBA-17 Batch (2020-22)


CONTD…

 SQL includes between as a comparison operator.


 Example: Find the loan number of those loans with
loan amounts between $90,000 and $100,000 (that is,
>= $90,000 and <= $100,000)
select loan_number
from loan
where amount between 90000 and 100000;

MBA-17 Batch (2020-22)


EXAMPLE OF BETWEEN

MBA-17 Batch (2020-22)


CONTD…
 The from clause lists the relations involved in the query.
 Example: Find all the tuples from borrower and loan
relations
select *
from borrower, loan;
 Example: Find the name, loan number and loan amount of
all customers having a loan at the Perryridge branch.
select customer_name, borrower.loan_number, amount
from borrower, loan
where borrower.loan_number = loan.loan_number and
branch_name = 'Perryridge' ;

MBA-17 Batch (2020-22)


RENAME OPERATION

 The SQL allows renaming relations and attributes


using the as clause:
old-name as new-name
 Ex: Find the name, loan number and loan amount of
all customers also rename the attribute name
loan_number as loan_id.
select customer_name, borrower.loan_number as
loan_id, amount
from borrower, loan
where borrower.loan_number = loan.loan_number;

MBA-17 Batch (2020-22)


EXAMPLE OF RENAME

MBA-17 Batch (2020-22)


RENAME TABLE NAME

MBA-17 Batch (2020-22)


RENAME ATTRIBUTE NAME

MBA-17 Batch (2020-22)


STRING OPERATIONS
 SQL includes a string-matching operator for comparisons on character strings.
The operator like uses patterns that are described using two special characters:
 percent (%) - The % character matches any substring.
 underscore (_) - The _ character matches any character.
 Patterns are case sensitive, i.e. uppercase characters do not match with
lowercase characters or vice versa.
 Find the names of all customers whose street includes the substring “Main”.
select customer_name
from customer
where customer_street like '%main%' ;
 ‘%main%’ matches any string containing ‘main’ as a substring.
 ‘Main%’ matches any string beginning with ‘Main’.
 ‘_ _ _’ matches any string of exactly three characters.
 ‘_ _ _ %’ matches any string of at least three characters.

 SQL supports a variety of string operations such as


 concatenation (using “||”)
 converting from upper to lower case (and vice versa)
 finding string length, extracting substrings, etc.

MBA-17 Batch (2020-22)


DEMO TABLE FOR STRING
OPERATIONS

MBA-17 Batch (2020-22)


EXAMPLE FOR STRING OPERATIONS

MBA-17 Batch (2020-22)


EXAMPLE FOR STRING OPERATIONS

MBA-17 Batch (2020-22)


EXAMPLE FOR UPPERCASE

MBA-17 Batch (2020-22)


FINDING STRING LENGTH

MBA-17 Batch (2020-22)


UPPERCASE PERMANENT CHANGE
IN TABLE
 mysql> UPDATE rescue_4 SET CAND_NAME=
upper(CAND_NAME);

mysql> select * from rescue_4;


OUTPUT:-

+-----------------+-----------+-----------+---------------+----
|CAND_NAME | stud_ID| room_no | mob_no |
+-----------------+-----------+------------+--------------+-
| ANCHAL | 801 | 11 |7696555803|
| SCOOBY | 802 | 12 | NULL |
MBA-17 Batch (2020-22)
SUB STRING

mysql> SELECT SUBSTR(CAND_NAME,2,3) FROM


RESCUE_4;
OUTPUT:-
+---------------------------------------+
| SUBSTR(CAND_NAME,2,3) |
+---------------------------------------+
| NCH |
| COO |
+---------------------------------------+
14 rows in set (0.00 sec)
MBA-17 Batch (2020-22)
ORDERING THE DISPLAY OF TUPLES
 Example: List in alphabetic order the names of
all customers having a loan at Perryridge
branch.
select distinct customer_name
from borrower, loan
where borrower.loan_number =
loan.loan_number and
branch_name = 'Perryridge'
order by customer_name;
 We may specify desc for descending order or
asc for ascending order, for each attribute;
ascending order is the default.
 Example: order by customer_name desc
MBA-17 Batch (2020-22)
EXAMPLE OF ORDER BY

MBA-17 Batch (2020-22)


SET OPERATIONS
 The set operations union, intersect, and except
operate on relations 
 The relations participating in the set operations must
be Compatible i.e., they must have the same set of
attributes.
 Each of the above operations automatically eliminate
duplicates.
 To retain all duplicates in the relations use union all,
intersect all and except all.
 Suppose a tuple occurs m times in r and n times in s,
then, it occurs:
 m + n times in r union all s
 min(m,n) times in r intersect all s
 max(0, m – n) times in r except all s

MBA-17 Batch (2020-22)


CONTD…
 Find all customers who have a loan, an account, or both:
(select customer_name from depositor)
union
(select customer_name from borrower);
 This query returns a customer name who has several accounts or loans
or both at the bank. But the customer name will appear only once in
the resultant relation.
 If we want to retain all duplicates , then we must write the query as,
(select customer_name from depositor)
union all
(select customer_name from borrower);
 The no. of duplicates in the resultant relation= total no. of duplicates
appeared in both relations i.e. depositor and borrower.
MBA-17 Batch (2020-22)
CONTD…
 Find all customers who have both a loan and an account.
(select customer_name from depositor)
intersect
(select customer_name from borrower);
 This query returns a customer name who has several
records of both account and loan in the bank. But the
customer name only appear once in the resultant relation.

 If we want to retain all duplicates , then we must write the


query as,
(select customer_name from depositor)
intersect all
(select customer_name from borrower);
 The no. of duplicates in the resultant relation= minimum no.
of duplicates appeared in both relations i.e. depositor and
borrower.
MBA-17 Batch (2020-22)
CONTD…

 Find all customers who have an account but no loan.


(select customer_name from depositor)
except
(select customer_name from borrower);

 If we want to retain all duplicates , then we must write


the query as,
(select customer_name from depositor)
except all
(select customer_name from borrower);
 The no. of duplicates in the resultant relation= ( The
no. of duplicate copies in depositor relation) – ( The
no. of duplicate copies in borrower relation).
** But the difference always positive.

MBA-17 Batch (2020-22)


DEMO TABLE FOR SET OPERATIONS

MBA-17 Batch (2020-22)


EXAMPLE OF UNION

MBA-17 Batch (2020-22)


AGGREGATE FUNCTIONS

 Aggregate functions are the functions that take a


collection of values as input and return a single value.
 SQL offers 5 built-in functions:
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
 The input to sum and avg must be a collection of
numbers but the other functions can operate on
collections of non-numeric data types such as strings.

MBA-17 Batch (2020-22)


CONTD…
 Find the average account balance at the
Perryridge branch.
select avg (balance)
from account
where branch_name = ‘Perryridge’;
 Find the number of tuples in the customer
relation.
select count (*)
from customer;
 Find the number of depositors in the bank.
select count (distinct customer_name)
from depositor;
MBA-17 Batch (2020-22)
DEMO TABLE FOR AGGREGATE
FUNCTIONS

MBA-17 Batch (2020-22)


EXAMPLE OF AVERAGE

MBA-17 Batch (2020-22)


EXAMPLE OF MAX, MIN

MBA-17 Batch (2020-22)


EXAMPLE OF COUNT

MBA-17 Batch (2020-22)


AGGREGATE FUNCTIONS
BY USING GROUP BY CLAUSE
 Find the number of depositors for each branch.
select branch_name, count (distinct customer_name)
from depositor, account
where depositor.account_number =
account.account_number group by branch_name;
Note: Attributes in select clause outside of aggregate
functions must appear in group by list.

MBA-17 Batch (2020-22)


DEMO TABLE FOR GROUP BY

MBA-17 Batch (2020-22)


EXAMPLE FOR GROUP BY

MBA-17 Batch (2020-22)


AGGREGATE FUNCTIONS
BY USING HAVING CLAUSE
 It is also useful to state a condition that applies to
groups rather than to tuples.
 SQL applies predicates in the having clause after the
formation of groups.
 Example: Find the names of all branches where the
average account balance is more than $1,200.
select branch_name, avg (balance)
from account
group by branch_name
having avg (balance) > 1200;
 Note: Predicates in the having clause are applied after
the formation of groups whereas predicates in the
where clause are applied before forming groups.

MBA-17 Batch (2020-22)


NULL VALUES
 It is possible for tuples to have null values, denoted by null,
to some of their attributes.
 null signifies an unknown value or a value that does not
exist.
 The predicate is null can be used to check for null values.
 Example: Find all loan numbers which appear in the loan
relation with null values for amount.
select loan_number
from loan
where amount is null;
 The result of any arithmetic expression involving null is null
 Example: 5 + null returns null
 All aggregate functions except count(*), ignore null values
in their input collection.

MBA-17 Batch (2020-22)


FOREIGN KEY CONCEPT
PARENT TABLE (STUDENT)

MBA-17 Batch (2020-22)


FOREIGN KEY CONCEPT (CHILD)

MBA-17 Batch (2020-22)


FOREIGN KEY CONCEPT

MBA-17 Batch (2020-22)


DEMO TABLE FOR ON DELETE
CASCADE

MBA-17 Batch (2020-22)


ON DELETE CASCADE

MBA-17 Batch (2020-22)


ON UPDATE CASCADE

MBA-17 Batch (2020-22)


SUBQUERY
 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.

MBA-17 Batch (2020-22)


DEMO TABLE FOR SUBQUERIES

MBA-17 Batch (2020-22)


SUBQUERY
 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.

MBA-17 Batch (2020-22)


SUBQUERIES WITH THE SELECT
STATEMENT
 The basic syntax is as follows −

 SELECT column_name1 [, column_name2]


FROM table1 [, table2 ]
WHERE column_name1 OPERATOR
(SELECT column_name1[, column_name2 ]
FROM table1 [, table2 ]
[WHERE])

MBA-17 Batch (2020-22)


EXAMPLE
 Consider the CUSTOMERS (ID, Name, Age, Address,
Salary) table:

SELECT *
FROM CUSTOMERS
WHERE ID IN
(SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;

MBA-17 Batch (2020-22)


EXAMPLE OF SELECT

MBA-17 Batch (2020-22)


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 basic syntax is as follows:


INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

MBA-17 Batch (2020-22)


EXAMPLE
 Consider a table CUSTOMERS_EMP with similar structure
as CUSTOMERS table.
 Now to copy the complete CUSTOMERS table into the
CUSTOMERS_EMP table.
INSERT INTO CUSTOMERS_EMP
SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS) ;

MBA-17 Batch (2020-22)


EXAMPLE OF INSERT

MBA-17 Batch (2020-22)


SUBQUERIES WITH UPDATE
STATEMENT
 The subquery can be used in conjunction with the UPDATE
statement.
 Either single or multiple columns in a table can be updated
by using a subquery with the UPDATE statement.
 The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]]
(SELECT COLUMN_NAME FROM TABLE_NAME)
[ WHERE) ]

MBA-17 Batch (2020-22)


EXAMPLE
 Assuming, we have CUSTOMERS_EMP table available which is
backup of CUSTOMERS table.
 The following example updates SALARY by 0.25 times in the
CUSTOMERS table for all the customers whose AGE is greater
than or equal to 27.

UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN
(SELECT AGE
FROM CUSTOMERS_EMP
WHERE AGE >= 27 );

MBA-17 Batch (2020-22)


EXAMPLE OF UPDATE

MBA-17 Batch (2020-22)


SUBQUERIES WITH THE DELETE
STATEMENT
 The subquery can be used in conjunction with the DELETE
statement.
 The basic syntax is as follows:
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ] ]
(SELECT COLUMN_NAME FROM TABLE_NAME)
[ WHERE) ]

MBA-17 Batch (2020-22)


EXAMPLE
 We have a CUSTOMERS_EMP table available which is a
backup of the CUSTOMERS table.
 The following example deletes the records from the
CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27.
DELETE
FROM CUSTOMERS
WHERE AGE IN
(SELECT AGE
FROM CUSTOMERS_EMP
WHERE AGE >= 27 );

MBA-17 Batch (2020-22)


EXAMPLE OF DELETE

MBA-17 Batch (2020-22)


DERIVED RELATION
 A derived table is a virtual table returned from
a SELECT statement.

 A derived table is similar to a temporary table, but using a


derived table in the SELECT statement is much simpler
than a temporary table because it does not require steps of
creating the temporary table.

 The term derived table and subquery is often used


interchangeably. When a stand-alone subquery is used in
the FROM clause of a SELECT statement, we call it a
derived table.

MBA-17 Batch (2020-22)


DERIVED RELATION
 A subquery expression to be used in the from clause.
 If such an expression is used, the resultant relation must
be given a name, and the attributes can be renamed.
 Find the average account balance of those branches where
the average account balance is greater than $1,000.
select bname, avg-balance
from
(select bname, avg(balance)
from account group by bname)
as result(bname, avg-balance)
where avg-balance > 1000;

MBA-17 Batch (2020-22)


DERIVED TABLE

MBA-17 Batch (2020-22)


VIEWS
 VIEWS are virtual tables .By virtual, we mean that the
tables do not store any data of their own but display data
stored in other tables.
 In other words, VIEWS are nothing but SELECT Queries.
 The basic syntax used to create a view in MySQL is:
CREATE VIEW `view_name` AS SELECT statement;

 WHERE "CREATE VIEW `view_name`" tells MySQL


server to create a view object in the database named
`view_name`
 "AS SELECT statement" is the SQL statements to be
packed in the views. It can be a SELECT statement can
contain data from one table or multiple tables.

MBA-17 Batch (2020-22)


EXAMPLE OF VIEW

MBA-17 Batch (2020-22)


JOINED RELATIONS
 SQL Join is used to fetch data from two or more tables,
which is joined to appear as single set of data.
 It is used for combining column from two or more tables
by using values common to both tables.
 Types of JOIN:
 CROSS JOIN or Cartesian Product
 INNER JOIN or EQUI JOIN
 NATURAL JOIN
 OUTER JOIN
 LEFT OUTER JOIN
 RIGHT OUTER JOIN
 FULL OUTER JOIN

MBA-17 Batch (2020-22)


CROSS JOIN (CARTESIAN PRODUCT)
 This type of JOIN returns the Cartesian product of rows from
the tables in Join. It will return a table which consists of
records which combines each row from the first table with
each row of the second table.
 Syntax:
SELECT column-name-list
FROM table-name1 CROSS JOIN table-name2;
 Example: SELECT * FROM class CROSS JOIN class_info;
class class_info ID NAME ID Address

1 abhi 1 DELHI
ID NAME ID Address
2 adam 1 DELHI

1 abhi 1 DELHI 4 alex 1 DELHI

1 abhi 2 MUMBAI

2 adam 2 MUMBAI 2 adam 2 MUMBAI

4 alex 3 CHENNAI 4 alex 2 MUMBAI

1 abhi 3 CHENNAI

2 adam 3 CHENNAI

4 alex 3 CHENNAI

MBA-17 Batch (2020-22)


INNER JOIN OR EQUI JOIN
 This is a simple JOIN in which the result relation is based on
matched data as per the equality condition specified in the
SQL query.
 Syntax:
SELECT column-name-list
FROM table-name1 INNER JOIN table-name2
WHERE table-name1.column-name = table-name2.column-
name;
 Example:
SELECT *
FROM class INNER JOIN class_info
WHERE class.id = class_info.id;
ID NAME ID Address ID NAME ID Address
1 abhi 1 DELHI 1 abhi 1 DELHI
2 adam 2 MUMBAI 2 adam 2 MUMBAI
3 alex 3 CHENNAI 3 alex 3 CHENNAI
4 anu

MBA-17 Batch (2020-22)


NATURAL JOIN
 Natural Join is a type of Inner join which is based on column
having same name, same datatype and same data value
present in both the tables to be joined.
 Syntax:
SELECT *
FROM table-name1 NATURAL JOIN table-name2;
 Example:
SELECT *
FROM class NATURAL JOIN class_info;
ID NAME ID Address ID NAME Address

1 abhi 1 DELHI 1 abhi DELHI


2 adam 2 MUMBAI 2 adam MUMBAI
3 alex 3 CHENNAI 3 alex CHENNAI
4 anu

MBA-17 Batch (2020-22)


OUTER JOIN
 Outer Join is based on both matched and unmatched data.
 Outer Joins subdivide further into:

 Left Outer Join


 Right Outer Join
 Full Outer Join
 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.
 Syntax:

SELECT column-name-list
FROM table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;

MBA-17 Batch (2020-22)


LEFT OUTER JOIN
 Example: SELECT * FROM class LEFT OUTER JOIN class_info
ON (class.id = class_info.id);

ID NAME ID Address ID NAME ID Address


1 abhi 1 DELHI 1 abhi 1 DELHI
2 adam 2 MUMBAI 2 adam 2 MUMBAI
3 alex 3 CHENNAI 3 alex 3 CHENNAI
4 anu 7 NOIDA 4 anu null null
5 ashish 8 PANIPAT 5 ashish null null

Left outer Join Syntax for Oracle is,


SELECT column-name-list
FROM table-name1, table-name2
ON table-name1.column-name = table-name2.column-name(+);
MBA-17 Batch (2020-22)
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.
 Syntax:
SELECT column-name-list
FROM table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
 Example: SELECT * FROM class RIGHT OUTER JOIN class_info ON
(class.id = class_info.id);
ID NAME ID Address ID NAME ID Address

1 abhi 1 DELHI 1 abhi 1 DELHI

2 adam 2 MUMBAI 2 adam 2 MUMBAI

3 alex 3 CHENNAI
3 alex 3 CHENNAI
null null 7 NOIDA
4 anu 7 NOIDA
null null 8 PANIPAT
5 ashish 8 PANIPAT
MBA-17 Batch (2020-22)
RIGHT OUTER JOIN
Right outer Join Syntax for Oracle is,
SELECT column-name-list
FROM table-name1, table-name2
ON table-name1.column-name(+) = table-name2.column-name;

MBA-17 Batch (2020-22)


FULL OUTER JOIN
 The full outer join returns a result set table with the matched
data of two table then remaining rows of both left table and
then the right table.
 Syntax:
SELECT column-name-list
FROM table-name1 FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
 Example: SELECT * FROM class FULL OUTER JOIN class_info
ON (class.id = class_info.id); ID NAME ID Address
ID NAME ID Address 1 abhi 1 DELHI
1 abhi 1 DELHI 2 adam 2 MUMBAI
2 adam 2 MUMBAI 3 alex 3 CHENNAI
3 alex 3 CHENNAI 4 anu null null
4 anu 7 NOIDA 5 ashish null null
5 ashish 8 PANIPAT null null 7 NOIDA

null null 8 PANIPAT


MBA-17 Batch (2020-22)

You might also like