0% found this document useful (0 votes)
8 views87 pages

CH 4

The document provides an overview of SQL, covering data types, DDL, DML, DCL, TCL, operators, and SQL functions. It details various data types such as CHAR, VARCHAR, DATE, NUMBER, LONG, and RAW, along with commands for creating, altering, and managing database structures. Additionally, it explains the use of operators and functions for data manipulation and retrieval in SQL.

Uploaded by

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

CH 4

The document provides an overview of SQL, covering data types, DDL, DML, DCL, TCL, operators, and SQL functions. It details various data types such as CHAR, VARCHAR, DATE, NUMBER, LONG, and RAW, along with commands for creating, altering, and managing database structures. Additionally, it explains the use of operators and functions for data manipulation and retrieval in SQL.

Uploaded by

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

CHAPTER-4

SQL
(STRUCTURED QUERY LANGUAGE)

By- Shalu Kushwah


DATA TYPES

TYPES DATATYPE
❑ CHAR(size)
❑ VARCHAR(size)/VARCHAR2(size)
❑ DATE
❑ NUMBER(P,S)
❑ LONG
❑ RAW/LONG RAW
1. CHAR(SIZE)

• This data type is used to store character strings values of fixed length.
• The size represents length of character should be stored
• This data can store maximum 255 characters.

• Example: Name CHAR(60)


2. VARCHAR(SIZE)/VARCHAR2(SIZE)

• This data type used store variable length alphanumeric data.


• The maximum size of this data type is 4000 characters.
• Example:- name VARCHAR(20)
3. DATE

• This data type is used to store date and time.


• The standard format is DD-MON-YY for example 21-JUN-09.
• Date time stores time in the 24-hours format.
• Range of this data type is January 1, 4712 B.C. to December
31, 4712 A.D.
• Example: dob date;
4. NUMBER(P,S)

• The NUMBER data type is used store numbers (both Integer


and floating point numbers).
• We can store number up to 38 characters long.
• The precision (P), determines the maximum length of number,
and scale (s), determines the point sign (.) right from a
number(P).
• Example: id number(2,10)
5. LONG

• This data type is used to store variable length character strings


up to 2 GB.
• LONG data can be used to store binary data in ASCII format.
• A table may contain only one column of type LONG
• Ex: contact LONG;
6. RAW/LONG RAW

• The RAW/LONG RAW data type are used to store binary data,
such as digitized picture or image
• RAW data type can have a maximum length of 255 bytes.
• LONG RAW data type can contain up to 2 GB.
• EX: area LONG RAW;
DATABASE LANGUAGE
DDL
(DATA-DEFINITION LANGUAGE)

• “We specify a database schema by a set of definition expressed by a special language called
a data-definition language(DDL)”.
• DDL is used to specify a database’s structure, which includes its tables, views, indexes, and
constraints.
• DDL statements only modify the database’s schema; they have no direct effect on the data
within the database.
• DDL declarations are irreversible and difficult to undo.
• DDL commands generally used for design or define database
• CREATE, ALTER, TRUNCATE, DROP TABLE
1. CREATE

• Create command used to create a table in


database.
• Syntax: Create table <table name>
( <columnname1> <datatype> (<size>),
<columnname2> <datatype> (<size>));
• Example: create table client_master (client_no
varchar2(6), name varchar2(20), city varchar2(15),
pincode number(8),state varchar2(15) );
2.ALTER

• Alter command used to modify structures of a table.


• Alter command can be used to add ,modify, or drop columns in a table
Syntax:
Adding New Columns
Alter table TableName Add (NewColumnName Datatype(size), NewColumnName
Datatype(size)….);
Modifying Existing Columns
Alter table TableName Modify (ColumnName NewDatatype(NewSize));
Dropping(deleting) Existing Columns
Alter table TableName Drop column columname;
Example:
• 1). alter table client_master add(telephone_no number(10));
• 2) alter table product_master modify(SELL_PRICE number(10,2));
• 3) alter table emp drop column dept;
ALTER(RENAME)

This command renames the already existing table.


Syntax: Alter table old_tablename rename to
new_tablename;
Example : Alter table Student rename to Student_10.
3. TRUNCATE

• TRUNCATE TABLE used to delete all data from a table


• Logically, this is equivalent to DELETE statement that deletes all
rows
• TRUNCATE command is faster than DELETE command
• The number of deleted rows are not returned
Syntax:
• TRUNCATE TABLE <TableName>
Example:
• TRUNCATE TABLE client_master;
4. DROP

• DROP TABLE command is used to delete or destroy table


from a database

• Syntax:
DROP TABLE <TableName>

• Example:
DROP TABLE client_master;
DML
(DATA MANIPULATION LANGUAGE)

• Inserting, updating, removing, and retrieving data from a


database are all possible with DML.
• DML commands come in the following types: SELECT, INSERT,
UPDATE, DELETE, and MERGE.
• DML statements have a direct impact on the database’s data.
• In the event of an error, data can be recovered thanks to the
reversibility of DML statements.
1. INSERT

• Used to insert data into a table or create a new row in table.


• Syntax:
Insert into <table name>
(<columnname1>,<columnname12>) values
(<expression1>,<expression2>);

Example:
Insert into table client_master Values (‘C00001’,’RAHUL’);
2. SELECT

The SELECT command is used to retrieve selected rows from one or more tables
Syntax:
• 1). SELECT * FROM <TableName>;
• 2). SELECT <ColumnName1>,<ColumnName1> From <TableName>;
• 3). SELECT * FROM <TableName> WHERE <Condition>; Etc

Example:
• 1). SELECT * FROM client_master;
• 2). SELECT name, city FROM client_master;
• 3). SELECT * FROM client_master Where city=’Bombay’;
3. DELETE

Delete command used to delete data or rows from a table


Delete command used to delete
• Selected rows from table
• All the rows from table
Syntax:
1) Delete from <table name>;
2) Delete from <table name> Where <Condition>;
Example:
1) Delete from client_master;
2) Delete from client_master Where client_no=’C00001’;
4. UPDATE

• The UPDATE command is used to change or modify data


of a table
• Update command used to update
Selected rows from table
All the rows from table
• Syntax: Update <table name> Set <columnname1> =
<expression1>, <columnname1> = <expression2>;
• Example: Update client_master Set city=’Bombay’;
DIFFERENCE B/W DDL & DML

DDL DML
• It helps us define a database's structure or • It allows us to manipulate, i.e., retrieve,
schema and deals with how data is stored in the
update, and delete the data stored in the
database.
database.
• The full form of DDL is Data Definition Language.
• The DDL commands have no further
• The full form of DML is Data Manipulation
classification. Language.
• The commonly used commands under DDL • The DML commands are classified as
language are: CREATE, DROP, ALTER,TRUNCATE procedural and non-procedural (declarative)
and RENAME.
DMLs.
• DDL commands are auto-committed, so changes
that happen in the database will be permanent. • The commonly used commands under DML
• DDL commands made changes permanent; language are: INSERT, UPDATE, DELETE and
therefore, we cannot roll back these statements. SELECT.
• DDL commands have no use of a WHERE clause • DML commands are not auto-committed, so
because here, filtration of records is not possible.
database changes are not permanent.
• The DDL command affects the entire database or
table. • DML commands do not make changes
permanent; therefore, rollback is possible for
these statements.
DCL(DATA CONTROL LANGUAGE)

• DCL includes commands such as GRANT and REVOKE which mainly deal with
the rights, permissions, and other controls of the database system.
• GRANT-Assigns new privileges to a user account, allowing access to specific
database objects, actions, or functions.
Syntax:- GRANT privilege_type [(column_list)] ON [object_type] object_name
TO user [WITH GRANT OPTION];
• Removes previously granted privileges from a user account, taking away their
access to certain database objects or actions.
Syntax:- REVOKE [GRANT OPTION FOR] privilege_type [(column_list)] ON
[object_type] object_name FROM user [CASCADE];
TCL
(TRANSACTION CONTROL LANGUAGE)

• Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group are
successfully completed. If any of the tasks fail, the transaction fails.
• Therefore, a transaction has only two results: success or failure.
Command Description Syntax
Starts a new BEGIN TRANSACTION
BEGIN TRANSACTION
transaction [transaction_name];
Saves all changes
COMMIT made during the COMMIT;
transaction
Undoes all changes
ROLLBACK made during the ROLLBACK;
transaction
Creates a savepoint
SAVEPOINT
OPERATORS
ARITHMETIC OPERATORS

• Oracle allows arithmetic operators to used while viewing records from


table or while performing data manipulation operations such as Insert,
Update and Delete.
• These are:
+ Addition * Multiplication
**Exponentiation () Enclosed operation
-Subtraction / Division
Example: Select product_no, description, sell_price * 0.05 from
product_master;
LOGICAL OPERATORS

1. The AND Operator


The AND Operator allows creating an SQL statement
based on two or more conditions being met.
It can be used in any valid SQL statement such as
select, insert, or delete.
Example: Select product_no, description, sell_price *
0.05 from product_master where sell_price between
500 and 1100;
LOGICAL OPERATORS

2 . The OR Operator
The OR condition allows creating an SQL statement where
records are returned when any one of the conditions are
met
It can be used in any valid SQL statement such as select,
insert, or delete.
Example: select client_no, name, city, pincode from
client_master
Where pincode=4000054 or pincode=4000057;
LOGICAL OPERATORS

3. Combining the AND and OR Operator


The AND and OR conditions can be combined in a single SQL statement
It can be used in any valid SQL statement such as select, insert, or
delete.
4. The NOT Operator
The Oracle engine will process all rows in a table and display only those
records that do not satisfy the condition specified
Example: select * from client_master where not ( city=’Bombay’, or
city=’Delhi’ );
COMPARISON OPERATORS

• Comparison operators are used in condition to compare


one expression with other. The comparison operators are
=, <, >, >=, <=, !=, between, like, is null and in
operators.
❑Between operator is used to check between two values or
specific range
• Example:
• SQL>select * from salesman_master where salary between
5000 and 8000;
• The above select statement will display only those rows
where salary of salesman is between 5000 and 8000.
COMPARISON OPERATORS

❑ In operator:
• The IN operator can be used to select rows that match one of the values in a list
• SQL> select * from client_master where client_no in(C00001, C00003);
• The above query will retrieve only those rows where client_no is either in C00001 or C00003

❑ Like operator:
• Like operator is used to search character pattern,. The like operator is used with special character %
and _(underscore)
• SQL> select * from client_master where city like ‘ b% ’;
• The above select statement will display only those rows where city is start with ‘B’ followed by any
number of any characters.
• % sign is used to refer number of character ( it similar to * asterisk wildcard in DOS).
• While ¬_(underscore) is used to refer single character.
• Example-SQL> select * from client_master where name like ‘_ahul’;
SQL FUNCTIONS

Single row functions


DATE FUNCTION

ADD_MONTHS()
• It returns the date after adding the number of months in specific date.
• Syntax: ADD_MONTHS(date,number)
• Example: select ADD_MONTHS (’04-jun-2009’,2) from dual;
• Output: 04-AUG-2009
MONTHS_BETWEEN
• It returns the number of months between the specified dates.
• Syntax: MONTHS_BETWEEN(date1,date2)
• Example: select MONTHS_BETWEEN (’02-FEB-09’,’02-JAN-09’) from dual;
• Output: 1
DATE FUNCTION

• Round()
• This function round a date in specified format
• Syntax: ROUND(date,format)
• Example: select ROUND(sysdate,’year’) from dual; Output:-1-jan-
2013
• NEXT_DAY
• It returns the date of the first weekday after specified date.
• Syntax: NEXT_DAY(date,’char’)
• Example: select NEXT_DAY(‘04-FEB-09’,’FRIDAY’) from dual; Output: 06-FEB-
09
• TRUNC()
• This function trunc a date in specified format
• Syntax: trunc(date,format)
• Example: select trunc(sysdate,’year’) from dual; Output:-01-
jan-2012
DATE FUNCTION

GREATEST()
• It displays the latest date from a list of dates
• Syntax: GREATEST (date1, date2, date3 …)
• Example: select GRETEST(’02-FEB-09’, ’02-JAN-09’) from dual;
• Output: 02-JAN-09
NEW_TIME()
• It display the date in the required time zone
• Syntax: : NEW_TIME (date,currenttimezone,newtimezone)
• Example: select NEW_TIME(sysdate,'EST','HST') from dual;
• Output: 22-JUL-09
NUMERIC FUNCTION

ABS()
• It returns the absolute value.
• Syntax: ABS(n)
• Example: select ABS(-15) from dual; Output: 15
CEIL()
• It returns the smallest integer that is greater than or equal to a specific value
• Syntax: CEIL(n)
• Example: select CEIL(1.3) from dual; Output:2
• Example: select CEIL(2) from dual; Output:2
• Example: select CEIL(-2.3) from dual; Output: -2
NUMERIC FUNCTION

COS()
• It returns the cosine of a given value.
• Syntax: COS
• Example: select COS(45) from dual; Output: 1

COSH()
• It returns hyperbolic cosine of a given value.
• Syntax: COSH
• Example: select COSH(45) from dual; Output:
1.7467E+19
NUMERIC FUNCTION

EXP()
• It returns e raised to the nth power, where e=2.71828183.
• Syntax: EXP(n)
• Example: select EXP(5) “Exponent” from dual; Output: Exponent
148.413159
FLOOR()
• It returns the greatest integer that is less than or equal to a specific value.
• Syntax: FLOOR(n)
• Example: select FLOOR(1.3) from dual; Output:
1
• Example: select FLOOR(2) from dual; Output:
2
• Example: select FLOOR(-2.3) from dual; Output:
-3
NUMERIC FUNCTION

POWER()
• It returns the value raised to a given positive exponent.
• Syntax: POWER(value, exponent)
• Example: select POWER(3,2) from dual; Output: 9
• Example: select POWER(64,0.5) from dual; Output: 8
MOD()
• It divides a value by a divisor and returns the remainder.
• Syntax: MOD(value, divisor)
• Example: select MOD(100,10) from dual; Output: 0
• Example: select MOD(10,3) from dual; Output: 1
• Example: select MOD(-30.23,7) from dual; Output: -
2.23
NUMERIC FUNCTION

ROUND()
• It rounds a number to given number of digits of precision
• Syntax: ROUND(value, precision)
• Example: select ROUND(66.666,2) from dual; Output: 66.67
TRUNC()
• It truncates digits of precision from a number
• Syntax: TRUNC(value, precision)
• Example: select TRUNC(66.666,2) from dual; Output: 66.66
SQRT()
• It returns the square root given number
• Syntax: SQRT(n)
• Example: select SQRT(64) from dual; Output: 8
CHARACTER FUNCTION

INITCAP()
• Returns a string with the first letter of each
word in UPPER CASE
• Syntax: INITCAP(char)
• Example: select INITCAP(‘Rahul Kumar') from
dual;
• Output: Rahul Kumar
CHARACTER FUNCTION

LOWER()
• It takes any string or column and converts it
into lowercase
• Syntax: LOWER(string)
• Example: select LOWER(‘RAHUL’) from dual;
• Output: rahul
CHARACTER FUNCTION

UPPER()
• It takes any string or column and converts it
into upper case
• Syntax: UPPER(string)
• Example: select UPPER(‘rahul’) from dual;
• Output: RAHUL
CHARACTER FUNCTION

LTRIM()
• It removes character from the left of char with
initial characters removed up to the first
character not in set
• Syntax: LTRIM(char, set)
• Example: select LTRIM(‘RAHUL’,’R’) from dual;
• Output: AHUL
CHARACTER FUNCTION

RTRIM()
• It returns char with final character removed
after the last character not in the set. ’set’ is
optional, it defaults to spaces.
• Syntax: RTRIM(char, set)
• Example: select RTRIM(‘RAHUL’,’L’) from dual;
• Output: RAHU
CHARACTER FUNCTION

REPLACE()
• It replaces a character in a string with zero or more
character.
• Syntax: REPLACE(string1, character to be replaced,
characters)
• Example: select REPLACE(‘Hello’, ’o’, ’rec’ ) from dual;
• Output: hellrec
CHARACTER FUNCTION

SUBSTRING()
• It returns a substring from a given string
• It returns a portion of char, beginning at character m
exceeding up to n characters.
• Syntax: SUBSTR(string)
• Example: select SUBSTR(‘SECURE’,3,4) from dual;
• Output: CURE
CHARACTER FUNCTION

• TRANSLATE()
• • Replace a sequence of character in a string with
another set of character.
• • Syntax: TRANSLATE(string1,string to replace,
replacement string)
• • Example: select TRANSLATE(‘1sct523’,’123’,’7a9’) from
dual;
• Output: 7sct5a9
CONVERSION FUNCTION

TO_CHAR()
• It converts a value of DATE data type to CHAR value. It accept
a date as well as the format in which the date has to appear. The
format must be a date format
• Syntax: TO_CHAR(date, format)
• Example: select TO_CHAR(SYSDATE,’DD-MM-YY’) from dual;
• Output: 22-07-09
CONVERSION FUNCTION

TO_DATE()
• It converts a CHAR filed to a DATE filed.
• Syntax: TO_DATE (‘char’, format)
• Example: select TO_DATE(‘26/08/09’,’DD/MM/YY’) from dual;
• Output: 26-AUG-09
CONVERSION FUNCTION

TO_NUMBER()
• It converts a character value containing a number to a value
of NUMBER data type.
• Syntax: TO_NUMBER(’char’)
• Example: select TO_NUMBER(‘100’) from dual;
• Output: 100
MISCELLANEOUS FUNCTION

UID
• It returns an integer that uniquely identifies the session user.
• Example: select UID from dual;
• Output: 18
USER
• It returns the name by which the current user is know to Oracle.
• Example: select USER from dual;
• Output: scott
VSIZE
• It returns the number of bytes in the internal representation of an expression.
• Syntax: VSIZE(expression)
• Example: select VSIZE(‘SCT on the net’) from dual;
• Output: 14
MISCELLANEOUS FUNCTION

NVL
• It stands for Null value Substitution.
• Syntax: NVL(value, substitute)
• If the value is NULL, this function is equal to substitute.
• If the value is not NULL, this unction is equal to value.
• Example:- Table name: Shipping
Select NVL (weight, 43) from shipping;
Client Weight Client Weight
Johnson tools 59 Johnson tools 59
Inf Software 27 Inf Software 27
Peterson NULL Peterson 43
Industries Industries

• In the above output, the NVL function replaces the value specified in wherever it encounters a
NULL value. Hence, 43 is inserted for client Peterson Industries.
GROUP FUNCTION

AVG()
• It returns average value of the specified column, ignoring NULL values.
• Syntax: AVG(Column name)
• Example: select AVG(sell_price) from product_master;
• Output: 2012.345
MIN()
• It returns the minimum value in the specified column.
• Syntax: MIN(column name)
• Example: select MIN(sell_price) from product_master;
• Output: 250
GROUP FUNCTION

MAX()
• It returns the maximum value in the specified column.
• Syntax: MAX(column name)
• Example: select MAX(sell_price) from product_master;
• Output: 1500
SUM()
• It returns the sum of values of the specified column.
• Syntax: SUM(column name)
• Example: select SUM(salary) from salesman_master;
• Output: 65000
GROUP FUNCTION

COUNT()
• It returns the number of rows in specified column or the total number
of rows in the table.
• Syntax: COUNT(column name)
• Example: select COUNT(salesman_no) from salesman_master;
• Output: 15
• Syntax: COUNT(*)
• Example: select COUNT(*) from salesman_master;
• Output: 50
DECODE FUNCTION

It is transformation function that does an orderly value-by-value substitution.


Syntax: DECODE(string,if1,then1,if2,then2,…..,else)
Example:
Select supplier_name, DECODE (supplier_id, 10000, ’IBM’, 10001, ’Microsoft’, 10002,’Hewlett
Packard’, ’gateway’) result FROM suppliers;
The above decode statement is equivalent to the following IF-THEN-ELSE statement
IF supplier_id = 10000 THEN
Result: = ‘IBM’;
ELSEIF supplier_id = 10001 THEN
Result: = ‘Microsoft’;
ELSEIF supplier_id = 10002 THEN
Result: = ‘Hewlett Packard’;
ELSE
Result: = ‘gateway’;
END IF;
The Decode function will compare each supplier_id value, one by one
GROUP BY, HAVING BY AND
ORDER BY CLAUSE
GROUP BY CLAUSE

• GROUP BY clause is another section of the select statement


• This optional clause tells Oracle to group rows based on distinct values that
exist for specified columns
• The GROUP BY clause creates a data set, containing several sets of records
grouped together based on a condition
• Syntax:
• Select <column name1>,<column name2>, <column nameN>
AGGREGATE_FUNCTION (<Expression>) From Table Name WHERE <condition>
GROUP BY<column name1>,<column name2>,<column nameN>;
• Example: SELECT branch_no“branch_no”,COUNT(emp_no)”No Employees” From
emp_master GROUP BY branch_no;
HAVING CLAUSE

• HAVING Clause can be used in conjunction with the GROUP BY clause HAVING
imposed a condition on the GROUP BY clause which further filter the group
created by the groups by clause
• Syntax: Select <column name1>,<column name2>, <column nameN>
AGGREGATE_FUNCTION (<Expression>) From Table Name WHERE
<condition> GROUP BY<column name1>,<column name2>,<column
nameN>; HAVING <condition>
• Example: Select product_no,sum (qty_ordered) “total QTY ordered” From
sales_order GROUP BY product_no HAVING product_no=’P00001’ or
product_no=’P00004’ HAVING clause is specified row displayed on screen.
ORDER BY CLAUSE

• ORDER BY is use want the information it return sorted in


the order specify.
• Syntax: Select <column name1>,<column name2>,
<column nameN> From Table Name Where <condition>
ORDER BY <column name1>;
• Example: Select feature, section, page from NEWSPAPER
Where section=’F’ ORDER BY feature;
SET OPERATORS
UNION CLAUSE

• The UNION clause merges or combines the output of two or more queries into a single set of
rows and columns
• Multiple queries can be put together and their output combined using the UNION clause.
• The output of both queries will be displayed as above.
• Output : Record only in query one + records only in query two + a single set of records which
is common in both queries

• The output of both queries will be displayed as above.


• Output : Record only in query one + records only in query two + a single set of records which
is common in both queries
UNION CLAUSE

Client_no Name City Salesman_no Name City


C00001 Ivan bay Bombay S00001 Kiran Bombay
Ross S00002 Manish Delhi
C00002 Vandana Madras S00003 Ravi Bombay
C00003 Pramala Bombay
Table Name: Table Name:
client_master salesman_master
Query:- ID Name
Select salesman_no “ID”, name from C00001 Ivan bayross
salesman_master Where city=’bombay’ C00003 Pramala
UNION Select client_no “ID”, name from S00001 Kiran
client_master Where city=’bombay’; S00003 Ravi

OUTPUT
UNION CLAUSE

Restriction on UNION clause :


• The number of column in all the queries should be
same.
• The data type of columns in each query should be
same
• Unions cannot be used in Sub queries
• Union cannot be used with aggregate functions
INTERSECT CLAUSE

• The INTERSECT clause outputs only those rows produced by both queries intersected.
• The output of INTERSECT clause will include only those rows that are retrieved by both the
queries.

• The output of both queries will be displayed as above


• The final output of INTERSECT clause will be:
• Output: A single set of Records which is common in both queries.
• Example: Retrieve the salesman name in ‘Bombay’ whose efforts have resulted into at least
one sales transaction
INTERSECT CLAUSE

Order_no Order_da Sman_no Salesman_no Name City


te S00001 Kiran Bombay
O19001 12-Apr-08 S00001
S00002 Manish Delhi
O19002 25-Dec-08 S00003
S00003 Ravi Bombay
O19003 19-Oct-08 S00001
O19004 02-May- S00002 Table Name:
Table Name:
08 salesman_master
sales_order
Query:-
select sman_no, name from Sman_no name
salesman_master where city='bombay' S00001 Kiran
INTERSECT
select salesman_master.sman_no , name S00003 Ravi
from salesman_master, sales_order where
salesman_master.sman_no=sales_order.sma OUTPUT
n_no;
MINUS CLAUSE

• The MINUS clause outputs the rows produced by the first


query, after filtering the rows retrieved by the second
query.
MINUS CLAUSE

• The output of both queries will be displayed as above


• The final output of MINUS clause will be:
• Output: Records only in query one
• Example: Retrieve all the product number of non-moving
items from the product_master table.
MINUS CLAUSE

Order_no product_ Product_n Descriptio


no o n
O19001 P00001 P00001 1.44
floppies Select product_no from
O19001 P00004
O19001 P00006 P00002 Monitors product_master
P00003 Mouse MINUS
O19002 P00002
P00004 1.22 Select product_no from
O19002 P00005 floppies Product_no
sales_order_details;
O19003 P00003
P00005 Keyboard
O19004 P00001 s P00007
O19005 P00006 P00006 CD drive
P00008
O19005 P00004 P00007 HDD
P00009
O19006 P00006 P00008 1.44
drive
Table Name: Table Name:
P00009 1.22 drive
sales_order_det product_master
ails
JOINS
JOINS

• The process of forming rows from two or more tables by


comparing the contents of a related column is called
Joining tables.
• The resulting table is called a JOIN between the tables.
Types of
Joins

1. Equi 2. Non- 3. Self 4. Outer


Join Equi Join Join Join
1. EQUI JOIN

• A join based on an exact match between two columns is called an Equi Join
• The comparison operator in the join condition is ‘=’
• Example:
• Table Name: emp Table Name: dept
Ename Eid Sal Deptno Deptno Deptnam Location
e
Rahul E01 1000 10
10 Sales Mumbai
Vishal E02 1500 15
15 Accounts Chennai
Ajit E03 2000 20
20 Purchase Mumbai
• select ename,eid,location from emp,dept where emp.deptno=dept.deptno;
• The above join query will retrieve the name, id and location of all employees
• Output: Ename Eid Location
Rahul E01 Mumbai
Vishal E02 Chenna
i
Ajit E03 Mumbai
2. NON-EQUI JOIN

• Joins which use comparison operators other than ‘=’ are called Non-Equi joins.
• Example: Table Name: emp Table Name: dept
Ename Eid Sal Deptn Deptno Deptnam Location
o e
Rahul E01 1000 10 10 Sales Mumbai
Vishal E02 1500 15 15 Accounts Chennai
Ajit E03 2000 20
20 Purchase Mumbai

Select ename, location from emp, dept Where sal BETWEEN(“operator other than ‘=’”)
1000 AND 2000;
The above join query willEname
retrieve the name, and location of employees having salary
Location
between 1000 and 2000Vishal Chennai
Output:
3. SELF JOIN

• A join that joins one row in table with another row in the same table is called Self Join.
• Using the table alias names these two identical tables can be joined.
• From <TableName> [<alias1>], <TableName> [<alias2>]…
• Example: Table Name: employee OUTPUT
Eid Ename Manager_ Ename Manager_n
no o
E00001 Rahul E00002 Rahul Vishal
E00002 Vishal E00005 Vishal Ronak
E00003 Ajit E00004 Ajit Prem
E00004 Prem
E00005 Ronak

• select e1.ename,e2.ename from employee e1,employee e2where e1.manager_no =


e2.eid;
• The above query will retrieve the names of the employees and the names of their
respective manager from the employee table
4. OUTER JOIN

Outer joins are joins that return matched values and


unmatched values from either or both tables.
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

• Note: LEFT JOIN is also refered to as OUTER LEFT JOIN.


RIGHT JOIN is also refered to as OUTER RIGHT JOIN. FULL
OUTER JOIN is also refered to as OUTER JOIN.
SYNTAX:-

SELECT column_name(s)
FROM table1
(INNER/LEFT/RIGHT/FULL OUTER) JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
I. INNER JOIN

• The INNER JOIN keyword selects records that have matching values in both tables.
SELECT ProductID, ProductName, CategoryName FROM Products INNER JOIN Categories
ON Products.CategoryID = Categories.CategoryID;
ProductID ProductN CategoryI Price CategoryID CategoryNam Description
ame D e
1 Beverages Soft drinks,
1 Chais 1 18 coffees, teas,
2 Chang 1 19 beers, and
ales
3 Aniseed 2 10
2 Condiments Sweet and
Syrup
savory
TABLE- PRODUCT sauces,
relishes,
ProductID ProductName CategoryName spreads, and
seasonings
1 Chais Beverages
3 Confections
TABLE- CATEGORYDesserts,
2 Chang Beverages candies, and
3 Aniseed Syrup Condiments sweet breads

OUTPUT
II. LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the right
side,
SELECTif there is no match.
ProductID, ProductName, CategoryName FROM Products LEFT JOIN Categories ON
Products.CategoryID = Categories.CategoryID;
ProductID ProductN CategoryI Price CategoryID CategoryNam Description
ame D e
1 Beverages Soft drinks,
1 Chais 1 18 coffees, teas,
2 Chang 1 19 beers, and
ales
3 Aniseed 2 10
2 Condiments Sweet and
Syrup
savory
TABLE- PRODUCT sauces,
relishes,
ProductID ProductName CategoryName spreads, and
seasonings
1 Chais Beverages
3 Confections
TABLE- CATEGORYDesserts,
2 Chang Beverages candies, and
3 Aniseed Syrup Condiments sweet breads

OUTPUT
III. RIGHT JOIN
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching
records from the left table (table1). The result is 0 records from the left side, if there is no
match.
SELECT ProductID, ProductName, CategoryName FROM Products RIGHT JOIN Categories
ON Products.CategoryID = Categories.CategoryID;
ProductID ProductN CategoryI Price CategoryID CategoryNam Description
ame D e
1 Beverages Soft drinks,
1 Chais 1 18 coffees, teas,
2 Chang 2 19 beers, and
TABLE- ales
3 Aniseed 3 10
PRODUCT 2 Condiments Sweet and
Syrup
savory
4 Rose 4 20 sauces,
relishes,
spreads, and
ProductID ProductName CategoryName seasonings
1 Chais Beverages 3 Confections
TABLE- CATEGORYDesserts,
candies, and
2 Chang Condiments sweet breads
OUTPUT
3 Aniseed Syrup Confections
IV. FULL JOIN(FULL OUTER JOIN)
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or
right (table2) table records.
SELECT ProductID, ProductName, CategoryName FROM Products FULL OUTER JOIN
Categories ON Products.CategoryID = Categories.CategoryID;
ProductID ProductN CategoryI Price CategoryID CategoryNam Description
ame D e
1 Beverages Soft drinks,
1 Chais 1 18 coffees, teas,
2 Chang 2 19 beers, and
ales
3 Aniseed 3 10
2 Condiments Sweet and
Syrup
savory
TABLE- PRODUCT sauces,
relishes,
ProductID ProductName CategoryName spreads, and
seasonings
1 Chais Beverages
3 Confections
TABLE- CATEGORYDesserts,
2 Chang Condiments candies, and
3 Aniseed Syrup Confections sweet breads

OUTPUT
SUBQUERIES

• Subqueries are queries that are nested inside another SQL query.
• They help us target specific rows to perform various operations in SQL. They are used to SELECT,
UPDATE, INSERT and DELETE records in SQL.
• There are different types of SQL subquery, like Single-row subquery, multiple row subquery,
multiple column subquery, correlated subquery, and nested subquery.
• Each type performs different roles, and their result is used depending on the user's requirement.
• Subqueries are present in the WHERE clause, FROM clause, or HAVING clause of the PARENT SQL
query.
• They are used with comparison operators and logical operators like >, <, >=, <>, <=, SOME,
ANY, ALL, and IN.
• They execute before the outer query at the run time and pass the result to complete the
statement.
• Subqueries are used to compare an expression to the output and check if any row gets selected.
• A maximum of 255 subquery levels can be nested in a WHERE clause. The FROM clause has no
limit in nesting subqueries. In the real world, we encounter not more than five subqueries. So, 255
is too large to be set as a limit.
( SELECT [DISTINCT] subquery_select_parameter
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )
TYPES OF SUBQUERIES

• Imagine that we are famous artists who sell their artworks in art galleries all over the
world. Let's see what the tables in our database look like:
TABLE- Paintings TABLE-
id city Sales_agent
gallery last_n first_n galler agenc
1 Jaipur id name price id
_id ame ame y_id y_fee
2 Kolkata Pattern 1 Brown Denis 2 2250
1 3 5000
3 Madhubani s
2 Ringer 1 4500 2 White Kate 3 3120
TABLE- Galleries 3 Gift 1 3200 3 Black Sarah 2 1640
id gallery_id Violin
1 2 4 Lesson 2 6700 4 Smith Helen 1 4500
2 3 s Stewa
Curiosi 5 Tom 3 2130
4 1 5 2 9800 rt
ty
TABLE- Managers
I. SINGLE ROW SUBQUERY

• Subqueries that return a single row as an output to


their parent query are called single-row subqueries. painting price avg_price

• Single-row subqueries are used in a SQL SELECT Patterns 5000 5840


statement with HAVING clause, WHERE clause, or a
FROM clause and a comparison operator. Ringer 4500 5840

• Single-row subqueries are used in the SELECT Gift 3200 5840


statement.
Violin
Example- 6700 5840
Lessons
SELECT name AS painting, price, (SELECT
AVG(price)FROM paintings) AS avg_price FROM Curiosity 9800 5840
paintings;
II. MULTIPLE ROW SUBQUERY

• Subqueries that return multiple rows as an output to their parent query are called
multiple-row subqueries.
• Multiple row subqueries can be used in a SQL SELECT statement with a HAVING
clause, WHERE clause, a FROM clause, and a logical operator(ALL, IN, NOT IN, and
ANY).
Example-
SELECT AVG(agency_fee) FROM sales_agents WHERE id NOT IN (SELECT id FROM
managers); agency_fee
1885
III. MULTIPLE COLUMN SUBQUERIES

• Subqueries that return multiple columns as an output to


their parent query are called multiple-column
subqueries.
Example-
SELECT id, name, price FROM paintings WHERE (name,
price) IN (SELECT name, MIN(price) FROM paintings);

gallery_
id name price
id
3 Gift 1 3200
IV. CORRELATED SUBQUERIES

• Subqueries that return multiple columns as output depending on the information


obtained from the parent query are called correlated subqueries. The
interdependence of the inner and outer query makes it complicated to understand.
• Correlated subqueries can be used in SELECT statements using WHERE and FROM
clauses.
Example-
SELECT city, (SELECT count(*) FROM paintings p WHERE g.id = p.gallery_id)
total_paintings FROM galleries city
g; total_painting
s
Jaipur 2
Kolkata 2
Madhubani 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy