SlideShare a Scribd company logo
1 of 55
Unit-2 Queries
SQL (Structured query language)
Introduction
Introduction
Database systems Syllabus
Oracle Express edition Installation
http://catgovind.com/oracle/oracle-express-edition-installation-on-windows-
10/
UNIT II
Queries:algebraandlogic(relationalalgebraandcalculus),relational
querylanguagesandqueries(namelySQL),select,project,join,union,i
ntersection,except,recursion,aggregation,datamanipulation
Step by step Oracle Express
Edition installation instruction link
SQL
(STRUCTURED QUERY
LANGUAGE)
SQL
• Structure Query Language(SQL) is a database
query language used for storing and managing data
in Relational DBMS. SQL was the first commercial
language introduced for E.F
Codd's Relational model of database. Today almost
all RDBMS(MySql, Oracle, Infomix, Sybase, MS
Access) use SQL as the standard database query
language. SQL is used to perform all types of data
operations in RDBMS.
Database
A Database is collection of meaningful Data that is organized so
that it can easily be accessed, managed, and updated.
Database Management System
DBMS is a system that allows inserting, updating, deleting and
processing of the stored data.
Relational Database
A Relational Database is a collection of Data items organized as a
set of formally-described Tables from which data can be
accessed or re-assembled in many different ways without having
to re-organize the Database Tables.
• The Relational Database was invented by Edgar. F. Codd at IBM
in 1970.
Relational DBMS
RDBMS stores data in the form of related tables.
The leading RDBMS products are Oracle, IBM's DB2 and
Microsoft's SQL Server, MySQL, IBM Informix.
Structured Query Language (SQL)
• SQL is a computer language for storing, manipulating and
retrieving data stored in relational database.
• SQL is the standard language for Relational Database System.
• All relational database management systems like MySQL, MS
Access, Oracle, Sybase, Informix and SQL Server use SQL as
standard database language.
SQL is usually provided in two modes – interactive and
embedded SQL.
• Interactive SQL is used to operate directly on a database. The
response to any SQL command can be seen almost
immediately on the same terminal.
• Embedded SQL consists of SQL commands used within
programs written in some other language like C, ASP, JSP, VB
or Pascal.
COMPONENTS OF SQL
DDL (Data Definition Language)
• CREATE - Creates a new table, a view of a table, or other
object in database
• ALTER - Modifies an existing database object, such as a table.
• DROP - Deletes an entire table, a view of a table or other
object in the database.
• TRUNCATE - remove all records from a table, including all
spaces allocated for the records.
• RENAME – Renames an existing table.
DCL (Data control language)
• GRANT - gives user's access privileges to database
• REVOKE - withdraw access privileges given with the GRANT
command
DML (Data Manipulation Language)
• INSERT - insert data into a table.
• UPDATE - updates existing data within a table.
• DELETE - deletes all records from a table, the space for the
records remain
• LOCK TABLE - control concurrency.
TCL (Transaction Control Language)
• COMMIT - save the changes permanently.
• SAVEPOINT - identify a point in a transaction to which you can
later roll back
• ROLLBACK - restore database to original since the last
COMMIT
DRL (Data Retrieval Language)
• SELECT - retrieve data from the a database.
CREATE Command
Creates a new table or a view of a table in the database.
Syntax
CREATE TABLE table_name( column1 datatype(size), column2
datatype(size), column3 datatype(size), ..... columnN
datatype(size), [Integrity_Constraints]);
Naming Convention for Tables:
• Name should start with a character.
• Duplicate table names are not allowed.
• Max length is 30 characters.
• Special characters are not allowed except _, $ and #
• Spaces and dots are not allowed.
• Not case sensitive by default.
• Reserved words like create, select etc are not allowed.
• Valid character sets are A-Z, a-z, 0-9, _, $, #
Basic Data Types
• VARCHAR2(LEN) - Variable length char. Values up to width length.
Maximum width is 4000 chars.
• CHAR(LEN) - Fixed length char. Values of width length. Default
width is 1. Maximum length is 200.
• NUMBER - Floating point with precision of 38 significant digits.
• NUMBER (Precision, Scale) - Precision represents Maximum
significant digits allowed, which may not exceed 38. Scale is
the number of decimal places on the right of the decimal point.
• DATE - Date values in the range 1-1-4712 B.C to 31-12-4712AD.
Format ‘DD-MON-YY’
• LONG - Variable length char. Values up to 2 GB. Only one LONG
column is allowed per table. You cannot use LONG datatype in
functions, WHERE clause and sub queries.
• RAW AND LONG RAW - Equivalent to VARCHAR2 and LONG
respectively, used for storing digital sound or graphics images.
• CLOB, BLOB, NCLOB - Used to store large char. And binary objects.
Each can accommodate upto 4 GB.
• BFILE - Stores a pointer to an external file.
• TIMESTAMP - It is an extension of Date datatype. It stores year,
month, day, hour, minute and second values
Example of CREATE
CREATE table customer(Cust_name varchar2(20),
Cust_id number(10),
Cust_street varchar2(30),
Cust_city varchar2(20));
Output: customer
Cust_name Cust_id Cust_street Cust_city
Creating a table from another table
CREATE table target_table_name (col1,col2,..colN) as select
col1,col2,..colN from source_table;
Example:
CREATE table supplier (supplier_no, supplier_name) as select
client_no, name from client;
Note: new table created will have all the data copied from the
old table. To create the table without records, the select
statement must have a where clause with the condition that
cant be satisfied.
INSERT Command
Inserts data into the table.
Syntax:
• INSERT into table_name values (value1, value2, value3, ...,
valueN);
• INSERT into table_name (col1, col2,..colN) values (value1,
value2,...valueN);
Insteractive Mode of Insertion:
• INSERT into table_name values (‘&col1’, ‘&col2’,…’&colN’);
For executing the above command type / and press enter to
give the input.
Note: single quotes will not be applied for number datatype
columns.
Inserting data from another table
• INSERT into target_table select col1,col2,..colN from source_table
[where column=expressions];
Example:
• INSERT into customer values (‘JOHN’, 12, ‘BanjaraHills’,
‘Hyderabad’);
• INSERT into customer (cust_name,cust_street) values (‘JACK’,
’Panjagutta’);
Output:
Cust_name Cust_id Cust_street Cust_city
JOHN 12 BanjaraHills Hyderabad
JACK Panjagutta
Insertion using Interactive Mode – Inserts multiple records without
the need of writing the whole command again.
INSERT into customer values (‘&Cust_name’, &cust_id, ‘&cust_street’,
‘&cust_city’);
SQL>Enter the value for cust_name:
Enter the value for cust_id:
Enter the value for cust_street:
Enter the value for cust_city:
SQL> /
Enter the value for cust_name:
Enter the value for cust_id:
Enter the value for cust_street:
Enter the value for cust_city:
SELECT Command – Retrieves data from the database tables.
Basic Structure:
SELECT A1,A2,…An
FROM R1,R2,..Rn
WHERE P;
A-Attributes
R-Relation or Tables
P-Predicate or Condition
Syntax:
SELECT [Distinct/All] */column_list FROM table-name [WHERE
Clause] [GROUP BY clause[HAVING clause]] [ORDER BY clause
[Asc/Desc]];
• SELECT * from table_name; - Retrieves all rows
• SELECT col1,col2..colN from table_name;
- Retrieves selected columns
• SELECT DISTINCT col1 from table_name;
-Retrieves data after eliminating duplicates
• SELECT ALL col1 from table_name; - Allows duplicates
WHERE clause specifies the condition
• SELECT col1,col2 FROM table_name WHERE condition;
- Retrieves specific rows which satisfies the given condition.
Example:
SELECT cust_name FROM customer WHERE cust_city=‘Hyderabad’;
Review of SQL components
• DDL -- create, alter, drop, truncate, rename
• DML -- insert, update, delete
• DRL -- select
• TCL -- commit, rollback, savepoint
• DCL -- grant, revoke
Select statement is used to do the
following operations
• Selectselecting particular records from the
table
• ProjectSelecting particular columns from
the table
• Joinused to get data from multiple tables
• Setunion,Intersect,Minus
FROM Clause
• Specifies the tables from where the data has to be retrieved.
• Can include more than one table name to retrieve data from
multiple tables.
• Uses table_name.attribute_name to avoid ambiguity where
an attribute appears in more than one relation.
Example:
Select ename,empno,emp.deptno,dname from emp, dept where
emp.deptno=dept.deptno;
Functions
• A function is a set of SQL statements that
perform a specific task. Functions foster code
reusability. If you have to repeatedly write
large SQL scripts to perform the same task,
you can create a function that performs that
task. Next time instead of rewriting the SQL,
you can simply call that function
AGGREGATE FUNCTIONS
1. AVG([distinct/all] n) – returns average of n values ignoring
the null values in the column.
Eg: select avg(sal) from emp;
2. MIN([distinct/all] expr) – returns minimum value of the
expression.
Eg: select min(sal) from emp;
3. MAX([distinct/all] expr) – returns maximum value of the
expression.
Eg: select max(sal) from emp;
4. COUNT([distinct/all] expr) – returns the number of rows
where expr is not null.
Eg: select count(empno) from emp;
5. COUNT(*) – returns the number of rows in the table
including duplicates and those with null values.
Eg: select count(*) from emp;
6. SUM([distinct/all] n) – returns sum of values of n.
Eg: select sum(sal) from emp;
7. STDDEV([distint/all] x) – returns standard deviation of x.
8. VARIANCE([distinct/all] x) – returns variance of x.
GROUPBY AND HAVING CLAUSE
• Groupby clause is used when we apply the aggregate
function to a group of sets of tuples.
• The attributes given in the groupby clause are used to form
groups. Tuples with the same value on all attributes in the
group by clause are placed in one group.
• Distinct keyword in used in the aggregate functions to
eliminate duplicates.
Syntax:
SELECT column1, column2 FROM table1, table2 [WHERE
conditions ] GROUP BY column1, column2 [HAVING conditions
] [ORDER BY column1, column2];
Eg: find average account balance at each branch.
Select br_name,avg(bal) from account group by br_name;
A condition can be imposed on the groupby clause using having
clause which further filters groups created by groupby clause.
Eg: find branches where average account balance is more than
2000.
Select br_name,avg(bal) from account group by br_name having
avg(bal)>2000;
NOTE: if a where clause, groupby clause and having clause
appears in the same query then SQL applies the predicate in
the where clause first. Tuples satisfying the where clause are
then placed into groups by groupby clause. SQL then applies
the having clause to each group.
OTHER FUNCTIONS
1. nvl(m,n) – returns n where there is a NULL value in column
m.
2. UID – returns user ID
3. USER – returns username
Sorting of data in a table –
Oracle allows data from a table to be viewed in a sorted order. By
default, the order by clause lists items in ascending order. To
specify the sort order, use desc for descending order and asc
for ascending order.
Ex: Display details of employees according to their names –
select * from emp order by ename;
JOINS
An SQL JOIN clause is used to combine rows from two or more tables,
based on a common field between them.
Types of JOINS:
• INNER JOIN OR EQUI JOIN
• OUTER JOIN – LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER
JOIN
• SELF JOIN
• CROSS JOIN OR CARTESIAN JOIN
• Different Types of SQL JOINs
• Here are the different types of the JOINs in SQL:
• (INNER) JOIN: Returns records that have matching
values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left
table, and the matched records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the
right table, and the matched records from the left
table
• FULL (OUTER) JOIN: Returns all records when there is
a match in either left or right table
INNER JOIN - returns rows when there is a match in both the
tables.
Syntax:
SELECT column_name(s) FROM table1 INNER JOIN table2 ON
table1.column_name=table2.column_name;
OR
SELECT column_name(s) FROM table1,table2 WHERE
table1.column_name=table2.column_name;
Eg: CUSTOMERS
ID NAME AGE ADDRESS SALARY
1 JOHN 20 HYD 50000
2 JACK 25 DELHI 30000
3 JILL 23 MUMBAI 40000
ORDERS
Eg: SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS,
ORDERS WHERE CUSTOMERS.ID = ORDERS.CUST_ID;
OR
SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS INNER
JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID;
OUTPUT:
ID NAME AGE AMOUNT
1 JOHN 20 5000
2 JACK 25 10000
OID DATE CUST_ID AMOUNT
102 12-JUN-14 1 5000
103 25-JUL-15 2 10000
104 10-JAN-12 5 2000
LEFT JOIN - returns all rows from the left table, even if there are
no matches in the right table.
Syntax:
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON
table1.column_name =table2.column_name;
Eg:
SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS LEFT JOIN
ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID;
ID NAME AGE AMOUNT
1 JOHN 20 5000
2 JACK 25 10000
3 JILL 23 NULL
RIGHT JOIN - returns all rows from the right table, even if there
are no matches in the left table.
Syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON
table1.column_name =table2.column_name;
Eg:
SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS RIGHT
JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID;
ID NAME AGE AMOUNT
1 JOHN 20 5000
2 JACK 25 10000
NULL NULL NULL 2000
FULL JOIN – combination of left join and right join.
Syntax:
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2
ON table1.column_name =table2.column_name;
Eg:
SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS FULL
OUTER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID;
ID NAME AGE AMOUNT
1 JOHN 20 5000
2 JACK 25 10000
3 JILL 23 NULL
NULL NULL NULL 2000
SELF JOIN – joins a table to itself. In a self join, two rows from the
same table combine to form a result row.
Since the table names are same, we use aliasing.
Syntax
SELECT a.column_name, b.column_name... FROM table1 a,
table1 b WHERE a.common_field = b.common_field;
Eg: find names of employees and their managers.
Select e.ename “employee”, m.ename “manager” from emp e,
emp m where e.mgr=m.empno;
Employee Manager
FORD JONES
SCOTT JONES
JAMES BLAKE
CROSS JOIN – combines every row of one table with every row
of another table.
Syntax:
SELECT column_name(s) FROM table1 CROSS JOIN table2;
OR
SELECT column_name(s) FROM table1,table2;
Eg:
SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS;
ID NAME AGE AMOUNT
1 JOHN 20 5000
1 JOHN 20 10000
1 JOHN 20 2000
2 JACK 25 5000
2 JACK 25 10000
2 JACK 25 2000
SUBQUERIES
• A subquery is a form of an SQL statement that appears inside
another SQL statement.
• Also termed as nested query.
• The statement containing a subquery is called a parent
statement.
• The parent statement uses the rows (i.e., the result set)
returned by the subquery.
It can be used for the following purpose:
1. To insert records in a target table
2. To create tables and insert records in the table created
3. To update records in a target table.
4. To create views
5. To provide values for conditions in WHERE, HAVING, IN and
so on used with SELECT, UPDATE and DELETE statements.
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 cannot be used in a subquery, although the
main query can use an ORDER BY.
• 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.
Subqueries with SELECT command:
SELECT column_name [, column_name ] FROM table1 [, table2 ]
WHERE column_name OPERATOR (SELECT column_name
FROM table [WHERE clause]);
Eg:
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM
CUSTOMERS WHERE SALARY > 4500) ;
Subqueries with INSERT command:
INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT ([
*|column1 [, column2 ] FROM table1 [, table2 ] [WHERE]);
Eg:
INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS);
Subqueries with UPDATE statement:
UPDATE table SET column_name = new_value [ WHERE
OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM
TABLE_NAME) [ WHERE]);
Eg:
UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE
IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
Subqueries with DELETE statement:
DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME FROM TABLE_NAME [WHERE]);
Eg:
DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM
CUSTOMERS_BKP WHERE AGE > 27 );
Types of Subqueries:
1. Correlated Subquery
• A query is called correlated subquery when both the inner
query and the outer query are interdependent.
• For every row processed by the inner query, the outer query
is processed as well.
• The inner query depends on the outer query before it can be
processed.
2. Non-Corelated Subquery
• If a subquery is not dependent on the outer query it is called a
non-correlated subquery.
Subqueries with comparison operators:
• ALL
• ANY (SOME)
• EXISTS , NOT EXISTS
• IN, NOT IN
• UNIQUE, NOT UNIQUE
ALL
• The ALL comparison condition is used to compare a value to a list or
subquery. It must be preceded by =, !=, >, <, <=, >= and followed by
a list or subquery.
• When the ALL condition is followed by a list, the optimizer expands
the initial condition to all elements of the list and strings them
together with AND operators.
Eg: SELECT empno, sal FROM emp WHERE sal > ALL (2000, 3000,
4000);
• "x = ALL (...)": The value must match all the values in the list to
evaluate to TRUE.
• "x != ALL (...)": The value must not match any values in the list
to evaluate to TRUE.
• "x > ALL (...)": The value must be greater than the biggest
value in the list to evaluate to TRUE.
• "x < ALL (...)": The value must be smaller than the smallest
value in the list to evaluate to TRUE.
• "x >= ALL (...)": The value must be greater than or equal to the
biggest value in the list to evaluate to TRUE.
• "x <= ALL (...)": The value must be smaller than or equal to the
smallest value in the list to evaluate to TRUE.
ANY OR SOME
• The ANY comparison condition is used to compare a value to a
list or subquery. It must be preceded by =, !=, >, <, <=, >= and
followed by a list or subquery.
• When the ANY condition is followed by a list, the optimizer
expands the initial condition to all elements of the list and
strings them together with OR operators, as shown below.
Eg:
SELECT empno, sal FROM emp WHERE sal > ANY (2000, 3000,
4000);
• "x = ANY (...)": The value must match one or more values in
the list to evaluate to TRUE.
• "x != ANY (...)": The value must not match one or more values
in the list to evaluate to TRUE.
• "x > ANY (...)": The value must be greater than the smallest
value in the list to evaluate to TRUE.
• "x < ANY (...)": The value must be smaller than the biggest
value in the list to evaluate to TRUE.
• "x >= ANY (...)": The value must be greater than or equal to
the smallest value in the list to evaluate to TRUE.
• "x <= ANY (...)": The value must be smaller than or equal to
the biggest value in the list to evaluate to TRUE.
EXISTS, NOT EXISTS OPERATOR
• The EXISTS operator checks the existence of a result of
a Subquery. It tests whether a subquery fetches at least one
row.
• EXISTS returns true if the subquery returns one or more
records.
• When no data is returned then this operator returns 'FALSE'.
• A valid EXISTS subquery must contain an outer reference and
it must be a correlated Subquery.
Syntax :
SELECT column-names FROM table-name WHERE EXISTS/ NOT
EXISTS (SELECT column-name FROM table-name WHERE
condition);
Eg: SELECT * FROM customers WHERE EXISTS (SELECT * FROM
orders WHERE customers.id = orders.customer_id);
IN, NOT IN OPERATOR
• Test for set membership where the set is a collection of values
produced by the select clause.
• NOT IN tests for absence of set membership.
• Reduces the need for multiple OR condition.
Syntax:
SELECT column-names FROM table-name1 WHERE value IN
(SELECT column-name FROM table-name2 WHERE condition)
Eg:
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM
CUSTOMERS WHERE SALARY > 4500) ;
UNIQUE, NOT UNIQUE OPERATORS
• It returns true if the argument subquery contains no duplicate
tuples.
• The UNIQUE operator searches every row of a specified table
for uniqueness (no duplicates).
• NOT UNIQUE construct test the existence of duplicates in the
sub query.
Syntax:
SELECT column-names FROM table-name WHERE UNIQUE/NOT
UNIQUE (SELECT column-name FROM table-name WHERE
condition);

More Related Content

Similar to dbs class 7.ppt (20)

Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Lab
LabLab
Lab
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Introduction to SQL..pdf
Introduction to SQL..pdfIntroduction to SQL..pdf
Introduction to SQL..pdf
 
Module02
Module02Module02
Module02
 
Oracle Material.pdf
Oracle Material.pdfOracle Material.pdf
Oracle Material.pdf
 
12 SQL
12 SQL12 SQL
12 SQL
 
12 SQL
12 SQL12 SQL
12 SQL
 
Adbms
AdbmsAdbms
Adbms
 
sql-commands.pdf
sql-commands.pdfsql-commands.pdf
sql-commands.pdf
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql commands
Sql commandsSql commands
Sql commands
 
PO WER - Piotr Mariat - Sql
PO WER - Piotr Mariat - SqlPO WER - Piotr Mariat - Sql
PO WER - Piotr Mariat - Sql
 
Dbms
DbmsDbms
Dbms
 
Sql
SqlSql
Sql
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Apache Cassandra, part 1 – principles, data model
Apache Cassandra, part 1 – principles, data modelApache Cassandra, part 1 – principles, data model
Apache Cassandra, part 1 – principles, data model
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 

Recently uploaded

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 

Recently uploaded (20)

(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 

dbs class 7.ppt

  • 1. Unit-2 Queries SQL (Structured query language) Introduction Introduction
  • 3.
  • 4. Oracle Express edition Installation http://catgovind.com/oracle/oracle-express-edition-installation-on-windows- 10/ UNIT II Queries:algebraandlogic(relationalalgebraandcalculus),relational querylanguagesandqueries(namelySQL),select,project,join,union,i ntersection,except,recursion,aggregation,datamanipulation Step by step Oracle Express Edition installation instruction link
  • 6. SQL • Structure Query Language(SQL) is a database query language used for storing and managing data in Relational DBMS. SQL was the first commercial language introduced for E.F Codd's Relational model of database. Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) use SQL as the standard database query language. SQL is used to perform all types of data operations in RDBMS.
  • 7. Database A Database is collection of meaningful Data that is organized so that it can easily be accessed, managed, and updated. Database Management System DBMS is a system that allows inserting, updating, deleting and processing of the stored data. Relational Database A Relational Database is a collection of Data items organized as a set of formally-described Tables from which data can be accessed or re-assembled in many different ways without having to re-organize the Database Tables. • The Relational Database was invented by Edgar. F. Codd at IBM in 1970.
  • 8. Relational DBMS RDBMS stores data in the form of related tables. The leading RDBMS products are Oracle, IBM's DB2 and Microsoft's SQL Server, MySQL, IBM Informix. Structured Query Language (SQL) • SQL is a computer language for storing, manipulating and retrieving data stored in relational database. • SQL is the standard language for Relational Database System. • All relational database management systems like MySQL, MS Access, Oracle, Sybase, Informix and SQL Server use SQL as standard database language.
  • 9. SQL is usually provided in two modes – interactive and embedded SQL. • Interactive SQL is used to operate directly on a database. The response to any SQL command can be seen almost immediately on the same terminal. • Embedded SQL consists of SQL commands used within programs written in some other language like C, ASP, JSP, VB or Pascal.
  • 10.
  • 11. COMPONENTS OF SQL DDL (Data Definition Language) • CREATE - Creates a new table, a view of a table, or other object in database • ALTER - Modifies an existing database object, such as a table. • DROP - Deletes an entire table, a view of a table or other object in the database. • TRUNCATE - remove all records from a table, including all spaces allocated for the records. • RENAME – Renames an existing table. DCL (Data control language) • GRANT - gives user's access privileges to database • REVOKE - withdraw access privileges given with the GRANT command
  • 12. DML (Data Manipulation Language) • INSERT - insert data into a table. • UPDATE - updates existing data within a table. • DELETE - deletes all records from a table, the space for the records remain • LOCK TABLE - control concurrency. TCL (Transaction Control Language) • COMMIT - save the changes permanently. • SAVEPOINT - identify a point in a transaction to which you can later roll back • ROLLBACK - restore database to original since the last COMMIT DRL (Data Retrieval Language) • SELECT - retrieve data from the a database.
  • 13. CREATE Command Creates a new table or a view of a table in the database. Syntax CREATE TABLE table_name( column1 datatype(size), column2 datatype(size), column3 datatype(size), ..... columnN datatype(size), [Integrity_Constraints]); Naming Convention for Tables: • Name should start with a character. • Duplicate table names are not allowed. • Max length is 30 characters. • Special characters are not allowed except _, $ and # • Spaces and dots are not allowed. • Not case sensitive by default. • Reserved words like create, select etc are not allowed. • Valid character sets are A-Z, a-z, 0-9, _, $, #
  • 14. Basic Data Types • VARCHAR2(LEN) - Variable length char. Values up to width length. Maximum width is 4000 chars. • CHAR(LEN) - Fixed length char. Values of width length. Default width is 1. Maximum length is 200. • NUMBER - Floating point with precision of 38 significant digits. • NUMBER (Precision, Scale) - Precision represents Maximum significant digits allowed, which may not exceed 38. Scale is the number of decimal places on the right of the decimal point. • DATE - Date values in the range 1-1-4712 B.C to 31-12-4712AD. Format ‘DD-MON-YY’
  • 15. • LONG - Variable length char. Values up to 2 GB. Only one LONG column is allowed per table. You cannot use LONG datatype in functions, WHERE clause and sub queries. • RAW AND LONG RAW - Equivalent to VARCHAR2 and LONG respectively, used for storing digital sound or graphics images. • CLOB, BLOB, NCLOB - Used to store large char. And binary objects. Each can accommodate upto 4 GB. • BFILE - Stores a pointer to an external file. • TIMESTAMP - It is an extension of Date datatype. It stores year, month, day, hour, minute and second values
  • 16. Example of CREATE CREATE table customer(Cust_name varchar2(20), Cust_id number(10), Cust_street varchar2(30), Cust_city varchar2(20)); Output: customer Cust_name Cust_id Cust_street Cust_city
  • 17. Creating a table from another table CREATE table target_table_name (col1,col2,..colN) as select col1,col2,..colN from source_table; Example: CREATE table supplier (supplier_no, supplier_name) as select client_no, name from client; Note: new table created will have all the data copied from the old table. To create the table without records, the select statement must have a where clause with the condition that cant be satisfied.
  • 18. INSERT Command Inserts data into the table. Syntax: • INSERT into table_name values (value1, value2, value3, ..., valueN); • INSERT into table_name (col1, col2,..colN) values (value1, value2,...valueN); Insteractive Mode of Insertion: • INSERT into table_name values (‘&col1’, ‘&col2’,…’&colN’); For executing the above command type / and press enter to give the input. Note: single quotes will not be applied for number datatype columns.
  • 19. Inserting data from another table • INSERT into target_table select col1,col2,..colN from source_table [where column=expressions]; Example: • INSERT into customer values (‘JOHN’, 12, ‘BanjaraHills’, ‘Hyderabad’); • INSERT into customer (cust_name,cust_street) values (‘JACK’, ’Panjagutta’); Output: Cust_name Cust_id Cust_street Cust_city JOHN 12 BanjaraHills Hyderabad JACK Panjagutta
  • 20. Insertion using Interactive Mode – Inserts multiple records without the need of writing the whole command again. INSERT into customer values (‘&Cust_name’, &cust_id, ‘&cust_street’, ‘&cust_city’); SQL>Enter the value for cust_name: Enter the value for cust_id: Enter the value for cust_street: Enter the value for cust_city: SQL> / Enter the value for cust_name: Enter the value for cust_id: Enter the value for cust_street: Enter the value for cust_city:
  • 21. SELECT Command – Retrieves data from the database tables. Basic Structure: SELECT A1,A2,…An FROM R1,R2,..Rn WHERE P; A-Attributes R-Relation or Tables P-Predicate or Condition Syntax: SELECT [Distinct/All] */column_list FROM table-name [WHERE Clause] [GROUP BY clause[HAVING clause]] [ORDER BY clause [Asc/Desc]];
  • 22. • SELECT * from table_name; - Retrieves all rows • SELECT col1,col2..colN from table_name; - Retrieves selected columns • SELECT DISTINCT col1 from table_name; -Retrieves data after eliminating duplicates • SELECT ALL col1 from table_name; - Allows duplicates WHERE clause specifies the condition • SELECT col1,col2 FROM table_name WHERE condition; - Retrieves specific rows which satisfies the given condition. Example: SELECT cust_name FROM customer WHERE cust_city=‘Hyderabad’;
  • 23. Review of SQL components • DDL -- create, alter, drop, truncate, rename • DML -- insert, update, delete • DRL -- select • TCL -- commit, rollback, savepoint • DCL -- grant, revoke
  • 24. Select statement is used to do the following operations • Selectselecting particular records from the table • ProjectSelecting particular columns from the table • Joinused to get data from multiple tables • Setunion,Intersect,Minus
  • 25. FROM Clause • Specifies the tables from where the data has to be retrieved. • Can include more than one table name to retrieve data from multiple tables. • Uses table_name.attribute_name to avoid ambiguity where an attribute appears in more than one relation. Example: Select ename,empno,emp.deptno,dname from emp, dept where emp.deptno=dept.deptno;
  • 26. Functions • A function is a set of SQL statements that perform a specific task. Functions foster code reusability. If you have to repeatedly write large SQL scripts to perform the same task, you can create a function that performs that task. Next time instead of rewriting the SQL, you can simply call that function
  • 27. AGGREGATE FUNCTIONS 1. AVG([distinct/all] n) – returns average of n values ignoring the null values in the column. Eg: select avg(sal) from emp; 2. MIN([distinct/all] expr) – returns minimum value of the expression. Eg: select min(sal) from emp; 3. MAX([distinct/all] expr) – returns maximum value of the expression. Eg: select max(sal) from emp; 4. COUNT([distinct/all] expr) – returns the number of rows where expr is not null. Eg: select count(empno) from emp; 5. COUNT(*) – returns the number of rows in the table including duplicates and those with null values. Eg: select count(*) from emp;
  • 28. 6. SUM([distinct/all] n) – returns sum of values of n. Eg: select sum(sal) from emp; 7. STDDEV([distint/all] x) – returns standard deviation of x. 8. VARIANCE([distinct/all] x) – returns variance of x. GROUPBY AND HAVING CLAUSE • Groupby clause is used when we apply the aggregate function to a group of sets of tuples. • The attributes given in the groupby clause are used to form groups. Tuples with the same value on all attributes in the group by clause are placed in one group. • Distinct keyword in used in the aggregate functions to eliminate duplicates.
  • 29. Syntax: SELECT column1, column2 FROM table1, table2 [WHERE conditions ] GROUP BY column1, column2 [HAVING conditions ] [ORDER BY column1, column2]; Eg: find average account balance at each branch. Select br_name,avg(bal) from account group by br_name; A condition can be imposed on the groupby clause using having clause which further filters groups created by groupby clause. Eg: find branches where average account balance is more than 2000. Select br_name,avg(bal) from account group by br_name having avg(bal)>2000;
  • 30. NOTE: if a where clause, groupby clause and having clause appears in the same query then SQL applies the predicate in the where clause first. Tuples satisfying the where clause are then placed into groups by groupby clause. SQL then applies the having clause to each group. OTHER FUNCTIONS 1. nvl(m,n) – returns n where there is a NULL value in column m. 2. UID – returns user ID 3. USER – returns username
  • 31. Sorting of data in a table – Oracle allows data from a table to be viewed in a sorted order. By default, the order by clause lists items in ascending order. To specify the sort order, use desc for descending order and asc for ascending order. Ex: Display details of employees according to their names – select * from emp order by ename;
  • 32. JOINS An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. Types of JOINS: • INNER JOIN OR EQUI JOIN • OUTER JOIN – LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN • SELF JOIN • CROSS JOIN OR CARTESIAN JOIN
  • 33. • Different Types of SQL JOINs • Here are the different types of the JOINs in SQL: • (INNER) JOIN: Returns records that have matching values in both tables • LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table • RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table • FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
  • 34.
  • 35. INNER JOIN - returns rows when there is a match in both the tables. Syntax: SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name=table2.column_name; OR SELECT column_name(s) FROM table1,table2 WHERE table1.column_name=table2.column_name; Eg: CUSTOMERS ID NAME AGE ADDRESS SALARY 1 JOHN 20 HYD 50000 2 JACK 25 DELHI 30000 3 JILL 23 MUMBAI 40000
  • 36. ORDERS Eg: SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUST_ID; OR SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS INNER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID; OUTPUT: ID NAME AGE AMOUNT 1 JOHN 20 5000 2 JACK 25 10000 OID DATE CUST_ID AMOUNT 102 12-JUN-14 1 5000 103 25-JUL-15 2 10000 104 10-JAN-12 5 2000
  • 37. LEFT JOIN - returns all rows from the left table, even if there are no matches in the right table. Syntax: SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name =table2.column_name; Eg: SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID; ID NAME AGE AMOUNT 1 JOHN 20 5000 2 JACK 25 10000 3 JILL 23 NULL
  • 38. RIGHT JOIN - returns all rows from the right table, even if there are no matches in the left table. Syntax: SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name =table2.column_name; Eg: SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID; ID NAME AGE AMOUNT 1 JOHN 20 5000 2 JACK 25 10000 NULL NULL NULL 2000
  • 39. FULL JOIN – combination of left join and right join. Syntax: SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name =table2.column_name; Eg: SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS FULL OUTER JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUST_ID; ID NAME AGE AMOUNT 1 JOHN 20 5000 2 JACK 25 10000 3 JILL 23 NULL NULL NULL NULL 2000
  • 40. SELF JOIN – joins a table to itself. In a self join, two rows from the same table combine to form a result row. Since the table names are same, we use aliasing. Syntax SELECT a.column_name, b.column_name... FROM table1 a, table1 b WHERE a.common_field = b.common_field; Eg: find names of employees and their managers. Select e.ename “employee”, m.ename “manager” from emp e, emp m where e.mgr=m.empno; Employee Manager FORD JONES SCOTT JONES JAMES BLAKE
  • 41. CROSS JOIN – combines every row of one table with every row of another table. Syntax: SELECT column_name(s) FROM table1 CROSS JOIN table2; OR SELECT column_name(s) FROM table1,table2; Eg: SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS; ID NAME AGE AMOUNT 1 JOHN 20 5000 1 JOHN 20 10000 1 JOHN 20 2000 2 JACK 25 5000 2 JACK 25 10000 2 JACK 25 2000
  • 42. SUBQUERIES • A subquery is a form of an SQL statement that appears inside another SQL statement. • Also termed as nested query. • The statement containing a subquery is called a parent statement. • The parent statement uses the rows (i.e., the result set) returned by the subquery. It can be used for the following purpose: 1. To insert records in a target table 2. To create tables and insert records in the table created 3. To update records in a target table. 4. To create views 5. To provide values for conditions in WHERE, HAVING, IN and so on used with SELECT, UPDATE and DELETE statements.
  • 43. 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 cannot be used in a subquery, although the main query can use an ORDER BY. • 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.
  • 44. Subqueries with SELECT command: SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name FROM table [WHERE clause]); Eg: SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ;
  • 45. Subqueries with INSERT command: INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT ([ *|column1 [, column2 ] FROM table1 [, table2 ] [WHERE]); Eg: INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS);
  • 46. Subqueries with UPDATE statement: UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE]); Eg: UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );
  • 47. Subqueries with DELETE statement: DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME [WHERE]); Eg: DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE > 27 );
  • 48. Types of Subqueries: 1. Correlated Subquery • A query is called correlated subquery when both the inner query and the outer query are interdependent. • For every row processed by the inner query, the outer query is processed as well. • The inner query depends on the outer query before it can be processed. 2. Non-Corelated Subquery • If a subquery is not dependent on the outer query it is called a non-correlated subquery.
  • 49. Subqueries with comparison operators: • ALL • ANY (SOME) • EXISTS , NOT EXISTS • IN, NOT IN • UNIQUE, NOT UNIQUE ALL • The ALL comparison condition is used to compare a value to a list or subquery. It must be preceded by =, !=, >, <, <=, >= and followed by a list or subquery. • When the ALL condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with AND operators. Eg: SELECT empno, sal FROM emp WHERE sal > ALL (2000, 3000, 4000);
  • 50. • "x = ALL (...)": The value must match all the values in the list to evaluate to TRUE. • "x != ALL (...)": The value must not match any values in the list to evaluate to TRUE. • "x > ALL (...)": The value must be greater than the biggest value in the list to evaluate to TRUE. • "x < ALL (...)": The value must be smaller than the smallest value in the list to evaluate to TRUE. • "x >= ALL (...)": The value must be greater than or equal to the biggest value in the list to evaluate to TRUE. • "x <= ALL (...)": The value must be smaller than or equal to the smallest value in the list to evaluate to TRUE.
  • 51. ANY OR SOME • The ANY comparison condition is used to compare a value to a list or subquery. It must be preceded by =, !=, >, <, <=, >= and followed by a list or subquery. • When the ANY condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with OR operators, as shown below. Eg: SELECT empno, sal FROM emp WHERE sal > ANY (2000, 3000, 4000);
  • 52. • "x = ANY (...)": The value must match one or more values in the list to evaluate to TRUE. • "x != ANY (...)": The value must not match one or more values in the list to evaluate to TRUE. • "x > ANY (...)": The value must be greater than the smallest value in the list to evaluate to TRUE. • "x < ANY (...)": The value must be smaller than the biggest value in the list to evaluate to TRUE. • "x >= ANY (...)": The value must be greater than or equal to the smallest value in the list to evaluate to TRUE. • "x <= ANY (...)": The value must be smaller than or equal to the biggest value in the list to evaluate to TRUE.
  • 53. EXISTS, NOT EXISTS OPERATOR • The EXISTS operator checks the existence of a result of a Subquery. It tests whether a subquery fetches at least one row. • EXISTS returns true if the subquery returns one or more records. • When no data is returned then this operator returns 'FALSE'. • A valid EXISTS subquery must contain an outer reference and it must be a correlated Subquery. Syntax : SELECT column-names FROM table-name WHERE EXISTS/ NOT EXISTS (SELECT column-name FROM table-name WHERE condition); Eg: SELECT * FROM customers WHERE EXISTS (SELECT * FROM orders WHERE customers.id = orders.customer_id);
  • 54. IN, NOT IN OPERATOR • Test for set membership where the set is a collection of values produced by the select clause. • NOT IN tests for absence of set membership. • Reduces the need for multiple OR condition. Syntax: SELECT column-names FROM table-name1 WHERE value IN (SELECT column-name FROM table-name2 WHERE condition) Eg: SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ;
  • 55. UNIQUE, NOT UNIQUE OPERATORS • It returns true if the argument subquery contains no duplicate tuples. • The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates). • NOT UNIQUE construct test the existence of duplicates in the sub query. Syntax: SELECT column-names FROM table-name WHERE UNIQUE/NOT UNIQUE (SELECT column-name FROM table-name WHERE condition);