SlideShare une entreprise Scribd logo
1  sur  9
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questionsPyadav010186
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Punjab University
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for BeginnersProduct School
 
80 different SQL Queries with output
80 different SQL Queries with output80 different SQL Queries with output
80 different SQL Queries with outputNexus
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan PasrichaMananPasricha
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankMd Mudassir
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testerstlvd
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sqlCharan Reddy
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functionsfarwa waqar
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answersMichael Belete
 

Tendances (20)

Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questions
 
SQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftjSQL BASIC QUERIES SOLUTION ~hmftj
SQL BASIC QUERIES SOLUTION ~hmftj
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
Intro to SQL for Beginners
Intro to SQL for BeginnersIntro to SQL for Beginners
Intro to SQL for Beginners
 
SQL UNION
SQL UNIONSQL UNION
SQL UNION
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
80 different SQL Queries with output
80 different SQL Queries with output80 different SQL Queries with output
80 different SQL Queries with output
 
Sql clauses by Manan Pasricha
Sql clauses by Manan PasrichaSql clauses by Manan Pasricha
Sql clauses by Manan Pasricha
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question Bank
 
Top 40 sql queries for testers
Top 40 sql queries for testersTop 40 sql queries for testers
Top 40 sql queries for testers
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
All questions
All questionsAll questions
All questions
 
SQL
SQLSQL
SQL
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
Sql queries questions and answers
Sql queries questions and answersSql queries questions and answers
Sql queries questions and answers
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Sql Queries
Sql QueriesSql Queries
Sql Queries
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 

Similaire à Sql ch 5

Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfhowto4ucontact
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptxEllenGracePorras
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic ConceptsTony Wong
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDev Chauhan
 
Server Query Language – Getting Started.pptx
Server Query Language – Getting Started.pptxServer Query Language – Getting Started.pptx
Server Query Language – Getting Started.pptxauzee32
 
The Ultimate Guide to Oracle solaris 11 advanced system administration 1 z0 822
The Ultimate Guide to Oracle solaris 11 advanced system administration  1 z0 822The Ultimate Guide to Oracle solaris 11 advanced system administration  1 z0 822
The Ultimate Guide to Oracle solaris 11 advanced system administration 1 z0 822SoniaSrivastva
 
ADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxArjayBalberan1
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
ADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptxADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptxArjayBalberan1
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSaiMiryala1
 
SQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfSQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfMadhusha15
 
Module 3.1.pptx
Module 3.1.pptxModule 3.1.pptx
Module 3.1.pptxANSHVAJPAI
 

Similaire à Sql ch 5 (20)

SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Data Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdfData Base Management System Lecture 10.pdf
Data Base Management System Lecture 10.pdf
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Sql
SqlSql
Sql
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Chapter9 more on database and sql
Chapter9 more on database and sqlChapter9 more on database and sql
Chapter9 more on database and sql
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
Sql joins
Sql joinsSql joins
Sql joins
 
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQLDATABASE MANAGMENT SYSTEM (DBMS) AND SQL
DATABASE MANAGMENT SYSTEM (DBMS) AND SQL
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
Server Query Language – Getting Started.pptx
Server Query Language – Getting Started.pptxServer Query Language – Getting Started.pptx
Server Query Language – Getting Started.pptx
 
Query
QueryQuery
Query
 
The Ultimate Guide to Oracle solaris 11 advanced system administration 1 z0 822
The Ultimate Guide to Oracle solaris 11 advanced system administration  1 z0 822The Ultimate Guide to Oracle solaris 11 advanced system administration  1 z0 822
The Ultimate Guide to Oracle solaris 11 advanced system administration 1 z0 822
 
ADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptxADV Powepoint 2 Lec.pptx
ADV Powepoint 2 Lec.pptx
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
ADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptxADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdfSQL Lesson 6 - Select.pdf
SQL Lesson 6 - Select.pdf
 
Module 3.1.pptx
Module 3.1.pptxModule 3.1.pptx
Module 3.1.pptx
 

Plus de Mukesh Tekwani

ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference ModelMukesh Tekwani
 

Plus de Mukesh Tekwani (20)

Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 
Social media
Social mediaSocial media
Social media
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference Model
 

Dernier

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 

Dernier (20)

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

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