Sunteți pe pagina 1din 19

SQL SERVER 6.

5
Chapter-4/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Subqueries and data manipulation statementsw
SCOPE
Performing subqueries
Nested SELECT statements
Type of subqueries
Correlated subqueries
SELECT INTO
UNION operator
Inserting Rows
Inserting Partial Data
Default Options
Inserting Rows with SELECT
Inserting Rows with Stored Procedures
Updating Rows
Updating Based On Data from Other Tables
Deleting Rows
Removing Rows Based On Data in Other Table
SQL SERVER 6.5
Chapter-4/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
PERFORMING SUBQUERIES
SELECT statements can be nested within other statements like SELECT, INSERT,
UPDATE or DELETE statements. These nested SELECT statements are called sub-
queries.
To use a sub-query, use the inner query within the parentheses to specify that it should be
evaluated before the outer query.
Nesting SELECT statements (Nested queries)
The nested or inner SELECT statement within another SELECT, INSERT, UPDATE
or DELETE statement is evaluated and the result is available to the outer statement.
A sub-query can return a single value, such as an aggregate, which can be used
wherever a single value can be used.
If a sub-query produces a column of values, it can only be used in the WHERE clause
where an expression can be used.
A sub-query can be nested inside the WHERE or HAVING clause of an outer
SELECT, INSERT, DELETE or UPDATE statement, or inside another sub-query.
There is no practical limit of nesting.
If a table appears only in a sub-query and not in the outer query, then columns from
that table cannot be included in the output (the select_list of the outer query).
EXAMPLE
To find the books that are of the same price as the book The Gourmet Microwave, there are 2 ways.
Either in two steps.
or, in a single step using subquery.
In two steps:
Step 1:
SELECT price FROM titles WHERE title = The Gourmet Microwave
OUTPUT:
price
---------
2.99
SQL SERVER 6.5
Chapter-4/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Step 2:
SELECT title, price FROM titles WHERE price = 2.99
OUTPUT:
title price
------------------------------- -------
You Can Combat Computer Stress 2.99
The Gourmet Microwave 2.99
Using subquery
SELECT title, price FROM titles WHERE price =
(SELECT price FROM titles WHERE title = The Gourmet Microwave)
Types of sub-queries
Sub-queries can be used in these contexts:
WHERE expression [NOT] IN
WHERE expression comparison_operator [ANY | ALL]
WHERE [NOT] EXISTS
IN operator
The result of a sub-query with IN or NOT IN will return a list of values.
The outer query makes use of the results returned by the inner query.
EXAMPLE
SELECT pub_name FROM publishers WHERE pub_id IN
(SELECT pub_id FROM titles WHERE type = psychology)
OUTPUT:
pub_name
----------------
New Moon Books
Binnet & Hardley
The statement is evaluated in two steps.
The inner query returns the identification numbers of the publishers who have published books on
psychology.
SQL SERVER 6.5
Chapter-4/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

These values are substituted into the outer query, which finds the names that match with the
identification numbers in the publishers table.
The second step looks like this:
SELECT pub_name FROM publishers WHERE pub_id IN (0877, 0736)
ANY operator
Compares a value to each value returned by a list or subquery.
IN operator is equivalent to =ANY.
> ANY means greater than at least one value. In other words, greater than minimum.
For example , > ANY(1,2,3) means greater than 1.
Thus, in > ANY, for a row to satisfy the condition specified in the outer query, the
value in the column that introduces the subquery must be greater than at least one of
the values in the list of values returned by the subquery.
EXAMPLE
SELECT emp_id FROM employee
WHERE job_lvl > ANY (SELECT job_lvl FROM employee WHERE pub_id =
9999)
OUTPUT:
The query finds the employees whose job levels are larger than the minimum job level for pub_id
9999.
The inner query finds a list of job levels for pub_id 9999.
The outer query looks at all values in the list and finds employees with job level larger than the lowest
job level of pub_id 9999.
ALL operator
Forces the specified relation for the column of a WHERE clause to be true for all
values returned by the sub-query.
NOT IN is equivalent to !=ALL.
Using the > comparison operator i.e. > ALL means greater than every value. In other
word, greater than the largest value. For example, > ALL (1,2,3) means greater than
3.
> ALL means that for a row to satisfy the condition specified in the outer query, the
value in the column that introduces the subquery must be greater than each value in
the list of value returned by the subquery.
SQL SERVER 6.5
Chapter-4/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
SELECT emp_id FROM employee
WHERE job_lvl > ALL (SELECT job_lvl FROM employee WHERE pub_id =
9999)
OUTPUT:
The query finds the employees whose job levels are larger than the maximum job level for pub_id
9999.
The inner query finds a list of job levels for pub_id 9999.
The outer query looks at all values in the list and finds employees with job level larger than the largest
job level of pub_id 9999.
EXISTS keyword
When a sub-query is introduced with the keyword EXISTS, it functions as an
existence test.
The WHERE clause of the outer query tests for the existence of rows returned by the
sub-query.
The sub-query doesnt produce data; it returns a value: TRUE or FALSE.
EXAMPLE
Example 1
SELECT au_lname, au_fname FROM authors WHERE EXISTS
(SELECT * FROM publishers WHERE authors.city = publishers.city)
OUTPUT:
Finds authors who live in the same city as a publisher.
An alternate way to get the same result.
SELECT au_lname, au_fname FROM authors WHERE city = ANY
(SELECT city FROM publishers)
Example 2
SELECT title FROM titles WHERE EXISTS
(SELECT * FROM publishers WHERE pub_id = titles.pub_id AND city
LIKE C%)
OUTPUT:
Finds titles of books published by any publisher located in the city that begins with the letter C.
SQL SERVER 6.5
Chapter-4/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Sub-query restrictions
The select_list of a sub-query introduced with a comparison operator can include only
one expression or column name.
If the WHERE clause of the outer statement includes a column name, it must be join
compatible.
EXISTS can operate on SELECT *, and IN can operate on select_list.
Columns of image and text type can not be included in the sub-query.
The DISTINCT keyword cannot be used with sub-queries that include a GROUP BY
clause.
A view created with a sub-query cannot be updated.
A subquery cannot include an ORDER BY clause, a COMPUTE clause or an INTO
keyword.
Correlated Sub-queries
Previous queries were all evaluated by executing the sub-query once, and substituting
the resulting value or values into the WHERE clause of the outer query.

A correlated query is one in which the WHERE clause references a table in the
FROM clause of the outer query.

In this case, sub-query is evaluated for each row of the table referenced in the outer
query.

Thus, the sub-query is repeatedly executed, once for each row that might be selected
by the outer query.

A correlated query is used to answer multi-part questions whose answer depends on
the value in each row of the parent query.
EXAMPLE
To find all the titles whose price is more than the average price of the books of the same publication as that
book .
Main query
SELECT title_id, pub_id, price FROM titles
WHERE price > (Average price of the books of the same publication as that book)
SQL SERVER 6.5
Chapter-4/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Sub-query
SELECT AVG(price) FROM titles
WHERE pub_id = (Book rows value of PUB_ID)
Correlated Subquery
SELECT title_id, pub_id, price FROM titles x
WHERE price > ( SELECT AVG(price) FROM titles WHERE pub_id = x.pub_id)
SELECT INTO
A SELECT statement with an INTO clause allows you to define a table and put data
into it without going through the usual data definition process.
SELECT INTO creates a new table based upon results of a query.
If a table already exists with the same name, this statement will fail.
The new table is based on the
columns specified in the select_list.
the table named in the FROM clause.
rows chosen in the WHERE clause.
Syntax:
SELECT select_list
INTO new_table_name
FROM table_list
WHERE search_conditions
Remarks:
By default, the SELECT INTO statement allows to create only a temporary table.
The SELECT INTO clause selects into a new permanent table only if the select
into/bulkcopy database option is set. (Covered later)
To select rows into a table that already exists, INSERT statement must be used.
If columns in the select_list have no titles, then the columns in the newly created table
will have no names.
Columns with no names can only be referenced with SELECT * FROM tablename.
Therefore, columns might need to be aliased.
New column headings should not have spaces.
SQL SERVER 6.5
Chapter-4/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Example 1
SELECT title = SUBSTRING (title, 1, 40), price = price * 1.1
INTO #table1
FROM titles
SELECT * FROM #table1
OUTPUT:
Lists the first 40 characters of each title, along with the price if increased by 10 percent.
The results are placed in the temporary table #table1.
The SELECT statement is used to see the results.
UNION operator
The UNION operator allows to manipulate the results of two or more queries by
combining the results into a single set.
A UNION results in an increase in number of rows.
Whereas a join results in increase in number of columns.
The column structure and datatypes have to be compatible.
Syntax:
SELECT select_list [INTO clause]
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]
[UNION [ALL]
SELECT select_list
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]]
[ORDER BY clause]
[COMPUTE clause]
SQL SERVER 6.5
Chapter-4/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
By default, UNION operator removes duplicate rows from the result set.
Using ALL option includes all rows in the result set.
All select_list in the UNION statement must have the same number of columns,
similar datatypes, and must occur in the same order.
If the UNION statement contains an ORDER BY clause, the entire results set is
sorted.
Columns names come from the first SELECT statement.
EXAMPLE
SELECT title, stor_name, ord_date, qty
FROM titles, sales, stores
WHERE titles.title_id = sales.title_id
AND stores.stor_id = sales.stor_id
UNION
SELECT title, No sales, null, null
FROM titles
WHERE title_id NOT IN (SELECT title_id FROM sales)
OUTPUT:
The first set is derived from a three-table join.
The result set is united to the second result set which retrieves information about titles that have no
sales.
title stor_name ord_date qty
--------------- ------------ --------- -------
Net Etiquette No sales NULL NULL
The Psycho No sales NULL NULL
Sushi News & Brews Jun 15 20
Is Anger Barnums Sep 13 75
: : : :
CLASSROOM EXERCISE
1. What is the difference between a correlated sub-query and a sub-query?
What makes it a correlated subquery?
2. What is the function of SELECT statement with an INTO clause?
3. Find the names of authors who have participated in writing at least
one book of type popular_comp. (Hint: Multiple nested query)
4. Is <>ANY equivalent to NOT IN?
SQL SERVER 6.5
Chapter-4/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

MODIFYING DATA
Insertion of rows
The INSERT statement adds a new row to the table.
It consists of :
(a) INSERT statement
(b) VALUES clause
INSERT statement
It specifies the table or view into which the row is to be inserted.
The table should be existing, before the INSERT statement can be used.
It can contain a column list to specify certain columns instead of the entire row.
VALUE clause
It specifies the data to be inserted.
It is a required keyword used to introduce the list of values for each column in the
column_list or table.
Character and date data must be enclosed in the quotes.
Syntax:
INSERT [INTO]
{table_name | viewname} [ (column_list)]
VALUES { value_list }
EXAMPLE
CREATE TABLE applicant
(fname varchar(10), lname varchar(10), address varchar(10))
INSERT INTO applicant
VALUES (Alton, john, 2 BLOCK)
OUTPUT:
A new applicant is added to the table applicant with all the details.
SQL SERVER 6.5
Chapter-4/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Inserting partial data
Data need not be specified in the VALUES clause for the columns that allow NULL
or a default value. (Default value is a value that is added automatically added when
user does not specify any value explicitly. Defaults are covered later in detail)
In the INSERT clause, the column names should be listed for the data which is
supplied.
If a column_list is given, the data in the VALUES clause corresponds to those
columns only.
Syntax:
INSERT [INTO]
{table_name | view_name } [(column_list)]
VALUES { value_list }
EXAMPLE
INSERT INTO publishers (pub_id, pub_name)
VALUES(1212, Press Press)
SELECT * FROM publishers
WHERE pub_name = Press Press
OUTPUT:
A new publisher is added, with the ID and name without filling in the other information.
The city, state and country fields allow null values.
pub_id pub_name city state country
-------- --------- ----- ----- --------
1212 Press Press (null) (null) (null)
Default options
The DEFAULT VALUES clause inserts a row containing default values for all
columns. (Creation of defaults for columns is covered later )
The next appropriate value will be inserted if the column has IDENTITY property (an
automatically assigned incremented value, or it has the timestamp datatype.)
If a default for the column does not exist and the column allows NULLs, NULL will
be inserted.
If any column of the table does not have a default or does not allow NULL, an error
will be returned and the INSERT statement is rejected.
SQL SERVER 6.5
Chapter-4/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
INSERT tablename DEFAULT VALUES
DEFAULT
It inserts a default value for the specified column.
DEFAULT is not valid for a column with the IDENTITY property.
Columns with IDENTITY property should not be listed in the column_list or
value_clause.
Syntax:
VALUES ( DEFAULT | constant_expression [, DEFAULT | constant_expression])
EXAMPLE
Assuming table called table_name is already existing, which has four columns and the third column has a
default bound to it i.e. if no value is supplied, the default value should be inserted in the column
INSERT INTO table_name
VALUES ( 2422, abc, DEFAULT, pqr)
OUTPUT:
Inserts a default value for the third column.
Note: Creation of defaults is covered later
A default value is inserted if one exists for the column or for the user defined
datatype.
NULL is entered if NULL is specified for the column when the table was created and
no default value exists for the column.
If NULL is not allowed and a specified default does not exist, an error is generated,
and row is not added.
SQL SERVER 6.5
Chapter-4/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Inserting rows with SELECT
SELECT clause allows to insert rows into an existing table from one or more other
tables.
Rows can be inserted from the same table also.
Syntax:
INSERT table_name SELECT column_list
FROM table_list WHERE search_condition
INSERT table and the SELECT results set must be compatible in terms of the number
of columns, columns ordering, datatypes and so on.
If any table_name columns are omitted, either a default should exist, or a value
should be provided, or NULL is allowed for the columns omitted.
The INSERT SELECT inserts many rows.
EXAMPLE
INSERT stores
SELECT substring(au_id, 8, 4), au_lname, address, city, state, zip
FROM authors
OUTPUT:
Adds a new store for each author using the last four digit of ID as a new store ID, and authors last
name for the new store name.
Inserting rows with stored procedure
INSERT statement can populate a table with results returned from a stored procedure.
Thus, data can be imported from the remote systems.
Syntax:
INSERT [INTO]
{table_name | view_name } [(column_list)]
EXEC { procedure_name | @procedure_name_var}
[[@parameter_name=] {value | @variable [OUTPUT] | DEFAULT}
[,[@parameter_name = ] {value | @variable [OUTPUT] | DEFAULT }]]
SQL SERVER 6.5
Chapter-4/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
The table is loaded with data returned from SELECT statements in the stored
procedure.
The table must already exist.
Data returned from PRINT, RAISERROR, FETCH statements or other output is not
stored in the table.
Data returned from the SELECT statement must conform to the datatypes in the
existing tables column.
A procedure that returns multiple result sets appends the data to the table.
Note: For details, refer session no. 8
EXAMPLE
INSERT INTO emp_info
EXEC fetch_data
OUTPUT:
The fetch_data user-defined stored procedure pulls data from remote sites into local tables.
Note: Try this exercise after learning creation of user-defined stored procedure (session 8)
Updating row data
The UPDATE statement changes data in existing rows in a table.
It operates on only one table.
SET specifies the column(s) and changed value.
WHERE identifies specific rows to update.
Syntax:
UPDATE {table_name | view_name }
SET [{table_name | view_name}]
{ column_list1 | variable_list1 | }= expression
[,column_listn | variable_listn | }= expression]
[WHERE clause]
expressions is a column name, constant, function (aggregate functions are not allowed),or
any combination of column names, constants and functions connected by an operator(s)
or a subquery.
SQL SERVER 6.5
Chapter-4/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
If the UPDATE statement violates integrity constraints, the update does not take
place and the entire update is rolled back.
EXAMPLE
UPDATE applicant
SET fname = ALTON
WHERE fname = ALLEN
OUTPUT:
In the table applicant the applicant whose first name is ALLEN is changed to ALTON.
Updating Based on data from other tables
A table can be updated using data from other tables.
This is implemented using the FROM clause.
For each row in the table to be updated, it has to meet the criteria of the outer
WHERE clause.
The nested SELECT, which must be a single value SELECT executes once for each
row.
The selected value will update the specified row.
If nested SELECT statement is not a single value, the results are unspecified.
A single UPDATE statement can not update the same row twice
Syntax:
UPDATE table_name[(column_list)]
SET column_name = expression
FROM table_list
WHERE serach_condition
EXAMPLE
Assuming a table called member is already existing which has a field called first_name.
UPDATE member
SET first_name = ( SELECT fname FROM applicant
WHERE lname = DOILEY)
OUTPUT:
The first_name of the member in the member table is changed.
It is set to the first_name in the applicant table whose last_name is DOILEY.
SQL SERVER 6.5
Chapter-4/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Deleting rows
DELETE statement allows to remove one or more rows from a table.
Syntax:
DELETE [from] table_name
WHERE search_conditions
If no WHERE clause is specified, all rows will be deleted.
EXAMPLE
Example 1
DELETE applicant
WHERE fname = ALTON
OUTPUT:
A record from the applicant table is deleted whose first_name is ALTON.
Example 2
DELETE applicant
OUTPUT:
All the rows from the table applicant are deleted.
Removing Rows Based on data in other tables
Syntax:
DELETE [from] table_name
FROM {table_name [, { table_name}...]}
WHERE search_conditions
The WHERE clause in a DELETE statement can look at data in other tables and
determine whether a row in the given table should be deleted.
This allows naming of more than one table or view to use with a WHERE clause to
specify which rows to delete.
The FROM clause allows to delete rows from one table based on the data stored in
other tables .
SQL SERVER 6.5
Chapter-4/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
DELETE FROM titleauthor
FROM authors a, titles t
WHERE a.au_id = titleauthor.au_id
AND t.title_id = titleauthor.title_id
AND t.title LIKE %computers%
OUTPUT:
Deletes all records from the titleauthor table where the book title contains computers.
The TRUNCATE table statement
It removes all rows from the table.
Table structure continue to exit.
It is faster than DELETE statement because it does not logs the individual deletes.
DELETE statement removes rows one at a time and logs each deleted row as
transaction.
Immediately frees all the space occupied by that tables data and indexes.
TRUNCATE TABLE guarantees that all rows are removed from the table and cannot
be rolled back.
The statement cannot be used on a table referenced by a FOREIGN KEY constraint.
Syntax:
TRUNCATE TABLE [[database.]owner.] table_name
CLASSROOM EXERCISE
1. Can you modify more than one table with a single UPDATE, INSERT or
DELETE statement.
2. Can more than one row be modified with the above statements?
3. How do you insert the rows into a table from another table? Contrast
this with SELECT INTO.
SQL SERVER 6.5
Chapter-4/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

LAB EXERCISES
Use pubs database for the following:
1. Find the names of authors who have participated in writing at least one book
which is of type popular_comp.
2. Find the authors who live in California and who receive less than 30% of the
royalties for a book.
3. Find the names of the publishers who have not published books of type
business.
4. Perform the following query a) using subquery b) using join.
Double the price of all books published by New Moon Books.
5. Remove all records of sales of books of type business using a subquery. Can
the same operation be performed using joins?
6. Find the names of all books priced higher than the current minimum price.
7. Find the books priced higher than the lowest priced book in the type
trad_cook.
8. Use a correlated subquery to find the types of books that are published by more
than one publisher.
9. Find sales where the quantity is less than the average quantity for sales of that
title.
10. Find the names of publishers who do not publish books of type business.
11. Copy the structure (not data) of the table publishers to another table called
publishers2.
12. Insert into titles table, the following data:
title_id - BU2222, title - Faster1, type - business, pub_id - 1389,
price - NULL, advance - NULL, royalty - NULL, ytd_sales - NULL ,
notes - ok, pubdate - 06/17/87.
13. Insert only the following values in certain fields only:
title_id - BU1237, title - ABC, type - business, pub_id - 1389,
notes - great, pubdate - 06/18/86
14. Insert all the details of authors who live in San Francisco into a new table called
SanAuthors.
15. Delete all the authors from the authors table whose last name is McBadden.
16. Try out the examples given in the book.
SQL SERVER 6.5
Chapter-4/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
SELECT statement can be nested within other statements like SELECT, INSERT ,
DELETE and UPDATE statements. These nested SELECT statements are called
subqueries.
Subqueries can be used in three contexts:
WHERE expression [NOT] IN
WHERE expression comparison_operator [ANY / ALL]
WHERE [NOT] EXISTS
In correlated subqueries, subquery is evaluated for each row of the table referenced in the
outer query.
SELECT INTO defines a table and puts data into it.
UNION operator manipulates the results of two or more queries by combining the results
into a single set.
INSERT statement adds a new row to the table.
UPDATE statement is used to change the existing data in a table.
DELETE statement removes one or more rows from a table.
TRUNCATE TABLE statement is similar to DELETE statement except that it can be
used only to remove all rows from the table and does not log the delete operation.

S-ar putea să vă placă și