SlideShare a Scribd company logo
SQL Basics – Queries 2

                                   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
Prof. Mukesh N. Tekwani                                                                       Page 1
SQL Basics– Queries 2

             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 2                                                               mukeshtekwani@hotmail.com
SQL Basics – Queries 2

      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




Prof. Mukesh N. Tekwani                                                                  Page 3
SQL Basics– Queries 2

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 4                                                                  mukeshtekwani@hotmail.com
SQL Basics – Queries 2

      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


Prof. Mukesh N. Tekwani                                                                     Page 5
SQL Basics– Queries 2

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 6                                                               mukeshtekwani@hotmail.com
SQL Basics – Queries 2

      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 =
Prof. Mukesh N. Tekwani                                                               Page 7
SQL Basics– Queries 2

         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 8                                                                 mukeshtekwani@hotmail.com
SQL Basics – Queries 2

      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




Prof. Mukesh N. Tekwani                                                                  Page 9

More Related Content

PDF
Sql wksht-1
PDF
Sql wksht-3
PDF
Sql wksht-6
PPTX
SQL - DML and DDL Commands
PPT
Sql basics and DDL statements
PPTX
PPT
SQL subquery
PPTX
Structured query language(sql)ppt
Sql wksht-1
Sql wksht-3
Sql wksht-6
SQL - DML and DDL Commands
Sql basics and DDL statements
SQL subquery
Structured query language(sql)ppt

What's hot (20)

PPTX
Presentation slides of Sequence Query Language (SQL)
PPTX
Sql subquery
DOCX
SQL-RDBMS Queries and Question Bank
PPTX
Group By, Order By, and Aliases in SQL
PPT
Joins in SQL
DOCX
Top 40 sql queries for testers
PPT
Introduction to structured query language (sql)
PPTX
Sql Constraints
PPTX
SQL for interview
PPTX
Aggregate function
PDF
İleri Seviye T-SQL Programlama - Chapter 05
PPTX
Aggregate functions in SQL.pptx
PPSX
Join query
DOCX
Index in sql server
PPTX
Proc SQL in SAS Enterprise Guide 4.3
PPT
Creating and Managing Tables -Oracle Data base
PPT
Introduction to sql
DOC
A must Sql notes for beginners
PPTX
Sql commands
Presentation slides of Sequence Query Language (SQL)
Sql subquery
SQL-RDBMS Queries and Question Bank
Group By, Order By, and Aliases in SQL
Joins in SQL
Top 40 sql queries for testers
Introduction to structured query language (sql)
Sql Constraints
SQL for interview
Aggregate function
İleri Seviye T-SQL Programlama - Chapter 05
Aggregate functions in SQL.pptx
Join query
Index in sql server
Proc SQL in SAS Enterprise Guide 4.3
Creating and Managing Tables -Oracle Data base
Introduction to sql
A must Sql notes for beginners
Sql commands
Ad

Similar to Sql ch 5 (20)

PDF
SQL Overview
PDF
Dynamic websites lec2
DOC
Sql functions
PDF
SQL Queries related to DDL and DML and DCL
PPT
Chinabankppt
PPT
Advanced Sql Training
PPT
PPT
PDF
PDF
PPTX
Introduction to SQL
PDF
Tech Jam 01 - Database Querying
PPTX
Server Query Language – Getting Started.pptx
PDF
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
PPT
Review of SQL
PPTX
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
PPTX
Sql slid
PPTX
Database Overview
PPT
Database Management systems lecture notes
PPTX
Subqueries, Backups, Users and Privileges
SQL Overview
Dynamic websites lec2
Sql functions
SQL Queries related to DDL and DML and DCL
Chinabankppt
Advanced Sql Training
Introduction to SQL
Tech Jam 01 - Database Querying
Server Query Language – Getting Started.pptx
FOUNDATION OF DATA SCIENCE SQL QUESTIONS
Review of SQL
vnd.openxmlformats-officedocument.presentationml.presentation&rendition=1.pptx
Sql slid
Database Overview
Database Management systems lecture notes
Subqueries, Backups, Users and Privileges
Ad

More from Mukesh Tekwani (20)

PDF
The Elphinstonian 1988-College Building Centenary Number (2).pdf
PPSX
Circular motion
PPSX
Gravitation
PDF
ISCE-Class 12-Question Bank - Electrostatics - Physics
PPTX
Hexadecimal to binary conversion
PPTX
Hexadecimal to decimal conversion
PPTX
Hexadecimal to octal conversion
PPTX
Gray code to binary conversion
PPTX
What is Gray Code?
PPSX
Decimal to Binary conversion
PDF
Video Lectures for IGCSE Physics 2020-21
PDF
Refraction and dispersion of light through a prism
PDF
Refraction of light at a plane surface
PDF
Spherical mirrors
PDF
Atom, origin of spectra Bohr's theory of hydrogen atom
PDF
Refraction of light at spherical surfaces of lenses
PDF
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
PPSX
Cyber Laws
PPSX
Social media
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Circular motion
Gravitation
ISCE-Class 12-Question Bank - Electrostatics - Physics
Hexadecimal to binary conversion
Hexadecimal to decimal conversion
Hexadecimal to octal conversion
Gray code to binary conversion
What is Gray Code?
Decimal to Binary conversion
Video Lectures for IGCSE Physics 2020-21
Refraction and dispersion of light through a prism
Refraction of light at a plane surface
Spherical mirrors
Atom, origin of spectra Bohr's theory of hydrogen atom
Refraction of light at spherical surfaces of lenses
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Cyber Laws
Social media

Recently uploaded (20)

PPTX
Pharma ospi slides which help in ospi learning
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Institutional Correction lecture only . . .
PDF
Classroom Observation Tools for Teachers
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Cell Structure & Organelles in detailed.
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
Pharma ospi slides which help in ospi learning
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
O5-L3 Freight Transport Ops (International) V1.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Institutional Correction lecture only . . .
Classroom Observation Tools for Teachers
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
VCE English Exam - Section C Student Revision Booklet
human mycosis Human fungal infections are called human mycosis..pptx
PPH.pptx obstetrics and gynecology in nursing
Cell Structure & Organelles in detailed.
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Supply Chain Operations Speaking Notes -ICLT Program

Sql ch 5

  • 1. SQL Basics – Queries 2 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 Prof. Mukesh N. Tekwani Page 1
  • 2. SQL Basics– Queries 2 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 2 mukeshtekwani@hotmail.com
  • 3. SQL Basics – Queries 2 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 Prof. Mukesh N. Tekwani Page 3
  • 4. SQL Basics– Queries 2 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 4 mukeshtekwani@hotmail.com
  • 5. SQL Basics – Queries 2 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 Prof. Mukesh N. Tekwani Page 5
  • 6. SQL Basics– Queries 2 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 6 mukeshtekwani@hotmail.com
  • 7. SQL Basics – Queries 2 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 = Prof. Mukesh N. Tekwani Page 7
  • 8. SQL Basics– Queries 2 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 8 mukeshtekwani@hotmail.com
  • 9. SQL Basics – Queries 2 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 Prof. Mukesh N. Tekwani Page 9