Sql ch 5

9
SQL Basics – Queries 2 Prof. Mukesh N. Tekwani Page 1 SQL – QUERIES 2 1. Explain the search conditions (predicates) in SQL There are 5 basic search conditions in SQL. These are also called as predicates. (i) Comparison test. Compares the value of one expression to the value of another expression. Use this test to select offices in the Eastern region, or salespeople whose sales are above their quotas. (ii) Range test. Tests whether the value of an expression falls within a specified range of values. E.g., to find salespeople whose sales are between 1,00,000 and 5,00,000. (iii) Set membership test. Checks whether the value of an expression matches one of a set of values. E.g., to select offices located in New York, Chicago, or Los Angeles. (iv) Pattern matching test. Checks whether the value of a column containing string data matches a specified pattern. E.g., to select customers whose names start with the letter "E." (v) Null value test. Checks whether a column has a NULL (unknown) value. E.g., to find the salespeople who have not yet been assigned to a manager. COMPARISON TEST In a comparison test, SQL computes and compares the values of two SQL expressions for each row of data. The expressions can be as simple as a column name or a constant, or they can be more complex arithmetic expressions. SQL offers six different ways of comparing the two expressions. These are =, < >, <, <=, >, >=. When SQL compares the values of the two expressions in the comparison test, three results can occur: If the comparison is true, the test yields a TRUE result. If the comparison is false, the test yields a FALSE result. If either of the two expressions produces a NULL value, the comparison yields a NULL result. Example 1: Find salespeople hired before 1988. SELECT NAME FROM SALESREPS WHERE HIRE_DATE < '01-JAN-88' Example 2: List the offices whose sales fall below 80 percent of target. SELECT CITY, SALES, TARGET FROM OFFICES WHERE SALES < (0.8 * TARGET) RANGE TEST The range test checks whether a data value lies between two specified values. It involves three SQL expressions. The first expression defines the value to be tested; the second and third expressions define the low and high ends of the range to be checked. The data types of the three expressions must be comparable. test-expression [NOT] BETWEEN low-expression AND high-expression The BETWEEN test

description

SQL

Transcript of Sql ch 5

Page 1: Sql ch 5

SQL Basics – Queries 2

Prof. Mukesh N. Tekwani Page 1

SQL – QUERIES 2

1. Explain the search conditions (predicates) in SQL

There are 5 basic search conditions in SQL. These are also called as predicates.

(i) Comparison test. Compares the value of one expression to the value of another

expression. Use this test to select offices in the Eastern region, or salespeople whose sales are above their quotas.

(ii) Range test. Tests whether the value of an expression falls within a specified range of values. E.g., to find salespeople whose sales are between 1,00,000 and 5,00,000.

(iii) Set membership test. Checks whether the value of an expression matches one of a set of values. E.g., to select offices located in New York, Chicago, or Los Angeles.

(iv) Pattern matching test. Checks whether the value of a column containing string data

matches a specified pattern. E.g., to select customers whose names start with the letter "E."

(v) Null value test. Checks whether a column has a NULL (unknown) value. E.g., to

find the salespeople who have not yet been assigned to a manager.

COMPARISON TEST

In a comparison test, SQL computes and compares the values of two SQL expressions for each row of data. The expressions can be as simple as a column name or a constant, or they can be more complex arithmetic expressions. SQL offers six different ways of comparing the two expressions. These are =, < >, <, <=, >, >=. When SQL compares the values of the two expressions in the comparison test, three results can occur: • If the comparison is true, the test yields a TRUE result. • If the comparison is false, the test yields a FALSE result. • If either of the two expressions produces a NULL value, the comparison yields a NULL result. Example 1: Find salespeople hired before 1988. SELECT NAME

FROM SALESREPS

WHERE HIRE_DATE < '01-JAN-88'

Example 2: List the offices whose sales fall below 80 percent of target.

SELECT CITY, SALES, TARGET FROM OFFICES

WHERE SALES < (0.8 * TARGET)

RANGE TEST

The range test checks whether a data value lies between two specified values. It involves three SQL expressions. The first expression defines the value to be tested; the second and third expressions define the low and high ends of the range to be checked. The data types of the three expressions must be comparable. test-expression [NOT] BETWEEN low-expression AND high-expression

The BETWEEN test

Page 2: Sql ch 5

SQL Basics– Queries 2

Page 2 [email protected]

A BETWEEN B AND C

is completely equivalent to: (A >= B) AND (A < = C)

Example 1: Find orders placed in the last quarter of 1989. SELECT ORDER_NUM, ORDER_DATE, MFR, PRODUCT, AMOUNT FROM ORDERS

WHERE ORDER_DATE BETWEEN '01-OCT-89' AND '31-DEC-89'

Example 2: Find the orders that fall into various amount ranges. SELECT ORDER_NUM, AMOUNT FROM ORDERS

WHERE AMOUNT BETWEEN 20000.00 AND 29999.99

Example 3: The negated version of the range test (NOT BETWEEN) checks for values that fall outside the range. List salespeople whose sales are not between 80 percent and 120 percent of quota. SELECT NAME, SALES, QUOTA

FROM SALESREPS WHERE SALES NOT BETWEEN (.8 * QUOTA) AND (1.2 * QUOTA)

SET MEMBERSHIP TEST The set membership test (IN) tests whether a data value matches one of a list of target values. Syntax: test-expression [NOT] IN (constant , )

The search condition X IN (A, B, C)

is completely equivalent to: (X = A) OR (X = B) OR (X = C)

Example 1: List the salespeople who work in New York, Atlanta, or Denver. (Codes 11, 22, 33) SELECT NAME, QUOTA, SALES FROM SALESREPS

WHERE REP_OFFICE IN (11, 13, 22)

Example 2: Find all orders placed with four specific salespeople. SELECT ORDER_NUM, REP, AMOUNT FROM ORDERS WHERE REP IN (107, 109, 101, 103)

PATTERN MATCHING TEST (LIKE): This test is used to retrieve rows where the contents of a text column match some particular text.

Page 3: Sql ch 5

SQL Basics – Queries 2

Prof. Mukesh N. Tekwani Page 3

Syntax: columnname [NOT] LIKE pattern

The pattern matching test (LIKE) checks to see whether the data value in a column matches a specified pattern. The pattern is a string that may include one or more wildcard characters. These characters are interpreted in a special way.

Wildcard Characters:

(i) The percent sign (%) wildcard character matches any sequence of zero or more characters. (ii) The underscore (_) wildcard character matches any single character. Example 1: Show the credit limit for Smithson Corp. Method 1: SELECT COMPANY, CREDIT_LIMIT

FROM CUSTOMERS WHERE COMPANY = 'Smithson Corp.'

Method 2: (using LIKE) SELECT COMPANY, CREDIT_LIMIT

FROM CUSTOMERS

WHERE COMPANY LIKE 'Smith% Corp.'

Example 2: If you are sure that the company's name is either "Smithson" or "Smithsen," for example, you can use this query: SELECT COMPANY, CREDIT_LIMIT FROM CUSTOMERS

WHERE COMPANY LIKE 'Smiths_n Corp.'

NULL VALUE TEST (IS NULL) NULL values create a three-valued logic for SQL search conditions. For any given row, the result of a search condition may be TRUE or FALSE, or it may be NULL because one of the columns used in evaluating the search condition contains a NULL value. Sometimes it's useful to check explicitly for NULL values in a search condition and handle them directly. SQL provides a special NULL value test (IS NULL) Syntax: column-name IS [NOT] NULL

Example 1: Find the salesperson not yet assigned to an office. SELECT NAME FROM SALESREPS

WHERE REP_OFFICE IS NULL

Page 4: Sql ch 5

SQL Basics– Queries 2

Page 4 [email protected]

2 Explain how query results can be combined using the UNION feature.

The results of two or more queries can be combined into a single table of query results. This can be done through the UNION feature of the SELECT statement. Consider the following figure:

Query : List all the products where the price of the product exceeds $2,000 or where more than $30,000 of the product has been ordered in a single order. This query can be studied by breaking it up into two parts as follows: The first part of the request can be satisfied with the top query in the figure: List all the products whose price exceeds $2,000. SELECT MFR_ID, PRODUCT_ID

FROM PRODUCTS

WHERE PRICE > 2000.00

Similarly, the second part of the query can be satisfied with the bottom query in the figure: List all the products where more than $30,000 of the product has been ordered in a single order. SELECT DISTINCT MFR, PRODUCT

FROM ORDERS WHERE AMOUNT > 30000.00

The UNION operation produces a single table of query results that combines the rows of the top query results with the rows of the bottom query results.

Page 5: Sql ch 5

SQL Basics – Queries 2

Prof. Mukesh N. Tekwani Page 5

List all the products where the price of the product exceeds $2,000 or where more than $30,000 of the product has been ordered in a single order. SELECT MFR_ID, PRODUCT_ID FROM PRODUCTS

WHERE PRICE > 2000.00

UNION SELECT DISTINCT MFR, PRODUCT

FROM ORDERS WHERE AMOUNT > 30000.00

But before we use the UNION clause, we must be aware of the following restrictions that apply on the tables that can be combined by a UNION operation. • The two tables must contain the same number of columns. • The data type of each column in the first table must be the same as the data type of the corresponding column in the second table. • Neither of the two tables can be sorted with the ORDER BY clause. However, the combined query results can be sorted. • The ANSI/ISO SQL standard specifies one more restriction on a SELECT statement that participates in a UNION. It permits only column names or an "all columns" specification (SELECT *) in the select list and prohibits expressions in the select list. • Many SQL implementations do not allow the SELECT statements to include the GROUP BY or HAVING clauses. The column names of the two queries combined by a UNION do not have to be identical. In the preceding example, the first table of query results has columns named MFR_ID and PRODUCT_ID, while the second table of query results has columns named MFR and PRODUCT. Because the columns in the two tables can have different names, the columns of query results produced by the UNION operation are unnamed. Because the UNION operation combines the rows from two sets of query results, it would tend to produce query results containing duplicate rows. But, by default, the UNION operation eliminates duplicate rows as part of its processing. Thus, the combined set of query results contains only one row for product REI-2A44L. If we want to keep duplicate rows in a UNION operation, we must specify the ALL keyword immediately following the word "UNION." List all the products where the price of the product exceeds $2,000 or where more than $30,000 of the product has been ordered in a single order. SELECT MFR_ID, PRODUCT_ID FROM PRODUCTS WHERE PRICE > 2000.00

UNION ALL SELECT DISTINCT MFR, PRODUCT

FROM ORDERS WHERE AMOUNT > 30000.00

Page 6: Sql ch 5

SQL Basics– Queries 2

Page 6 [email protected]

3 Explain how query results combined by using the UNION feature can be sorted.

The ORDER BY clause cannot appear in either of the two SELECT statements combined by a UNION operation. We cannot sort sort the two sets of query results, because they are fed directly into the UNION operation and are never visible to the user. However, the combined set of query results produced by the UNION operation can be sorted by specifying an ORDER BY clause after the second SELECT statement. Since the columns produced by the UNION operation are not named, the ORDER BY clause must specify the columns by column number. We illustrate this by using the same products query as that shown in previous figure sorted by manufacturer and product number: List all the products where the price of the product exceeds $2,000 or where more than $30,000 of the product has been ordered in a single order, sorted by manufacturer and product number. SELECT MFR_ID, PRODUCT_ID

FROM PRODUCTS

WHERE PRICE > 2000.00 UNION

SELECT DISTINCT MFR, PRODUCT

FROM ORDERS WHERE AMOUNT > 30000.00 ORDER BY 1, 2

4 Explain the concept of multiple unions.

The UNION operation can be used repeatedly to combine three or more sets of query results. The union of Table B and Table C in the figure produces a single, combined table. This table is then combined with Table A in another operation.

The query in the figure is written this way:

Page 7: Sql ch 5

SQL Basics – Queries 2

Prof. Mukesh N. Tekwani Page 7

SELECT * FROM A UNION ( SELECT * FROM B UNION SELECT * FROM C ) The brackets in the query indicate which UNION should be performed first. If all of the UNIONs in the statement eliminate duplicate rows, or if all of them retain duplicate rows, the order in which they are performed is unimportant. These three expressions are completely equivalent: A UNION (B UNION C) or (A UNION B) UNION C or (A UNION C) UNION B

5 Explain the JOIN operation, with appropriate examples.

• The process of forming pairs of rows by matching the contents of related columns is called joining the tables.

• The resulting table (containing data from both of the original tables) is called a join between the two tables.

• A join based on an exact match between two columns is called an equi-join.

• Data is intentionally kept spread out to keep it as modular as possible. A JOIN consolidates the data in two tables into a single result set. The tables are not merged; they just appear to be merged in the results returned by the query.

• A join between two tables is established by linking a column in one table with that in another. The expression used to join the two tables is called the join condition or join criterion.

• When the join is successful, the data in the second table is combined with the first to form a composite result. This result is the set of rows containing data from both the tables.

Example 1:

List all orders showing order number, amount, customer name, and the customer's credit limit. SELECT ORDER_NUM, AMOUNT, COMPANY, CREDIT_LIMIT FROM ORDERS, CUSTOMERS

WHERE CUST = CUST_NUM

Note the following important points for this query: 1. The FROM clause lists two tables instead of just one. These two tables are ORDERS and CUSTOMERS.

2. The SELECT statement for a multi-table query must contain a search condition that

specifies the column match. In this case, the search condition is WHERE CUST =

Page 8: Sql ch 5

SQL Basics– Queries 2

Page 8 [email protected]

CUST_NUM

The SELECT statement does not say anything about how SQL should execute the query. The query may or may not start with the ORDERS table or CUSTOMERS table.

Example 2:

List each salesperson and the city and region where they work.

SELECT NAME, CITY, REGION FROM SALESREPS, OFFICES

WHERE REP_OFFICE = OFFICE

6 Explain inner join and outer join.

• There are two basic types of joins – the inner join and the outer join.

• The main difference between them is that the outer join includes rows in the result set even when the join condition is not met. But the inner join does not do that.

• What data ends up in the result set when the join condition fails? When the join criteria in an outer join are not met, columns in the first table are returned normally, but columns from the second table are returned with no value – as NULLs.

Example of Inner Join: SELECT customers.CustNumber, orders.Amount

FROM customers, orders WHERE customers.CustNumber = orders.CustNumber

If an order does not exist for a given customer, the customer is omitted completely from the list. This query can also be written as: SELECT customers.CustNumber, orders.Amount

FROM customers

JOIN orders

ON ( customers.CustNumber = orders.CustNumber)

Example of outer join: SELECT customers.CustNumber, orders.Amouont, items.Description FROM customers LEFT OUTER JOIN orders ON (customers.CustNumber = orders.CustNumber) LEFT OUTER JOIN items ON (orders.ItemNumber = items.OrderNumber)

Here the query first joins the customers and orders table. Then it joins the result with the items table.

7 Explain the process of querying three or more tables.

Consider the following query: List orders over $25,000, including the name of the salesperson who took the order and the name of the customer who placed it.” SELECT ORDER_NUM, AMOUNT, COMPANY, NAME

Page 9: Sql ch 5

SQL Basics – Queries 2

Prof. Mukesh N. Tekwani Page 9

FROM ORDERS, CUSTOMERS, SALESREPS WHERE CUST = CUST_NUM

AND REP = EMPL_NUM AND AMOUNT > 25000.00

This query uses two foreign keys in the ORDERS table. The CUST column is a foreign key for the CUSTOMERS table, linking each order to the customer who placed it. The REP column is a foreign key for the SALESREPS table, linking each order to the salesperson who took it. Informally speaking, the query links each order to its associated customer and salesperson.

Example 2:

List the orders over $25,000, showing the name of the customer who placed the order and the name of the salesperson assigned to that customer. SELECT ORDER_NUM, AMOUNT, COMPANY, NAME

FROM ORDERS, CUSTOMERS, SALESREPS WHERE CUST = CUST_NUM

AND CUST_REP = EMPL_NUM AND AMOUNT > 25000.00