Академический Документы
Профессиональный Документы
Культура Документы
In this section we will explain some of the basic terminologies which will be required to
learn SQL. We will give an overview of what SQL is and what does it do etc.
What is Database?
A database is an organized collection of data, that is useful to us. The data inside in a
database can be modified, deleted or new data can be added. They are stored in the form
of records as shown in the table below:
The above table shows a single record. The columns-Emp_id, Emp_name, Age, Salary are
the fields or attributes, while the row containing the corresponding the values-1101, Ana,
28, 15000 is a single record.
There can be a number of records in a table and number of tables in a database. The
tables in a database are related to each other through one/more attributes/fields.
What is Dbms?
A DBMS is usually an inherent part of a database product. Some of the popular DBMSs
(actually they are all Relational DBMS) are-Oracle's line of database management
products, Sybase's products, Microsoft's SQL Server. On PCs, Microsoft Access is a popular
example of a single-or small-group user DBMS.
Basics
What is SQL
SQL, an acronym for Structured Query Language, is an ANSI (American National Standard
Institute) standard computer language. SQL statements are used for accessing and
manipulating data from these database systems. It works with RDBMS like Oracle,
Sybase, Microsoft SQL Server, Access, Ingres etc.
SQL:
What is a Query?
A Query is a statement containing SQL commands and reserved words, which when
executed returns a set of desired records known as result set. Actually queries are used as
an interface to manipulate a database and its contents.
For Example:
Data Type
A data type is a set of data with values having predefined characteristics. Each languge
has its own data types. Usually, a limited number of such data types come built into a
language. The language usually specifies the range of values for a given data type, how
the values are processed by the computer, and how they are stored. Some data types in
SQL are: char, number, date etc.
The various Data Types along with their description are shown below:
Data Type Description
char(size) Holds fixed-length character string. Size is specified in parenthesis. Max
255 bytes.
varchar(size) Holds variable-length character string. Max size is specified in
parenthesis.
number(size) Holds Number value with a max number digits specified in parenthesis.
Date Holds a Date value.
number(size,d Holds a Number value with a maximum number of digits of "size" total,
) with a maximum number of "d" digits to the right of the decimal.
Operators
The various Operators along with their description are shown below in tabular form:
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
LIKE String comparison test
AND Logical And returns TRUE when both the specified conditions are true
OR Logical Or returns TRUE when atleast one of the specified conditions is true
NOT Logical Not returns TRUE when none one of the specified conditions is true
SQL can be termed as a DDL i.e. Data Definition Language. The DDL part in SQL enables it
to create/delete/alter a database table. Through this DDL feature indexes, links between
tables as well as constraints can be defined.
The following statements/commands consist of DDL portion of SQL:
SQL can be termed as DCL i.e. Data Control Language. The DCL part of SQL are those
statements that control the behaviour of the database objects.
Semicolon(;) is the standard way to separate SQL statements from one another in
database systems that allow more than one SQL statement to be executed in the same
call to the server.
Note: We would abstain from using semicolon after each SQL statement in this tutorial.
However it is necessary to execute a query.
SQL Commands
SQL commands are used by Access, Oracle, MS SQL server etc. In short, if you use
databases, be it in VB, FoxPro, Access or anything else, at some stage you will need to
use SQL. SQL gives you complete control over databases, creating, deleting, modifying,
adding, reading, sorting, querying etc.
In this section, we will cover the SQL Commands which have been classified as:
The commands have been described with appropriate examples one at a time, covering all
the clauses.
SQL Select
The Select statement is used to retrieve desired records from a database table.
Syntax:
Example:
The above query on running will return a set of desired records (result set) from table
Employee as shown below:
EMPLOYEE Table
Result Set
Emp_name
Ana
Joe
Jack
Now lets take up an example where we want to view values from two column as discussed
in the query below:
the above query will yield the following result set from the table "Employee".
Emp_name Age
Ana 28
Joe 23
Jack 25
Thus we can include more one columns using comma to view values from more than one
table.
Example:
The above query on running will return the following set of records.
Result Set
Distinct keyword is used to retrieve values that are distinct or non-repetitive. The SQL
Select retrieves values from database table which may be repetitive. Adding the word
Distinct to Select, we can get rid of this problem.
Syntax:
Example:
S_name
Renee
James
Renee
Example:
S_name
Renee
James
We might want to retrieve records which satisfy a particular condition. For example, we
want to retrieve Employee names from database table Employee with salaries above
14000. To do this, we make use of the clause Where. Thus Where clause is used to specify
a selection criterion.
Syntax:
WHERE condition
The operators that can be used to specify the condition are listed below:
Comparison Operators
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
LIKE String comparison test
Example:
To get the names of all the employees with salaries above 14000 from table Employee
Emp_name
Ana
Jack
WHERE Emp_name='Ana'
the above query will produce the result set as shown below:
The Like condition can be used to search for a particular pattern in a column in a database
table.
Syntax:
Example:
The following SQL statement will display Employee names beginning with alphabet 'A'
Now Suppose, we want to retrieve all information about employees from "Employee" table
where the second character of names is 'n'. For that, we key in the following query:
AND & OR are logical operators and are used to join two or more single conditions. As we
have seen, WHERE clause is used to select data conditionally. But it has the limitation of
specifying single condition only. Hence AND & OR are used to specify compound conditions
(compound conditions are made by joining two or more single conditions using AND or
OR).
AND operator displays a record if All single conditions are True. OR operator displays a
record if Any of the single conditions are True
Syntax:
Example:
Result Set
Notice in the output above that only one record is displayed in the result-set because that
is the only record which satisfies both the specified condition.
Example:
Result set
Emp_id Emp_name Age Salary
1101 Ana 28 15000
1103 Jack 25 14500
Notice in the output above that 2 records are displayed in the result-set because both the
records satisfy atleast one out of the two specified condition.
Lets take up another example. Suppose, we want to retrieve all information about
employees from "Employee" table where either the second character of names is 'o' or
name is 3 characters long and first two characters is 'An'. For that, we key in the following
query:
SQL Not
Sql statements using NOT will process all rows in a table and display the result only when
none of the conditions specified usong the NOT operator are used.
Syntax:
Example:
Syntax:
Example:
The above query will select Emp_id and Emp_name from the Employee table where
Emp_name is equal to either: Ana or Joe. Thus the result displayed by this query is shown
below:
Emp_id Emp_name
1101 Ana
1102 Joe
While IN is used to select a value present in the list, NOT IN is used to exclude the rows
from the list mentioned.
For example, the following query:
Emp_id Emp_name
1103 Jack
The BETWEEN keyword is used to test whether or not a value is present between the two
values mentioned in the query followed by the keyword BETWEEN.
Syntax:
Example:
While BETWEEN is used to retrieve values present in the specified range, NOT BETWEEN is
used to exclude values between the specified range.
For example, suppose we want to select the "Emp_id", "Emp_name" and "Age" from
"Employee" table where age does not lie between 23 and 26 (including 23 and 26). We
type in the following query for that:
Order By Clause
ORDER BY is used to get the result in the sorted manner. Unless Explicitly stated, the
order by clause sorts the result in ascending order.
Syntax:
ORDER BY column_name
Example:
ORDER BY Emp_name
Result Set
Emp_id Emp_name
1101 Ana
1103 Jack
1102 Joe
Example:
Result Set
Emp_id Emp_name
1102 Joe
1103 Jack
1101 Ana
Example:
Now suppose we want to display names in reverse alphabetical order and subjects in
alphabetical order. To do so, we key in
S_name Sujects
Renee Computers
Renee Physics
James Maths
SQL Insert
INSERT INTO statement allows a new row to be inserted or added into a database table.
The values that are mentioned and to be inserted will be fed into the rows and they will
match up with the names of the columns that are specified correspondingly.
Syntax:
The column names can be explicitly specified for which data is to be inserted as shown
below:
Example:
will result in
Lets take another case in which the columns for which data is to be inserted are specified.
Example:
will result in
Syntax:
SELECT column_name(s)
FROM table2
For example, suppose we want to insert data into table "Supply" from various columns in
table "Client" as:
FROM Client
On executing the above query, all values from the columns- "client_id", "name",
"address", "city", "remarks", will be inserted into respective columns of table "Supply".
We can add condition i.e. using "WHERE" clause. For example, suppose we want to insert
data into table "Supply" from various columns in table "Client" where client_id contains
the value '1101CS'. We key in the following query for that:
FROM Client
SQL Update
Syntax:
UPDATE table_name
Example:
UPDATE Employee
SET Age = 28
WHERE Emp_id = 1105
Example:
UPDATE Employee
SQL Delete
Syntax:
Example:
It is also possible to delete all the records in a database table at one go, without deleting
the table. This implies that although all the records will be deleted, the table structure,
fields and indexes will continue to exist. This can be done by the following SQL statement:
or
The commands have been described with appropriate example one at a time covering all
the clauses.
SQL Create
Create a Database
Syntax:
Create Table
With CREATE TABLE, a new table can be created. A table can be considered as a basic
structure within which data is stored. It consists of rows and columns. A row represents a
single record while a column represents attributes/fields which can be thought of as one of
the components contributing to make a record. While creating a table, data types have to
be mentioned for each field.
Syntax:
Example:
The above statement creates an empty table (containing no records) named Details
having fields-first_name, Surname, Address and DOB.
Sometimes cases arise when records in database table do not have values for every field
either because of incomplete information during data entry or the field is not applicable for
each case. In such cases, a NULL value is placed in the column in the absence of a user
defined value and if the column created was NULLABLE i.e, Null values are allowed.
Null values are different from blank or a zero and can be inserted into columns of any data
type.
When a column is defined as NOT NULL, then a value must be entered into that column so
as to store it into the database table.
Syntax:
Example:
CREATE TABLE Details (First_name varchar(50) NOT NULL, Surname varchar(50), Address
char(50), DOB date)
The above query results in creation of a database table named Details with the fields-
First_name, Surname, Address, DOB. The Field - First_Name should contain a value for
each record and should not be left blank.
For finding out table(s) created by a user (the tables which user has access to) is:
The above query will display all those tables created by that user and/or has access to:
TNAME TABTYPE
Employee Table
Details Table
For finding out column details of a table we use DESCRIBE (or DESC).
Syntax:
DESCRIBE table_name
For example, to view the column details of the table "Details" that we created above, we
key in:
DESCRIBE Details
Note: DESCRIBE & SELECT statements are not a part of Data Definition Language.
Create Index
CREATE INDEX is used to create index over one or more columns in a table. Each index
has specific name. They are created to to locate rows (records) quickly and efficiently and
thus speed up the queries.
Syntax:
ON table_name (column_name)
Example:
The above statement creates an index named Emp_index on the field Emp_name of table
Employee.
To create index on a column in descending order, we make use of reserved word DESC as:
Unique Index
Indexes created above are simple indexes i.e, two rows can have same index values. But
as UNIQUE keyword is used for index creation, duplicate values are not considered.
Syntax:
ON table_name (column_name)
After a database table has been created and values have been inserted into it and stored,
it becomes necessary to prevent all columns being accessed by the users. Hence we
create views. A View is an object that is mapped to a SELECT sentence. A view is created
on the top of a base table and contains no data at all until a call for it is made. A view is
treated like a base table (the table on which the view is created) and hence queries can be
fired on it just like on any database table.
Syntax:
SELECT column_name(s)
FROM table_name
Example:
Create Sequence
Before coming to the command CREATE SEQUENCE, lets first try to understand what a
sequence is and why at all. do we need to create it.
Sequences are database objects that automatically generate sequential lists of numbers.
They are useful when creating surrogate key values for primary key fields. For example,
we can generate range of numbers starting from 1101 onwards, when new record is
added to the table, 1101 could be value of the primary field for the first record and so on.
Every sequence must have unique name. The command to create a sequence is CREATE
SEQUENCE.
The above query creates a sequence called emp_number_seqnce that starts with 1101
and increments by 1 each time the sequence runs new record.
After the sequence has been created, the next thing we want do is to insert it into a table.
Suppose that we want to insert a sequence value for "emp_id" field in the "Emp_detail"
(Emp_id,Emp_name, Age) table. Here is how we will do that:
VALUES (emp_number_seqnce.NEXTVAL,'Mohan',26,)
We inserted one record into the "Emp_detail" table using sequence generated values for
the "Emp_id" field. NEXTVAL, that has been used in the query to insert values above, is a
command that generates next available for the sequence. Remember you have to have
record in the department table with "Emp_name" of "Mohan" in order to insert this record
successfully. The above query finally yields the following result set:
We mention "DUAL" above, which is a virtual table with one row and one column. It has
been described in SQL FUNCTIONS SECTION in detail.
Alter Table
ALTER TABLE is used to add/drop/modify column(s) in a table structure of a database.
Syntax:
Example:
the above query will add a new field in the table Employee as shown below:
Similarly, a column can be dropped from a table by the following SQL statement:
We can also modify existing columns using ALTER with MODIFY clause.
Suppose we want to change the size of the column "Surname" from existing "varchar(50)"
to new size "varchar(40)" in table "Details" that we had created (in Create table section).
We key in the following the following query for that:
The above query will alter the size of the column.Notice that only new data type along
with he new size had to be mentioned. There is no need to specify the old data type along
with its corresponding size.
The alteration done can be checked by the DESCRIBE command, as done below:
DESCRIBE Details
As seen above the column size of "Surname" has been successfully updated.
SQL Drop
SQL DROP is used to drop or delete a table. Thus all the records containing inside it also
get deleted with the deletion of the table structure.
Syntax:
Example:
On running the above query, the table named Employee gets deleted and with that,
records are also lost.
Drop Index
DROP INDEX deletes an existing index which was created over a column name in a
database table.
Syntax:
For example, to delete an index named Emp_index which was created over a field/column
in a table named Employee, we key in the following query:
Syntax:
Example:
Drop Database
Syntax:
Example:
The above query deletes the database named Emp_database and with that, all the tables
inside it containing records are deleted too.
Drop Sequence
Syntax:
To remove the sequence that we created in this tutorial enter the following command.
Select Into
The SELECT INTO command is used to make back_up copies of tables i.e, in case a table
is accidentally lost or destroyed, the back_up copy of it can be used.
Syntax:
FROM table_name
Example:
FROM Employee
The above query creates a backup copy of table Employee called Emp_backup.
Example:
FROM Employee
In the above example, a backup copy of Employee table called Emp_backup gets created
which resides in another database called Emp.mdb.
We can also create a backup copy containing selected columns instead of all columns of a
table.
Example:
FROM Employee
WHERE clause can be added to create a backup copy which satisfies a condition. This can
be explained by the following query:
FROM Employee
Constraints
Constraints are rules that are applied on data while values are keyed in columns so that
invalid data entry into the database tables can be prevented. The various Constraints are:
For Example, The following query creates a table Details in which a primary key constraint
called p_key has been defined:
CREATE TABLE Details (E_id varchar(10) CONSTRAINT p_key PRIMARY KEY, First_name
varchar(50), Surname varchar(50), Address char(50), DOB date)
A Primary Key, consisting of one or more columns in a database table, uniquely identifies
each row/record in the table. Thus the values fed into a column(s) which is a primary key,
must be unique (non-repeatitive) and should not contain Null Values.
If a single column is the primary key in a table it is called a Simple Key. When a Primary
Key is made of more than one columns (i.e, multicolumn), it is called as Composite Key.
Syntax:
Example:
CREATE TABLE Details (E_id varchar(10) PRIMARY KEY, First_name varchar(50), Surname
varchar(50), Address char(50), DOB date)
The above query creates a table Details where E_id is the primary key.
Lets take up an example where a primary key is made of two columns i.e we make a
composite key.
The above query creates a table "Sales_Details", whose Primary key is a composite key i.e
consists of more than one columns and they are-"detail_order_no" and "product_no".
A foreign key is a column (or group of columns) whose values are derived from a primary
key/unique key of some other table.
The database table that defines the Primary key is called as the Primary table while the
table that defines the Foreign key is called as the Foreign table.
The Primary Table is referenced in the table where foreign key is defined (Foreign Table)
using the keyword REFERENCES.
The existence of foreign implies a relation between two tables i.e, the Primary table and
the Foreign /table. Thus a Foreign Key in foreign table must have a corresponding Primary
Key in Primary Table.
An error message is displayed when an attempt is made to delete a record from Primary
Table when the corresponding records exist in Foreign table. There is an option of ON
DELETE CASCADE, which when specified in the foreign key definition and an attempt is
made to delete a record in the primary table, all corresponding records in the foreign table
along with record in the primary table gets deleted.
Syntax:
Example:
The above table defines Foreign Key-E_id, which is a Primary Key in Table Details.
Unique Constraint
The UNIQUE constraint is used to avoid keying in repeated values into a column which has
been declared UNIQUE. This ensures that the value stored into the column is unique (non-
repeated). A table ca have more than one columns with Unique constraint.
Syntax:
Example:
The above query results in creation of a database table named Details with the fields-E_id,
First_name, Surname, Address, DOB. The Field-E_id is unique, i.e no two values in this
field/column are same.
Check Constraint
CHECK constraints are generally specified as logical expression and hence evaluates either
True/False. Various Validations can be applied on values in a column of a database table
using CHECK constraint.
Syntax:
CREATE TABLE table_name (column_name(s) data_type(size) CHECK (logical expression))
Example:
The Above Query creates a table Details such that Values inserted into the fields
First_name & Surname are in upper case only. The above query can be re-written as:
The commands have been described one at a time, covering all the clauses
Before we go on to discuss Data Control Language (DCL) commands, lets understand the
concept of transaction.
What is a Transaction?
A transaction consists of one or more statements that are executed together as a unit, so
either all of the statements are executed, or none of the statements is executed.
For example, when a shopkeeper updates the amount of a particular product sold each
week, he will also want to update the total amount sold to date. However, he will not want
to update one without also updating the other; otherwise, the data will be inconsistent.
The way to ensure that either both actions occur or neither action occurs is to use a
transaction.
Savepoint
When a transaction is rolled back to a savepoint all changes made after that savepoint are
undone. Savepoint names must be distinct within a given transaction. If you create a
second savepoint with the same identifier as an earlier savepoint, then the earlier
savepoint is erased. After a savepoint has been created, you can either continue
processing, commit your work, roll back the entire transaction, or roll back to the
savepoint.
SAVEPOINT Savepoint_name
The above statement sets a named transaction savepoint whose name is savepoint_name.
Rollback
The Rollback Statement terminates the current transaction and rescinds all changes made
under the transaction. It rolls back the changes to the database.
Thus, Rollback statement is used to undo work done in the current transaction.
The above statement rolls back a transaction to the SAVEPOINT named savepoint_name.
Modifications that this transaction made to rows after the savepoint was set, are undone
in the rollback
Using Rollback, without the To Savepoint clause, ends the transaction and with that, all
the savepoints are erased. This undoes all changes in the current transaction.
Commit
Commit statement leaves all the changes made by the current transaction in effect i.e, it
saves all the changes brought about by the current transaction. Thus all changes resulting
from statements in the transaction will be made permanent with Commit.
The Commit Statement terminates the current transaction and makes all changes under
the transaction persistent. It commits the changes to the database.
However, Commit may fail if the transaction had been marked to be canceled before
Commit operates.
Having defined Commit, Rollback & Savepoint above, we now take up an example using
these three commands, given below:
Consider a case where Ana and Jack's salary are to updated in table Employee
(emp_name, emp_grade, dept, salary), check that total salary in the department does not
exceed Rs.1,00,000 then re-enter Jack's salary
UPDATE Employees
SET salary = 7000
WHERE emp_name = 'Ana'
SAVEPOINT ana_sal
UPDATE Employees
SET salary = 10000
WHERE emp_name = 'Jack'
SAVEPOINT jack_sal
UPDATE employees
SET salary = 9000
WHERE emp_name = 'Jack'
Commit
As seen from the above code that as the sum of salary exceeds 100000, the transaction is
rolled back to the save point named ana_sal meaning changes upto that point have been
updated but updations after that have been rolled back i.e made undone.
Nested Queries
In this section we discuss nested queries and why they are used.
Nested Queries
A nested query is a query that 'NESTS' inside a query, implying a query residing inside
another query. The nested queries are also termed as Subqueries. The statement/query
containing/enclosing a subquery is called as he parent query. The parent query makes use
of the rows/records returned by the sub query.
· to create tables/views
· to insert records in a table
· to update records in a table
· to supply values in SELECT/UPDATE/DELETE statements where conditions are specified
using clauses-WHERE, HAVING, IN etc.
To explain the subqueries further using examples we would be referring two tables-
Student and Students_Sports as shown below:
Student
Student_Sports
S_id Sport
0012 Basketball
0013 Basketball
0014 Basketball
0016 Volleyball
From the two tables above, suppose we want to retrieve the names of all students who do
not play sports.
SQL Join
Join is one of the most beneficial features of SQL and Relational Database Management
Systems. Till now we have been using a single table to select records. With Join, we can
refer to more than one table at time. Thus Join by allowing to link data from two or more
tables, truly makes the relational database management system-Relational.
Inner Join
Outer Join
Self Join
To Explain Join further, let us first of all consider two tables in a database:
Table Transaction
Table Customer
Cust_id Cust_name
AB04 Ana
CD03 Perry
EF04 Jane
GH05 Joe
For Explaining the various type of joins, we will be using these two tables.
Inner Join
Inner Join returns all those records from both the tables where a match is found. This
implies whenever a set of records from two tables satisfy the specified condition, they are
selected.
Syntax:
ON table1.column = table2.column
Example:
The query:
FROM Transaction
ON Transaction.Cust_id = Customer.Cust_id
will result in
T_Date Cust_name
03-02-2004 Ana
03-02-2004 Perry
04-02-2004 Ana
04-02-2004 Jane
Outer Join
Left Join
Right Join
Left Join
Left Join returns all the records from the first table even if no corresponding matches are
found in the second table.
Syntax:
FROM table1
ON table1.column = table2.column
Example:
The query:
SELECT Customer.Cust_name,Transaction.T_Date
FROM Customer
ON Customer.Cust_id = Transaction.Cust_id
Cust_name T_Date
Ana 03-02-2004
Ana 04-02-2004
Perry 03-02-2004
Jane 04-02-2004
Joe
As seen above, the T_date Field is empty for Cust_name Joe as no match was found for
Joe (of table Customer) in table Transaction.
Right Join
Left Join returns all the records from the second table even if no corresponding matches
are found in the first table.
Syntax:
FROM table1
ON table1.column = table2.column
Example:
The query
SELECT Transaction.T_Date,Customer.Cust_name,
FROM Transaction
ON Transaction.Cust_id = Customer.Cust_id
T_Date Cust_name
03-02-2004 Ana
03-02-2004 Perry
04-02-2004 Ana
04-02-2004 Jane
Joe
As shown above, Although no match was found for the last record of table Customer on
the First table Transaction. The field for which no match has been found is kept empty.
Self Join
There are times, when it becomes necessary to join a table to itself. This is known as Self
Join.
In Self Join, two copies of the same table are opened in the memory. Hence in the FROM
clause the table name is mentioned twice under aliases. This is done to avoid the situation
when the second table overwrites the copy of the first table since both have the same
name.
To Explain the Self Join further with an example conisder a table Emp_Manager below:
Suppose we want select the records displaying the names of the employees and their
respective managers from the above table. We key in the following query for that:
Employee Manager
Ana Perry
Perry Jane
The above output results as each Manager_id record (0320, 0224) of emp table is joined
with Emp_id records (0420, 0320, 0424, 0224) of mgr table.
SQL Union
SQL Union is used to join the results of two queries together. It is similar to Join with one
big exception and that is, the selected columns, while using Union, must be of same data
type. Queries using Union always return distinct i.e, non-repetitive values.
Syntax:
SQL Statement1
Union
SQL Statement2
Client_Local
C_id Client_name
L11 ABC
L12 DEF
L13 HIJ
L15 RST
L16 OPQ
Client_Foreign
C_id Client_name
F11 XYZ
F12 UVW
F13 RST
F14 OPQ
Now we use the Union to select all the client names that are distinct. We key in the
following query:
Union
Client_name
ABC
DEF
HIJ
RST
OPQ
XYZ
UVW
Although client_name 'RST' and 'OPQ' appeared in both the tables i.e, twice, still in the
result set duplicate values have been removed. Thus the two client names appear only
once in the result set.
Union All
Union All is similar to Union except that the former does not remove duplicate values from
the result set. This implies that the values in the result set using Union All might not be
distinct and may have repetitive values.
Syntax:
SQL Statement1
Union All
SQL Statement2
Example:
Union All
Client_name
ABC
DEF
HIJ
RST
OPQ
XYZ
UVW
RST
OPQ
As seen above, client_name 'RST' and 'OPQ' are listed twice in the result set.
Intersect
Using Intersect, multiple queries can be put together and their output can be combined.
Intersect outputs only those rows/records that are produced by both the queries. This
implies queries using Intersect will include only those rows that are fetched by both the
queries.
Syntax:
SQL Statement1
Intersect
SQL Statement2
Lets take up an example to understand it better. We will consider the two tables for that
namely, table "Student and table" "Student_Sport" as shown below:
Student
Student_Sport
S_id Sport
0111 Volleyball
0112 Basketball
0225 Basketball
0119 Volleyball
0445 Volleyball
Now, suppose we want to retrieve the names all students who play 'Volleyball' and stay in
'CVR' hostel.
Intersect
Lets analyze how the Intersect keyword gives the final result set from output of two
queries. The first query in the Intersect example above i.e:
S_id Name
0111 Ana
0112 Perry
S_id Name
0111 Ana
The Intersect clause picks up those records that are common in both queries. Thus from
the above two result sets, applying the Intersect clause, we get the final set as shown
below:
S_id Name
0111 Ana