0% found this document useful (0 votes)
75 views

SQL Part 2

The MINUS command in SQL subtracts the results of the second query from the first query. It returns rows that are in the first query but not in the second. INTERSECT returns rows that are in both queries. SUBQUERIES allow embedding one SQL statement inside another statement in the WHERE or HAVING clause, and can be simple or correlated between the inner and outer queries.

Uploaded by

bella
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

SQL Part 2

The MINUS command in SQL subtracts the results of the second query from the first query. It returns rows that are in the first query but not in the second. INTERSECT returns rows that are in both queries. SUBQUERIES allow embedding one SQL statement inside another statement in the WHERE or HAVING clause, and can be simple or correlated between the inner and outer queries.

Uploaded by

bella
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

SQL Minus

The MINUS command operates on two SQL statements. It takes all the results from t
he first SQL statement, and then subtract out the ones that are present in the second
SQL statement to get the final result set. If the second SQL statement includes result
s not present in the first SQL statement, such results are ignored.

Syntax

The syntax for MINUS is as follows:

[SQL Statement 1]
MINUS
[SQL Statement 2];
The columns selected in [SQL Statement 1] and [SQL Statement 2] need to be of the s
ame data type for MINUS to work.
Example

We use the following tables for our example.


Table Store_Information
Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999


Boston 700 Jan-08-1999

Table Internet_Sales
Txn_Date Sales

Jan-07-1999 250

Jan-10-1999 535
Jan-11-1999 320
Jan-12-1999 750

To find all the dates where there are store sales but no internet sales, we use the foll
owing SQL statement:
SELECT Txn_Date FROM Store_Information
MINUS
SELECT Txn_Date FROM Internet_Sales;
Result:
Txn_Date
Jan-05-199
9
Jan-08-199
9

'Jan-05-1999', 'Jan-07-1999';, and 'Jan-08-1999' are the distinct values returned from
SELECT Txn_Date FROM Store_Information. Out of the three dates, 'Jan-07-1999' is
also returned from the second SQL statement,SELECT Txn_Date FROM Internet_Sale
s, so it is excluded from the final result set.
Please note that the MINUS command will only return distinct values.
Some databases may use EXCEPT instead ofMINUS. Please check the documentation
for your specific database for the correct usage.

SQL > Advanced SQL > Limit


The LIMIT clause restricts the number of results returned from a SQL statement. It is
available in MySQL.
Syntax

The syntax for LIMIT is as follows:


[SQL Statement 1]
LIMIT [N];
where [N] is the number of records to be returned. Please note that the ORDER BY cl
ause is usually included in the SQL statement. Without the ORDER BY clause, the res
ults we get would be dependent on what the database default is.
Example

We use the following table for our example.


Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

To retrieve the two highest sales amounts in Table Store_Information, we key in,

SELECT Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY Sales DESC
LIMIT 2;
Result:
Store_Name Sales Txn_Date
Jan-05-199
Los Angeles 1500
9
Jan-08-199
Boston 700
9

The SQL Server equivalent to LIMIT is TOP.


SQL > Advanced SQL > Intersect
The INTERSECT command in SQL combines the results of two SQL statement and returns only d
ata that are present in both SQL statements.
INTERSECT can be thought of as an ANDoperator (value is selected only if it appears in both stat
ements), while UNION and UNION ALLcan be thought of as an OR operator (value is selected if i
t appears in either the first or the second statement).
Syntax

The syntax for INTERSECT is as follows:


[SQL Statement 1]
INTERSECT
[SQL Statement 2];
The columns selected in [SQL Statement 1] and [SQL Statement 2] need to be of the same data t
ype for INTERSECT to work.
Example

We use the following tables for our example.


Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999


Boston 700 Jan-08-1999

Table Internet_Sales

Txn_Date Sales

Jan-07-1999 250

Jan-10-1999 535
Jan-11-1999 320
Jan-12-1999 750

To find out all the dates where there are both store sales and internet sales, we use the followi
ng SQL statement:
SELECT Txn_Date FROM Store_Information
INTERSECT
SELECT Txn_Date FROM Internet_Sales;
Result:
Txn_Date
Jan-07-1999

Please note that the INTERSECT command will only return distinct values.

SQL > Advanced SQL > Inline View


An inline view is a SELECT statement in theFROM clause. As mentioned in the View section, a vi
ew is a virtual table that has the characteristics of a table yet does not hold any actual data. In a
n inline view construct, instead of specifying table name(s) after the FROMkeyword, the source
of the data actually comes from the inline view.
Inline view is sometimes referred to as derived table. These two terms are used interchangeabl
y.
Syntax

The syntax for an inline view is,


SELECT "column_name" FROM (Inline View);
Example

Assume we have two tables: The first table isUser_Address, which maps each user to a ZIP code
; the second table is User_Score, which records all the scores of each user. The question is, how
to write a SQL query to find the number of users who scored higher than 200 for each ZIP code?
Without using an inline view, we can accomplish this in two steps:
Query 1
CREATE TABLE User_Higher_Than_200
SELECT User_ID, SUM(Score) FROM User_Score
GROUP BY User_ID
HAVING SUM(Score) > 200;
Query 2
SELECT a2.ZIP_CODE, COUNT(a1.User_ID)
FROM User_Higher_Than_200 a1, User_Address a2
WHERE a1.User_ID = a2.User_ID
GROUP BY a2.ZIP_CODE;
In the above code, we introduced a temporary table, User_Higher_Than_200, to store the list o
f users who scored higher than 200.User_Higher_Than_200 is then used to join to theUser_Add
ress table to get the final result.
We can simplify the above SQL using the inline view construct as follows:
Query 3
SELECT a2.ZIP_CODE, COUNT(a1.User_ID)
FROM
(SELECT User_ID, SUM(Score) FROM User_Score GROUP BY User_ID HAVING S
UM(Score) > 200) a1,
User_Address a2
WHERE a1.User_ID = a2.User_ID
GROUP BY a2.ZIP_CODE;
The code that is in red represents an inline view. There are two advantages on using inline view
here:
1. We do not need to create the temporary table. This prevents the database from having too
many objects, which is a good thing as each additional object in the database costs resources to
manage.
2. We can use a single SQL query to accomplish what we want.
Notice that we treat the inline view exactly the same as we treat a table. Comparing Query 2 an
d Query 3, we see that the only difference is that we replace the temporary table name in Quer
y 2 with the inline view statement in Query 3. Everything else stays the same.

SQL > Advanced SQL > Subquery

A subquery is a SQL statement that has another SQL query embedded in the WHER
E or theHAVING clause.

Syntax

The syntax for a subquery when the embedded SQL statement is part of the WHER
E condition is as follows:

SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");

[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also
be a text operator such as "LIKE". The portion in red is considered as the "inner query
," while the portion in green is considered as the "outer query."

Examples

We use the following tables for our examples.

Table Store_Information

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999San Diego250Jan-07-1999Los


Angeles300Jan-08-1999Boston700Jan-08-1999

Table Geography

Region_NameStore_NameEastBostonEastNew YorkWestLos AngelesWestSan DiegoE


xample 1: Simple subquery

To use a subquery to find the sales of all stores in the West region, we use the followi
ng SQL statement:

SELECT SUM (Sales) FROM Store_Information


WHERE Store_Name IN
(SELECT Store_Name FROM Geography
WHERE Region_Name = 'West');

Result:

SUM (Sales)2050

In this example, instead of joining the two tables directly and then adding up only th
e sales amount for stores in the West region, we first use the subquery to find out w
hich stores are in the West region, and then we sum up the sales amount for these st
ores.
Notice that in this example, the inner query and the outer query are independent of
each other. This type of subquery is called a simple subquery.

Example 2: Correlated subquery

If the inner query is dependent on the outer query, we will have a correlated subque
ry. An example of a correlated subquery is shown below:

SELECT SUM (a1.Sales) FROM Store_Information a1


WHERE a1.Store_Name IN
(SELECT Store_Name FROM Geography a2
WHERE a2.Store_Name = a1.Store_Name);

Result:

SUM (Sales)2750

Here, the inner query is used to make sure that SQL only sums up sales amount from
stores that appear in both the Store_Information and theGeography tables.

Notice the WHERE clause in the inner query, where the condition involves a table fro
m the outer query.

@@@@@@@@@
SQL > Advanced SQL > Intersect

The INTERSECT command in SQL combines the results of two SQL statement and retu
rns only data that are present in both SQL statements.

INTERSECT can be thought of as an ANDoperator (value is selected only if it appears i


n both statements), while UNION and UNION ALLcan be thought of as an OR operato
r (value is selected if it appears in either the first or the second statement).

Syntax

The syntax for INTERSECT is as follows:

[SQL Statement 1]
INTERSECT
[SQL Statement 2];

The columns selected in [SQL Statement 1] and [SQL Statement 2] need to be of the s
ame data type for INTERSECT to work.

Example

We use the following tables for our example.

Table Store_Information
Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999San Diego250Jan-07-1999Los
Angeles300Jan-08-1999Boston700Jan-08-1999

Table Internet_Sales

Txn_DateSalesJan-07-1999250Jan-10-1999535Jan-11-1999320Jan-12-1999750

To find out all the dates where there are both store sales and internet sales, we use t
he following SQL statement:

SELECT Txn_Date FROM Store_Information


INTERSECT
SELECT Txn_Date FROM Internet_Sales;

Result:

Txn_DateJan-07-1999

Please note that the INTERSECT command will only return distinct values.
@@@@@@@
SQL > Advanced SQL > Top

The TOP keyword restricts the number of results returned from a SQL statement in
Microsoft SQL Server.

Syntax

The syntax for TOP is as follows:

SELECT TOP [TOP argument] "column_name"


FROM "table_name";

where [TOP argument] can be one of two possible types:

1. [N]: The first N records are returned.

2. [M] PERCENT: The number of records corresponding to M% of all qualifying record


s are returned.

Examples

We use the following table for our examples.

Table Store_Information

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999San Diego250Jan-07-1999Sa


n Francisco300Jan-08-1999Boston700Jan-08-1999Example 1: [TOP argument] is an in
teger
To show the two highest sales amounts in TableStore_Information, we key in,

SELECT TOP 2 Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY Sales DESC;

Result:

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999Boston700Jan-08-1999

Example 2: [TOP argument] is a percentage

To show the top 25% of sales amounts from Table Store_Information, we key in,

SELECT TOP 25 PERCENT Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY Sales DESC;

Result:

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999

Next: SQL Subquery

SQL > Advanced SQL > Case

CASE is used to provide if-then-else type of logic to SQL. There are two formats: The f
irst is a Simple CASE expression, where we compare an expression to static values. Th
e second is a Searched CASEexpression, where we compare an expression to one or
more logical conditions.

Simple CASE Expression Syntax

The syntax for a simple CASE expression is:

SELECT CASE ("column_name")


WHEN "value1" THEN "result1"
WHEN "value2" THEN "result2"
...
[ELSE "resultN"]
END
FROM "table_name";

The ELSE clause is optional.

Simple CASE Expression Example

We use the following table for our example.


Table Store_Information

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999San Diego250Jan-07-1999Sa


n Francisco300Jan-08-1999Boston700Jan-08-1999

To multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San
Diego' by 1.5 while keeping the sales amount for other stores the same, we would us
e the following SQL statement using CASE:

SELECT Store_Name, CASE Store_Name


WHEN 'Los Angeles' THEN Sales * 2
WHEN 'San Diego' THEN Sales * 1.5
ELSE Sales
END
"New Sales",
Txn_Date
FROM Store_Information;

"New Sales" is the name given to the column with the CASE statement. This is an exa
mple of a simpleCASE expression, because the conditions listed, 'Los SQL > Advanced
SQL > Exists

EXISTS is a Boolean operator used in a subqueryto test whether the inner query retur
ns any row. If it does, then the outer query proceeds. If not, the outer query does not
execute, and the entire SQL statement returns nothing.

Syntax

The syntax for EXISTS is:

SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
(SELECT *
FROM "table_name2"
WHERE "condition");

Please note that instead of *, you can select one or more columns in the inner query.
The effect will be identical.

Example

We use the following tables for our example.

Table Store_Information

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999San Diego250Jan-07-1999Los


Angeles300Jan-08-1999Boston700Jan-08-1999
Table Geography

Region_NameStore_NameEastBostonEastNew YorkWestLos AngelesWestSan Diego

The following SQL query,

SELECT SUM(Sales) FROM Store_Information


WHERE EXISTS
(SELECT * FROM Geography
WHERE Region_Name = 'West');

produces the result below:

SUM(Sales)2750

At first, this may appear confusing, because the subquery includes the [region_name
= 'West'] condition, yet the query summed up sales for stores in all regions. Upon clo
ser inspection, we find that since the subquery returns more than zero row, the EXIS
TS condition is true, and the rows returned from the query "SELECT SUM(Sales) FRO
M Store_Information" become the final result.

Next: SQL CASE

SQL > Advanced SQL > IDENTITY

IDENTITY is used in Microsoft SQL Server to automatically insert numerical primary k


ey values to a table as new data is inserted. This is similar to the AUTO INCREMENT c
ommand in MySQL.

Syntax

The syntax for IDENTITY is as follows:

CREATE TABLE TABLE_NAME


(PRIMARY_KEY_COLUMN INT PRIMARY KEY IDENTITY ( [Initial_Value], [Interval] ),
...);

where [Initial_Value] is the first value of the primary key, and [Interval] is the interval
between two consecutive identity values. If no [Initial_Value] or [Interval] is specifie
d, the default for both is 1. In other words, the primary key for the first row would be
1, and subsequent rows would get a primary key value that is 1 larger than the previ
ous row.

Example

Assume we want to create a table that consists of a primary key, last name, and first
name. We use the following SQL:
CREATE TABLE USER_TABLE
(Userid int PRIMARY KEY IDENTITY(2,1),
Last_Name nvarchar(50),
First_Name nvarchar(50));

Upon creation, the table is empty.

We insert the first value:

INSERT INTO USER_TABLE VALUES ('Washington', 'George');

Now the table has the following values:

Table USER_TABLE

UseridLast_NameFirst_Name2WashingtonGeorge

Userid is 2 because we had specified the initial value to be 2.

Next we insert the second value:

INSERT INTO USER_TABLE VALUES ('Jefferson', 'Thomas');

Now the table has the following values:

Table USER_TABLE

UseridLast_NameFirst_Name2WashingtonGeorge3JeffersonThomas

userid for the second row is 3 because it is 1 larger than the previous Userid, which is
2.

SQL > Advanced SQL > DECODE Function

DECODE is a function in Oracle and is used to provide if-then-else type of logic to SQL
. It is not available in MySQL or SQL Server.

Syntax

The syntax for DECODE is:

SELECT DECODE ( "column_name", "search_value_1", "result_1",


["search_value_n"],
{"default_result"} );

"search_value" is the value to search for, and "result" is the value that is displayed.

[ ] means that the "search_value_npair can occur zero, one, or more times.
Example

We use the following table for our example.

Table Store_Information

Store_NameSalesTxn_DateLos Angeles1500Jan-05-1999San Diego250Jan-07-1999Sa


n Francisco300Jan-08-1999Boston700Jan-08-1999

To display 'LA' for 'Los Angeles', 'SF' for 'San Francisco', 'SD' for 'San Diego', and 'Othe
rs' for all other cities, we use the following SQL,

SELECT DECODE (Store_Name,


'Los Angeles', 'LA',
'San Francisco', 'SF',
'San Diego', 'SD',
'Others') Area, Sales, Txn_Date
FROM Store_Information;

"Area" is the name given to the column that theDECODE function operates on.

Result:

AreaSalesTxn_DateLA1500Jan-05-1999SD250Jan-07-1999SF300Jan-08-1999Others70
0Jan-08-1999

To achieve what DECODE does in MySQL and SQL Server, we would use the CASE fun
ction.

Next: SQL AUTO I

SQL > SQL String Functions > CAST Function

The CAST function in SQL converts data from one data type to another. For example,
we can use the CAST function to convert numeric data into character string data.

Syntax

The syntax of the CAST function is as follows:

CAST (expression AS [data type])

where [data type] is a valid data type in the RDBMS you are working with.

Examples

We use the following table for our examples.

Table Student_Score
Column NameData TypeStudentIDintegerFirst_Namechar(20)Scorefloat

This table contains the following rows:

Table Student_Score

StudentIDFirst_NameScore1Jenny85.22Bob92.53Alice904James120.1Example 1

SELECT First_Name, CAST(Score AS Integer) Int_Score FROM Student_Score;

Result:

First_NameInt_ScoreJenny85Bob92Alice90James120

In Example 1, we use the CAST function to convert the Score column from type FLOA
T to INTEGER. When we do this, different RDMBS have different rules on how to han
dle the numbers after the decimal point. In the above example, the numbers after th
e decimal point are always truncated.

Example 2

SELECT First_Name, CAST(Score AS char(3)) Char_Score FROM Student_Score;

Result:

First_NameChar_ScoreJenny85.Bob92.Alice90 James120

In Example 2, we use the CAST function to convert the SCORE column from type FLO
AT to CHAR(3). When we do this, we only take the first three characters. So, if there
are more than three characters, everything after the first three characters is discarde
d.

SQL > Advanced SQL > SEQUENCE And NEXTVAL

Oracle uses the concept of SEQUENCE to create numerical primary key values as we
add rows of data into a table. Whereas numerical primary key population for MySQL
and SQL Server is tied to individual tables, in Oracle the SEQUENCEconstruct is create
d separately and is not tied to an individual table.

SyntaxThe syntax for creating a sequence in Oracle is:

CREATE SEQUENCE SEQUENCE_NAME


[START WITH {Initial_Value}]
[INCREMENT BY {interval}];

{Initial_Value} is the starting value of the sequence, and {interval} is the interval betw
een consecutive sequence numbers. Both [START WITH] and [INCREMENT BY] are op
tional fields. If they are not specified, the default {Initial_Value} and {interval} are bot
h 1.

Example

Assume we have a table with the following structure:

Table USER_TABLE

UseridintegerLast_Namevarchar(50)First_Namevarchar(50)

and we want to use the following sequence to generate the userid:

CREATE SEQUENCE SEQ_USER START WITH 5 INCREMENT BY 5;

We specify that we want to use the sequence and the NEXTVAL function in the INSER
T INTOstatements in the following order:

INSERT INTO USER_TABLE VALUES (SEQ_USER.NEXTVAL, 'Washington', 'George');

INSERT INTO USER_TABLE VALUES (SEQ_USER.NEXTVAL, 'Jefferson', 'Thomas');

Now the table has the following two rows:

Table USER_TABLE

UseridLast_NameFirst_Name5WashingtonGeorge10JeffersonThomas

It is worth noting that a sequence is independent of a table. In other words, a sequen


ce can be used to generate primary key values for multiple tables, and the sequence
continues even if it is being applied to a different table. So, let's say for example we h
ave a second table, TableNEW_USERS, which has the same structure as table USER_T
ABLE, and we issue the following SQL command after executing the two SQL comma
nds above:

INSERT INTO NEW_USER VALUES (SEQ_USER.NEXTVAL, 'Adams', 'John');

Table NEW_USER will have the following row:

Table NEW_USER

UseridLast_NameFirst_Name15AdamsJohn

Userid is 15 because that is the next value after 10.

Angeles' and 'San Diego', are static values.

Result:
Store_NameNew SalesTxn_DateLos Angeles3000Jan-05-1999San Diego375Jan-07-19
99San Francisco300Jan-08-1999Boston700Jan-08-1999

Searched CASE Expression Syntax

The syntax for a searched CASE expression is:

SELECT CASE
WHEN "condition1" THEN "result1"
WHEN "condition2" THEN "result2"
...
[ELSE "resultN"]
END
FROM "table_name";

The ELSE clause is optional. "Condition" can consist of one or more logical statement
s.

Searched CASE Expression Example

We use the same Store_Information above. If we want to define the status of a store
's sale based on the following rules:

If Sales >= 1,000, it's a "Good Day"If Sales >= 500 and < 1,000, it's an "OK Day"If Sales
< 500, it's a "Bad Day"

We can use the following searched CASEexpression:

SELECT Store_Name, Txn_Date, CASE


WHEN Sales >= 1000 THEN 'Good Day'
WHEN Sales >= 500 THEN 'OK Day'
ELSE 'Bad Day'
END
"Sales Status"
FROM Store_Information;

Result:

Store_NameTxn_DateSales StatusLos AngelesJan-05-1999Good DaySan DiegoJan-07-


1999Bad DaySan FranciscoJan-08-1999Bad DayBostonJan-08-1999OK Day

Note that a simple CASE expression is a special case of a searched CASE expression. A
s an example, the following two CASE expressions are identical:

Simple CASE Expression:

SELECT Store_Name, CASE Store_Name


WHEN 'Los Angeles' THEN Sales * 2
WHEN 'San Diego' THEN Sales * 1.5
ELSE Sales
END
"New Sales",
Txn_Date
FROM Store_Information;

Searched CASE Expression:

SELECT Store_Name, CASE


WHEN Store_Name = 'Los Angeles' THEN Sales * 2
WHEN Store_Name = 'San Diego' THEN Sales * 1.5
ELSE Sales
END
"New Sales",
Txn_Date
FROM Store_Information;

You might also like