SlideShare a Scribd company logo
Advanced Query Techniques
Session Objectives
 Explain the UNION, EXCEPT and
INTERSECT operators.
 Explain subqueries.
 Describe joins.
 Describe the various types of joins.
Introduction
 In large enterprises, there are huge
volumes of data stored in
databases.
 Data can be spread over several
tables that are related to one
another.
 When data is stored in such tables,
there must be some means to
combine and retrieve the data from
those tables.
 Using SQL Server, there are a
number of ways to combine data
from multiple tables.
Database
Table 1
Table 2
Table N
Table ..
Combining Data Using Operators
SQL Server provides certain keywords,
also called as operators, to combine data
from multiple tables. These operators are:
 UNION
 INTERSECT
 EXCEPT
UNION Operator - 1
 Combines results from two different query statements
into a single resultset.
Syntax:
Query_Statement1
UNION [ALL]
Query_Statement2
where,
Query_Statement1 and Query_Statement2 are SELECT statements.
UNION Operator:
Example of using UNION -1
Journals:
Books:
Consider that you want to see the title_id and title of all the books and
journals in an online library. To accomplish this, the records from both the
tables have to be retrieved. The data in the tables are as follows:
Records of Books table are displayed first, followed by those
in Journals table. This is because the records are sorted by
default on the basis of the first column. In this case, they are
sorted on title_id.
Example of using UNION -2
ALL clause of UNION Operator
By default, the UNION operator removes duplicate records from the resultset.
But, if you use the ALL clause with UNION operator, then all the rows are
returned.
Consider that you have an additional table named Publications with the
following data in the online library, and that the table has records as shown:
Example of ALL with UNION
The figure shows how to combine the data in the tables Books
and Publications using UNION with ALL. The query
displays all the records from both the tables.
INTERSECT Operator -1
The tables Publications and Books contain four records each:
Consider that you want to display only the rows that are common to both the
tables. To do this, you will need to use an operator named INTERSECT.
INTERSECT Operator -2
The INTERSECT operator is used with two query
statements to return a distinct set of rows that are
common to both the query statements.
Syntax:
Query_Statement1
INTERSECT
Query_Statement2
where,
Query_Statement1 and Query_Statement2 are SELECT statements.
Example of using INTERSECT
Rules for using INTERSECT
The basic rules for using INTERSECT are:
 The number of columns and the order in which
they are given must be the same in both the
queries.
 The data types of the columns being used must be
compatible.
EXCEPT Operator
The two rules that apply to INTERSECT operator are also applicable for
EXCEPT operator.
Syntax:
Query_Statement1
EXCEPT
Query_Statement2
The EXCEPT operator returns all of the distinct
rows from the query given on the left of the
EXCEPT operator and removes all the rows
from the resultset that match the rows on the
right of the EXCEPT operator.
Example of using EXCEPT
Subqueries
 You can use a SELECT statement or a query to return
records that will be used as criteria for another SELECT
statement or query. The outer query is called parent
query and the inner query is called a subquery.
 The simplest form of a subquery is one which returns
just one column. The parent query can use the results of
this subquery using an = sign.
SELECT <ColumnName> FROM <table>
WHERE <ColumnName> =
(
SELECT <ColumnName> FROM <Table> WHERE
<ColumnName> = <Condition>
)
Syntax:
Example of Subqueries
Consider that you want to know the names of titles from the
database pubs which are published by the publisher ‘New
Moon Books’.
ANY, ALL, IN, and EXISTS
 You can use a subquery instead of a value in
a WHERE clause of a SELECT statement.
 ANY, ALL, IN, and EXISTS are keywords that
can be used with the WHERE clause of a
SELECT statement when the query returns
one column but one or more rows.
Example of using IN
EXISTS and NOT EXISTS
 The keyword EXISTS is used with a subquery to check the
existence of rows returned by the subquery. The subquery
does not actually return any data; it returns a value of
TRUE or FALSE.
SELECT <ColumnName> FROM <table>
WHERE [NOT] EXISTS
(
<Subquery_Statement>
)
Syntax:
Example of EXISTS
Consider that you want to determine if there
are any publishers who publish books in the
category of traditional cooking, that is,
‘trad_cook’. Here, you can use the
EXISTS keyword to check the existence of
any such books and then retrieve
information about their publishers. Example
1 shows the code for this.
Example 1
USE pubs
SELECT pub_id, pub_name, city
FROM publishers
WHERE EXISTS
(
SELECT pub_id FROM titles
WHERE pub_id = publishers.pub_id
AND type = ‘trad_cook’
)
Example of using NOT EXISTS
 Consider that you want to retrieve book details such as
name, type and published date for only those books that
are published by publishers other than ‘New Moon
Books’.
 The condition could be summarized as “publishers not
with pub_name New Moon Books”.
 This would result in the publisher information who are
other than ‘New Moon Books’.
 To perform this task, you need to use the NOT EXISTS
operator as shown in Example 2.
Example 2
USE pubs
GO
SELECT title, type, pubdate
FROM titles
WHERE NOT EXISTS
(
SELECT * FROM publishers
WHERE
pub_id = titles.pub_id
AND
pub_name = ’New Moon Books’
)
Output of Example 2

More Related Content

PPTX
Joins And Its Types
PPT
Join sql
PPTX
SQL JOIN
PPTX
Oracle: Joins
PPTX
MySQL JOIN & UNION
PPT
Sql join
Joins And Its Types
Join sql
SQL JOIN
Oracle: Joins
MySQL JOIN & UNION
Sql join

What's hot (18)

PPSX
Join query
PPTX
Sql joins inner join self join outer joins
PPT
Types Of Join In Sql Server - Join With Example In Sql Server
PPTX
V19 join method-c
PDF
7. Using Sub Queries
DOC
SQL Joins
PPTX
SQL UNION
PPTX
Sql joins
PPT
SQL Joinning.Database
PPT
Sql joins
PPTX
MS Sql Server: Joining Databases
PDF
SQL JOINS
PDF
04 quiz 1 answer key
PPTX
Computer Science:Sql Set Operation
PPTX
SQL JOINS- Reena P V
PPT
Oracle sql joins
PPTX
Inner join and outer join
PPT
Functions of ms excel 2003
Join query
Sql joins inner join self join outer joins
Types Of Join In Sql Server - Join With Example In Sql Server
V19 join method-c
7. Using Sub Queries
SQL Joins
SQL UNION
Sql joins
SQL Joinning.Database
Sql joins
MS Sql Server: Joining Databases
SQL JOINS
04 quiz 1 answer key
Computer Science:Sql Set Operation
SQL JOINS- Reena P V
Oracle sql joins
Inner join and outer join
Functions of ms excel 2003
Ad

Viewers also liked (19)

PDF
Tutorial Instalisasi Oracle 10g dan Setting User
PPT
Intro to Application Express
PPT
Intro oracle10gexpress
PPTX
Step By Step How To Install Oracle XE
PPT
IBM Informix Database SQL Set operators and ANSI Hash Join
PDF
Oracle intro to designer abridged
PPT
Time-Based Blind SQL Injection using Heavy Queries
PPTX
Oracle database introduction
PPTX
T sql語法之 cte 20140214
PPT
Managing Oracle Streams Using Enterprise Manager Grid Control
PPT
Transaction
PDF
Oracle dba trainining in hyderabad
PPTX
Oracle: Joins
PDF
Oracle 10g Installation
PPT
Advanced sql
PPT
Advanced Sql Training
PPTX
SQL Data Manipulation
PDF
Oracle Essentials Oracle Database 11g
PPT
4. SQL in DBMS
Tutorial Instalisasi Oracle 10g dan Setting User
Intro to Application Express
Intro oracle10gexpress
Step By Step How To Install Oracle XE
IBM Informix Database SQL Set operators and ANSI Hash Join
Oracle intro to designer abridged
Time-Based Blind SQL Injection using Heavy Queries
Oracle database introduction
T sql語法之 cte 20140214
Managing Oracle Streams Using Enterprise Manager Grid Control
Transaction
Oracle dba trainining in hyderabad
Oracle: Joins
Oracle 10g Installation
Advanced sql
Advanced Sql Training
SQL Data Manipulation
Oracle Essentials Oracle Database 11g
4. SQL in DBMS
Ad

Similar to Sql server ___________ (advance sql) (20)

PPTX
MergeResult_2024_02_09_08_59_11.pptx
PPTX
PostgreSQL (PostgreSQL is a versatile, open-source object-relational database...
PPTX
More Complex SQL and Concurrency ControlModule 4.pptx
PPTX
MULTIPLE TABLES
PPTX
Guide To Mastering The MySQL Query Execution Plan
PDF
Oracle SQL Part 3
PDF
Bt0075 rdbms with mysql 2
PPT
1 introduction to my sql
PPTX
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPTX
Day-2 SQL Theory_V1.pptx
PPTX
Data Manipulation Language.pptx
PPTX
SQL Server Learning Drive
PPTX
Sql slid
PPTX
Practical Tutorial about the PostgreSQL Database
PPTX
Relational Algebra in Database design.pptx
PPTX
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DOCX
CIS 515 Discussion post responses.Respondto the colleagu.docx
PPTX
Sql(structured query language)
PPTX
Structure query language (sql)
PPTX
Structure Query Language (SQL).pptx
MergeResult_2024_02_09_08_59_11.pptx
PostgreSQL (PostgreSQL is a versatile, open-source object-relational database...
More Complex SQL and Concurrency ControlModule 4.pptx
MULTIPLE TABLES
Guide To Mastering The MySQL Query Execution Plan
Oracle SQL Part 3
Bt0075 rdbms with mysql 2
1 introduction to my sql
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Day-2 SQL Theory_V1.pptx
Data Manipulation Language.pptx
SQL Server Learning Drive
Sql slid
Practical Tutorial about the PostgreSQL Database
Relational Algebra in Database design.pptx
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
CIS 515 Discussion post responses.Respondto the colleagu.docx
Sql(structured query language)
Structure query language (sql)
Structure Query Language (SQL).pptx

More from Ehtisham Ali (17)

PPT
Android tutorial
PPTX
Sql server ___________session_20(ddl triggers)
PPTX
Sql server ___________session3-normailzation
PPTX
Sql server ___________session2-data_modeling
PPTX
Sql server ___________session_19(triggers)
PPTX
Sql server ___________session_18(stored procedures)
PPTX
Sql server ___________session_17(indexes)
PPTX
Sql server ___________session_16(views)
PPTX
Sql server ___________session_15(data integrity)
PPTX
Sql server ___________session_11-12(joins)
PPTX
Sql server ___________session_10(group by clause)
PPT
Sql server ___________session_1-intro
PPT
Sql server ___________session 3(sql 2008)
PPT
Sql server ___________session 2(sql 2008)
PPT
Sql server ___________session 1(sql 2008)
PPTX
Sql server ___________data type of sql server
PPTX
Sql server ___________data control language
Android tutorial
Sql server ___________session_20(ddl triggers)
Sql server ___________session3-normailzation
Sql server ___________session2-data_modeling
Sql server ___________session_19(triggers)
Sql server ___________session_18(stored procedures)
Sql server ___________session_17(indexes)
Sql server ___________session_16(views)
Sql server ___________session_15(data integrity)
Sql server ___________session_11-12(joins)
Sql server ___________session_10(group by clause)
Sql server ___________session_1-intro
Sql server ___________session 3(sql 2008)
Sql server ___________session 2(sql 2008)
Sql server ___________session 1(sql 2008)
Sql server ___________data type of sql server
Sql server ___________data control language

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Cell Types and Its function , kingdom of life
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Pharma ospi slides which help in ospi learning
Anesthesia in Laparoscopic Surgery in India
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Microbial disease of the cardiovascular and lymphatic systems
PPH.pptx obstetrics and gynecology in nursing
Cell Types and Its function , kingdom of life
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
GDM (1) (1).pptx small presentation for students
TR - Agricultural Crops Production NC III.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Supply Chain Operations Speaking Notes -ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O7-L3 Supply Chain Operations - ICLT Program
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
VCE English Exam - Section C Student Revision Booklet
Pharmacology of Heart Failure /Pharmacotherapy of CHF

Sql server ___________ (advance sql)

  • 2. Session Objectives  Explain the UNION, EXCEPT and INTERSECT operators.  Explain subqueries.  Describe joins.  Describe the various types of joins.
  • 3. Introduction  In large enterprises, there are huge volumes of data stored in databases.  Data can be spread over several tables that are related to one another.  When data is stored in such tables, there must be some means to combine and retrieve the data from those tables.  Using SQL Server, there are a number of ways to combine data from multiple tables. Database Table 1 Table 2 Table N Table ..
  • 4. Combining Data Using Operators SQL Server provides certain keywords, also called as operators, to combine data from multiple tables. These operators are:  UNION  INTERSECT  EXCEPT
  • 5. UNION Operator - 1  Combines results from two different query statements into a single resultset. Syntax: Query_Statement1 UNION [ALL] Query_Statement2 where, Query_Statement1 and Query_Statement2 are SELECT statements. UNION Operator:
  • 6. Example of using UNION -1 Journals: Books: Consider that you want to see the title_id and title of all the books and journals in an online library. To accomplish this, the records from both the tables have to be retrieved. The data in the tables are as follows:
  • 7. Records of Books table are displayed first, followed by those in Journals table. This is because the records are sorted by default on the basis of the first column. In this case, they are sorted on title_id. Example of using UNION -2
  • 8. ALL clause of UNION Operator By default, the UNION operator removes duplicate records from the resultset. But, if you use the ALL clause with UNION operator, then all the rows are returned. Consider that you have an additional table named Publications with the following data in the online library, and that the table has records as shown:
  • 9. Example of ALL with UNION The figure shows how to combine the data in the tables Books and Publications using UNION with ALL. The query displays all the records from both the tables.
  • 10. INTERSECT Operator -1 The tables Publications and Books contain four records each: Consider that you want to display only the rows that are common to both the tables. To do this, you will need to use an operator named INTERSECT.
  • 11. INTERSECT Operator -2 The INTERSECT operator is used with two query statements to return a distinct set of rows that are common to both the query statements. Syntax: Query_Statement1 INTERSECT Query_Statement2 where, Query_Statement1 and Query_Statement2 are SELECT statements.
  • 12. Example of using INTERSECT
  • 13. Rules for using INTERSECT The basic rules for using INTERSECT are:  The number of columns and the order in which they are given must be the same in both the queries.  The data types of the columns being used must be compatible.
  • 14. EXCEPT Operator The two rules that apply to INTERSECT operator are also applicable for EXCEPT operator. Syntax: Query_Statement1 EXCEPT Query_Statement2 The EXCEPT operator returns all of the distinct rows from the query given on the left of the EXCEPT operator and removes all the rows from the resultset that match the rows on the right of the EXCEPT operator.
  • 16. Subqueries  You can use a SELECT statement or a query to return records that will be used as criteria for another SELECT statement or query. The outer query is called parent query and the inner query is called a subquery.  The simplest form of a subquery is one which returns just one column. The parent query can use the results of this subquery using an = sign. SELECT <ColumnName> FROM <table> WHERE <ColumnName> = ( SELECT <ColumnName> FROM <Table> WHERE <ColumnName> = <Condition> ) Syntax:
  • 17. Example of Subqueries Consider that you want to know the names of titles from the database pubs which are published by the publisher ‘New Moon Books’.
  • 18. ANY, ALL, IN, and EXISTS  You can use a subquery instead of a value in a WHERE clause of a SELECT statement.  ANY, ALL, IN, and EXISTS are keywords that can be used with the WHERE clause of a SELECT statement when the query returns one column but one or more rows.
  • 20. EXISTS and NOT EXISTS  The keyword EXISTS is used with a subquery to check the existence of rows returned by the subquery. The subquery does not actually return any data; it returns a value of TRUE or FALSE. SELECT <ColumnName> FROM <table> WHERE [NOT] EXISTS ( <Subquery_Statement> ) Syntax:
  • 21. Example of EXISTS Consider that you want to determine if there are any publishers who publish books in the category of traditional cooking, that is, ‘trad_cook’. Here, you can use the EXISTS keyword to check the existence of any such books and then retrieve information about their publishers. Example 1 shows the code for this.
  • 22. Example 1 USE pubs SELECT pub_id, pub_name, city FROM publishers WHERE EXISTS ( SELECT pub_id FROM titles WHERE pub_id = publishers.pub_id AND type = ‘trad_cook’ )
  • 23. Example of using NOT EXISTS  Consider that you want to retrieve book details such as name, type and published date for only those books that are published by publishers other than ‘New Moon Books’.  The condition could be summarized as “publishers not with pub_name New Moon Books”.  This would result in the publisher information who are other than ‘New Moon Books’.  To perform this task, you need to use the NOT EXISTS operator as shown in Example 2.
  • 24. Example 2 USE pubs GO SELECT title, type, pubdate FROM titles WHERE NOT EXISTS ( SELECT * FROM publishers WHERE pub_id = titles.pub_id AND pub_name = ’New Moon Books’ )