SlideShare a Scribd company logo
SQL Simple Queries – Ch 5


                             SQL Queries - Basics
                                    Worksheet - 1
1     USE Statement:
      This statement is used to open an existing database.

      Syntax

      USE { database }

      Arguments

      database

      Is the name of the database to which the user context is switched. Database names must
      conform to the rules for identifiers.

2     Write SQL statement to open a database called pubs


3     Write SQL statement to open a database called Northwind


4     Write SQL statement to open an existing database called student


5     SELECT clause
      Retrieves rows from the database and allows the selection of one or many rows or columns
      from one or many tables.

      SELECT select_list
      [ INTO new_table ]
      FROM table_source
      [ WHERE search_condition ]
      [ GROUP BY group_by_expression ]
      [ HAVING search_condition ]
      [ ORDER BY order_expression [ ASC | DESC ] ]

      E.g., Consider the database called pubs.
6     To select all records from this table, we give the query:
      USE pubs
      SELECT * FROM authors




Prof. Mukesh N. Tekwani                                                            Page 1 of 9
SQL Simple Queries – Ch 5

7    Syntax Diagram of SELECT statement:




8    Write a query to select all records from a table called authors, and order the results in
     ascending order of lastname of author (au_lname), and ascending order of first name
     (au_fname).
     USE pubs
     SELECT *
     FROM authors
     ORDER BY au_lname ASC, au_fname ASC

9    Write a query to return all rows, and only a subset of the columns (au_lname,
     au_fname, phone, city, state) from the authors table in the pubs database. Sort in
     ascending order of lastname and then by ascending order of first name. Column
     heading should be added to Telephone field.
     USE pubs
     SELECT au_fname, au_lname, phone AS Telephone, city, state
     FROM authors
     ORDER BY au_lname ASC, au_fname ASC

10   Write a query to return all rows, and only a subset of the columns (au_lname,
     au_fname, phone, city, state) from the authors table in the pubs database. Sort in
     ascending order of lastname and then by ascending order of first name. Column
     headings should be added to lastname and first name fields.




Page 2 of 9                                                       mukeshtekwani@hotmail.com
SQL Simple Queries – Ch 5

11    Write a query to return all rows, and only a subset of the columns (au_lname,
      au_fname, phone, state) from the authors table in the pubs database, and only for
      authors staying in California. Phone column should have an appropriate heading.
      USE pubs
      SELECT au_fname, au_lname, phone AS Telephone, state
      FROM authors
      WHERE state = 'CA'
      ORDER BY au_lname ASC, au_fname ASC

12    Write a query to return all rows, and only a subset of the columns (au_lname,
      au_fname, phone, state) from the authors table in the pubs database, and only for
      authors not staying in California. Phone column should have an appropriate heading.




13    List the sales offices with their targets and actual sales.
      SELECT CITY, TARGET, SALES
      FROM OFFICES

14    List the Eastern region sales offices with their targets and sales.
      SELECT CITY, TARGET, SALES
      FROM OFFICES
      WHERE REGION = 'Eastern'

15    List Eastern region sales offices whose sales exceed their targets, sorted in
      alphabetical order by city.
      SELECT CITY, TARGET, SALES
      FROM OFFICES
      WHERE REGION = 'Eastern'
      AND SALES > TARGET
      ORDER BY CITY

16    What are the average target and sales for Eastern region offices?
      SELECT AVG(TARGET), AVG(SALES)
      FROM OFFICES WHERE REGION = 'Eastern'

Prof. Mukesh N. Tekwani                                                        Page 3 of 9
SQL Simple Queries – Ch 5

17   Show me a current list of our employees and their phone numbers."
     SELECT EmpLastName, EmpFirstName, EmpPhoneNumber
     FROM Employees

18   "What are the names and prices of the products we carry, and under what category is
     each item listed?"
     SELECT ProductName, RetailPrice, Category
     FROM Products

18   Show a list of subjects (SUBNAME), the category (CATID) each belongs to, and the
     code (SUBCODE) used in the catalog. Show the name first, followed by the category
     and then the code.
     SELECT SubjectName, CategoryID, SubjectCode
     FROM Subjects

19   Consider a table called BOWLERS. Give a query to list of unique cities from this
     table.
     SELECT DISTINCT City
     FROM Bowlers

20   Show a list of classes offered by the university, in alphabetical order.
     SELECT Category
     FROM Classes
     ORDER BY Category


21   Select vendor name and ZIP Code from the vendors table and order by ZIP Code
     SELECT VendName, VendZipCode
     FROM Vendors
     ORDER BY VendZipCode

22   Select vendor name and ZIP Code from the vendors table and order by ZIP Code in
     descending order.
     SELECT VendName, VendZipCode
     FROM Vendors
     ORDER BY VendZipCode DESC

23   Select last name, first name, phone number, and employee ID from the employees
     table and order by last name and first name
     Select last name, first name, phone number, and employee ID from the employees table

Page 4 of 9                                                        mukeshtekwani@hotmail.com
SQL Simple Queries – Ch 5

      and order by last name and first name.
      SELECT EmpLastName, EmpFirstName, EmpPhoneNumber, EmployeeID
      FROM Employees
      ORDER BY EmpLastName, EmpFirstName

24    Modify the above example to use the descending sort for last name and ascending sort
      for first name.
      SELECT EmpLastName, EmpFirstName, EmpPhoneNumber, EmployeeID
      FROM Employees
      ORDER BY EmpLastName DESC, EmpFirstName ASC

25    Write SQL query to find out the five most expensive products in the Sales Orders
      database.
      SELECT TOP 5 ProductName, RetailPrice
      FROM Products
      ORDER BY RetailPrice DESC

26    To find out the top 10% of products by price.
      SELECT TOP 10 PERCENT ProductName, RetailPrice
      FROM Products
      ORDER BY RetailPrice DESC

27    Write a query to answer the following : “Which states do our customers come from?"
      SELECT DISTINCT CustState
      FROM Customers

28    Give me a list of the buildings on campus and the number of floors for each building.
      Sort the list by building in ascending order."
      SELECT BuildingName, NumberOfFloors
      FROM Buildings
      ORDER BY BuildingName ASC

29    Give me a list of all tournament dates and locations. I need the dates in descending
      order and the locations in alphabetical order."
      SELECT TourneyDate, TourneyLocation
      FROM Tournaments
      ORDER BY TourneyDate DESC, TourneyLocation ASC



Prof. Mukesh N. Tekwani                                                            Page 5 of 9
SQL Simple Queries – Ch 5

30   List the names, offices, and hire dates of all salespeople.
     SELECT     NAME,       REP_OFFICE,     HIRE_DATE
     FROM     SALESREPS

31   What are the name, quota, and sales of employee number 107?
     SELECT NAME, QUOTA, SALES
     FROM SALESREPS
     WHERE EMPL_NUM = 107

32   What are the average sales of our salespeople?
     SELECT AVG(SALES)
     FROM SALESREPS

33   List the salespeople, their quotas, and their managers.
     SELECT NAME, QUOTA, MANAGER
     FROM SALESREPS

34   List the city, region, and amount over/under target for each office. This involves a
     calculated value.
     SELECT CITY, REGION, (SALES - TARGET)
     FROM OFFICES

35   Show the value of the inventory for each product. Inventory is qty * price
     SELECT MFR_ID, PRODUCT_ID, DESCRIPTION, (QTY_ON_HAND * PRICE)
     FROM PRODUCTS

36   Show me the result if I raised each salesperson's quota by 3 percent of their year-to-
     date sales.
     SELECT NAME, QUOTA, (QUOTA + (.03*SALES))
     FROM SALESREPS

37   List the name and month and year of hire for each salesperson.
     SELECT NAME, MONTH(HIRE_DATE), YEAR(HIRE_DATE)
     FROM SALESREPS

38   SQL constants can be used by themselves as items in a select list. This can be useful
     for producing query results that are easier to read and interpret.
     SELECT CITY, 'has sales of', SALES
     FROM OFFICES


Page 6 of 9                                                        mukeshtekwani@hotmail.com
SQL Simple Queries – Ch 5

39     List the offices whose sales fall below 80 percent of target.
       SELECT CITY, SALES, TARGET
       FROM OFFICES
       WHERE SALES < (.8 * TARGET)


40    Find salespeople hired before 1988.
      SELECT NAME
      FROM SALESREPS
      WHERE HIRE_DATE < '01-JAN-88'


41    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'


42    Find the orders that fall into various amount ranges.
      SELECT ORDER_NUM, AMOUNT
      FROM ORDERS
      WHERE AMOUNT BETWEEN 20000.00 AND 29999.99


43    List the salespeople who work in New York, Atlanta, or Denver.
      SELECT NAME, QUOTA, SALES
      FROM SALESREPS
      WHERE REP_OFFICE IN (11, 13, 22)


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


      Note : The search condition
      X IN (A, B, C)
      is completely equivalent to:
Prof. Mukesh N. Tekwani                                                Page 7 of 9
SQL Simple Queries – Ch 5

      (X = A) OR (X = B) OR (X = C)


45   Wildcard Characters
      The percent sign (%) wildcard character matches any sequence of zero or more characters.
     This query uses the percent sign for pattern matching:
     SELECT COMPANY, CREDIT_LIMIT
     FROM CUSTOMERS
     WHERE COMPANY LIKE 'Smith% Corp.'




46   The underscore (_) wildcard character matches any single character. 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.'
     In this case, any of these names will match the pattern:
     Smithson Corp. Smithsen Corp. Smithsun Corp.


47   Wildcard characters can appear anywhere in the pattern string, and several wildcard
     characters can be within a single string. This query allows either the "Smithson" or
     "Smithsen" spelling and will also accept "Corp.," "Inc.," or any other ending on the
     company name:
     SELECT COMPANY, CREDIT_LIMIT

Page 8 of 9                                                       mukeshtekwani@hotmail.com
SQL Simple Queries – Ch 5

      FROM CUSTOMERS
      WHERE COMPANY LIKE 'Smiths_n %'


48    Find products whose product IDs start with the four letters "A%BC".
      SELECT ORDER_NUM, PRODUCT
      FROM ORDERS
      WHERE PRODUCT LIKE 'A$%BC%' ESCAPE '$'


      Here we are using the $ character as the “Escape” character. The escape character is
      specified as a one-character constant string in the ESCAPE clause of the search condition.
      The first percent sign in the pattern, which follows an escape character, is treated as a
      literal percent sign; the second functions as a wildcard.




Prof. Mukesh N. Tekwani                                                               Page 9 of 9

More Related Content

PDF
Sql ch 5
PDF
Sql wksht-6
PDF
Sql wksht-3
PPTX
PDF
Sql Basics | Edureka
PPTX
SQL - DML and DDL Commands
PPT
SQL subquery
PDF
DBMS 5 | MySQL Practice List - HR Schema
Sql ch 5
Sql wksht-6
Sql wksht-3
Sql Basics | Edureka
SQL - DML and DDL Commands
SQL subquery
DBMS 5 | MySQL Practice List - HR Schema

What's hot (20)

PPT
Retrieving data using the sql select statement
PPTX
Aggregate function
DOCX
Top 40 sql queries for testers
PDF
PL/SQL TRIGGERS
PPT
Introduction to structured query language (sql)
PPTX
Structured query language(sql)ppt
DOCX
SQL-RDBMS Queries and Question Bank
PPTX
Sql fundamentals
PPTX
Sql subquery
PPT
Sql basics and DDL statements
PPTX
sql function(ppt)
ODP
PPT
Sql select
ODP
Introduction to triggers
PDF
SQL Overview
DOCX
Index in sql server
PPTX
Basic sql Commands
PPTX
SQL for interview
PDF
Integrity constraints in dbms
Retrieving data using the sql select statement
Aggregate function
Top 40 sql queries for testers
PL/SQL TRIGGERS
Introduction to structured query language (sql)
Structured query language(sql)ppt
SQL-RDBMS Queries and Question Bank
Sql fundamentals
Sql subquery
Sql basics and DDL statements
sql function(ppt)
Sql select
Introduction to triggers
SQL Overview
Index in sql server
Basic sql Commands
SQL for interview
Integrity constraints in dbms
Ad

Viewers also liked (16)

PDF
Sql wksht-9
PDF
Sql wksht-7
PDF
Sql ch 4
PDF
Sql wksht-5
PDF
Sql wksht-2
PDF
23246406 dbms-unit-1
PDF
Analytical Queries with Hive: SQL Windowing and Table Functions
DOCX
DBMS lab manual
DOC
Sql queries
PDF
Python reading and writing files
PDF
Dbms viva questions
DOC
DBMS Practical File
DOC
Dbms lab questions
ODT
Sql queries interview questions
DOC
Sql queries with answers
PDF
Top 100 SQL Interview Questions and Answers
Sql wksht-9
Sql wksht-7
Sql ch 4
Sql wksht-5
Sql wksht-2
23246406 dbms-unit-1
Analytical Queries with Hive: SQL Windowing and Table Functions
DBMS lab manual
Sql queries
Python reading and writing files
Dbms viva questions
DBMS Practical File
Dbms lab questions
Sql queries interview questions
Sql queries with answers
Top 100 SQL Interview Questions and Answers
Ad

Similar to Sql wksht-1 (20)

PPTX
Module 3.1.pptx
PPTX
PDF
SQL sheet
PPTX
Adv Topic -------Basic SQL_DML Session 2
PPTX
DOC
SQL practice questions set - 2
PPTX
Data Manipulation Language.pptx
PPTX
Introduction to SQL
PDF
Dynamic websites lec2
PPT
Sql server lab_3
PDF
Database Systems - SQL - DDL Statements (Chapter 3/3)
PPTX
Beginers guide for oracle sql
PDF
WORKSHEET SQL SOLVED FOR CLASS XII FINAL
PPTX
PDF
Structured query language(sql)
PDF
PDF
SQL Practice Question set
DOCX
PPTX
ADV Powepoint 2 Lec.pptx
PPTX
12. Basic SQL Queries (2).pptx
Module 3.1.pptx
SQL sheet
Adv Topic -------Basic SQL_DML Session 2
SQL practice questions set - 2
Data Manipulation Language.pptx
Introduction to SQL
Dynamic websites lec2
Sql server lab_3
Database Systems - SQL - DDL Statements (Chapter 3/3)
Beginers guide for oracle sql
WORKSHEET SQL SOLVED FOR CLASS XII FINAL
Structured query language(sql)
SQL Practice Question set
ADV Powepoint 2 Lec.pptx
12. Basic SQL Queries (2).pptx

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
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Institutional Correction lecture only . . .
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
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
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
RMMM.pdf make it easy to upload and study
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
master seminar digital applications in india
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Institutional Correction lecture only . . .
human mycosis Human fungal infections are called human mycosis..pptx
VCE English Exam - Section C Student Revision Booklet
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
RMMM.pdf make it easy to upload and study
O7-L3 Supply Chain Operations - ICLT Program
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Week 4 Term 3 Study Techniques revisited.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
master seminar digital applications in india
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Anesthesia in Laparoscopic Surgery in India
TR - Agricultural Crops Production NC III.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf

Sql wksht-1

  • 1. SQL Simple Queries – Ch 5 SQL Queries - Basics Worksheet - 1 1 USE Statement: This statement is used to open an existing database. Syntax USE { database } Arguments database Is the name of the database to which the user context is switched. Database names must conform to the rules for identifiers. 2 Write SQL statement to open a database called pubs 3 Write SQL statement to open a database called Northwind 4 Write SQL statement to open an existing database called student 5 SELECT clause Retrieves rows from the database and allows the selection of one or many rows or columns from one or many tables. SELECT select_list [ INTO new_table ] FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ] E.g., Consider the database called pubs. 6 To select all records from this table, we give the query: USE pubs SELECT * FROM authors Prof. Mukesh N. Tekwani Page 1 of 9
  • 2. SQL Simple Queries – Ch 5 7 Syntax Diagram of SELECT statement: 8 Write a query to select all records from a table called authors, and order the results in ascending order of lastname of author (au_lname), and ascending order of first name (au_fname). USE pubs SELECT * FROM authors ORDER BY au_lname ASC, au_fname ASC 9 Write a query to return all rows, and only a subset of the columns (au_lname, au_fname, phone, city, state) from the authors table in the pubs database. Sort in ascending order of lastname and then by ascending order of first name. Column heading should be added to Telephone field. USE pubs SELECT au_fname, au_lname, phone AS Telephone, city, state FROM authors ORDER BY au_lname ASC, au_fname ASC 10 Write a query to return all rows, and only a subset of the columns (au_lname, au_fname, phone, city, state) from the authors table in the pubs database. Sort in ascending order of lastname and then by ascending order of first name. Column headings should be added to lastname and first name fields. Page 2 of 9 mukeshtekwani@hotmail.com
  • 3. SQL Simple Queries – Ch 5 11 Write a query to return all rows, and only a subset of the columns (au_lname, au_fname, phone, state) from the authors table in the pubs database, and only for authors staying in California. Phone column should have an appropriate heading. USE pubs SELECT au_fname, au_lname, phone AS Telephone, state FROM authors WHERE state = 'CA' ORDER BY au_lname ASC, au_fname ASC 12 Write a query to return all rows, and only a subset of the columns (au_lname, au_fname, phone, state) from the authors table in the pubs database, and only for authors not staying in California. Phone column should have an appropriate heading. 13 List the sales offices with their targets and actual sales. SELECT CITY, TARGET, SALES FROM OFFICES 14 List the Eastern region sales offices with their targets and sales. SELECT CITY, TARGET, SALES FROM OFFICES WHERE REGION = 'Eastern' 15 List Eastern region sales offices whose sales exceed their targets, sorted in alphabetical order by city. SELECT CITY, TARGET, SALES FROM OFFICES WHERE REGION = 'Eastern' AND SALES > TARGET ORDER BY CITY 16 What are the average target and sales for Eastern region offices? SELECT AVG(TARGET), AVG(SALES) FROM OFFICES WHERE REGION = 'Eastern' Prof. Mukesh N. Tekwani Page 3 of 9
  • 4. SQL Simple Queries – Ch 5 17 Show me a current list of our employees and their phone numbers." SELECT EmpLastName, EmpFirstName, EmpPhoneNumber FROM Employees 18 "What are the names and prices of the products we carry, and under what category is each item listed?" SELECT ProductName, RetailPrice, Category FROM Products 18 Show a list of subjects (SUBNAME), the category (CATID) each belongs to, and the code (SUBCODE) used in the catalog. Show the name first, followed by the category and then the code. SELECT SubjectName, CategoryID, SubjectCode FROM Subjects 19 Consider a table called BOWLERS. Give a query to list of unique cities from this table. SELECT DISTINCT City FROM Bowlers 20 Show a list of classes offered by the university, in alphabetical order. SELECT Category FROM Classes ORDER BY Category 21 Select vendor name and ZIP Code from the vendors table and order by ZIP Code SELECT VendName, VendZipCode FROM Vendors ORDER BY VendZipCode 22 Select vendor name and ZIP Code from the vendors table and order by ZIP Code in descending order. SELECT VendName, VendZipCode FROM Vendors ORDER BY VendZipCode DESC 23 Select last name, first name, phone number, and employee ID from the employees table and order by last name and first name Select last name, first name, phone number, and employee ID from the employees table Page 4 of 9 mukeshtekwani@hotmail.com
  • 5. SQL Simple Queries – Ch 5 and order by last name and first name. SELECT EmpLastName, EmpFirstName, EmpPhoneNumber, EmployeeID FROM Employees ORDER BY EmpLastName, EmpFirstName 24 Modify the above example to use the descending sort for last name and ascending sort for first name. SELECT EmpLastName, EmpFirstName, EmpPhoneNumber, EmployeeID FROM Employees ORDER BY EmpLastName DESC, EmpFirstName ASC 25 Write SQL query to find out the five most expensive products in the Sales Orders database. SELECT TOP 5 ProductName, RetailPrice FROM Products ORDER BY RetailPrice DESC 26 To find out the top 10% of products by price. SELECT TOP 10 PERCENT ProductName, RetailPrice FROM Products ORDER BY RetailPrice DESC 27 Write a query to answer the following : “Which states do our customers come from?" SELECT DISTINCT CustState FROM Customers 28 Give me a list of the buildings on campus and the number of floors for each building. Sort the list by building in ascending order." SELECT BuildingName, NumberOfFloors FROM Buildings ORDER BY BuildingName ASC 29 Give me a list of all tournament dates and locations. I need the dates in descending order and the locations in alphabetical order." SELECT TourneyDate, TourneyLocation FROM Tournaments ORDER BY TourneyDate DESC, TourneyLocation ASC Prof. Mukesh N. Tekwani Page 5 of 9
  • 6. SQL Simple Queries – Ch 5 30 List the names, offices, and hire dates of all salespeople. SELECT NAME, REP_OFFICE, HIRE_DATE FROM SALESREPS 31 What are the name, quota, and sales of employee number 107? SELECT NAME, QUOTA, SALES FROM SALESREPS WHERE EMPL_NUM = 107 32 What are the average sales of our salespeople? SELECT AVG(SALES) FROM SALESREPS 33 List the salespeople, their quotas, and their managers. SELECT NAME, QUOTA, MANAGER FROM SALESREPS 34 List the city, region, and amount over/under target for each office. This involves a calculated value. SELECT CITY, REGION, (SALES - TARGET) FROM OFFICES 35 Show the value of the inventory for each product. Inventory is qty * price SELECT MFR_ID, PRODUCT_ID, DESCRIPTION, (QTY_ON_HAND * PRICE) FROM PRODUCTS 36 Show me the result if I raised each salesperson's quota by 3 percent of their year-to- date sales. SELECT NAME, QUOTA, (QUOTA + (.03*SALES)) FROM SALESREPS 37 List the name and month and year of hire for each salesperson. SELECT NAME, MONTH(HIRE_DATE), YEAR(HIRE_DATE) FROM SALESREPS 38 SQL constants can be used by themselves as items in a select list. This can be useful for producing query results that are easier to read and interpret. SELECT CITY, 'has sales of', SALES FROM OFFICES Page 6 of 9 mukeshtekwani@hotmail.com
  • 7. SQL Simple Queries – Ch 5 39 List the offices whose sales fall below 80 percent of target. SELECT CITY, SALES, TARGET FROM OFFICES WHERE SALES < (.8 * TARGET) 40 Find salespeople hired before 1988. SELECT NAME FROM SALESREPS WHERE HIRE_DATE < '01-JAN-88' 41 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' 42 Find the orders that fall into various amount ranges. SELECT ORDER_NUM, AMOUNT FROM ORDERS WHERE AMOUNT BETWEEN 20000.00 AND 29999.99 43 List the salespeople who work in New York, Atlanta, or Denver. SELECT NAME, QUOTA, SALES FROM SALESREPS WHERE REP_OFFICE IN (11, 13, 22) 44 Find all orders placed with four specific salespeople. SELECT ORDER_NUM, REP, AMOUNT FROM ORDERS WHERE REP IN (107, 109, 101, 103) Note : The search condition X IN (A, B, C) is completely equivalent to: Prof. Mukesh N. Tekwani Page 7 of 9
  • 8. SQL Simple Queries – Ch 5 (X = A) OR (X = B) OR (X = C) 45 Wildcard Characters The percent sign (%) wildcard character matches any sequence of zero or more characters. This query uses the percent sign for pattern matching: SELECT COMPANY, CREDIT_LIMIT FROM CUSTOMERS WHERE COMPANY LIKE 'Smith% Corp.' 46 The underscore (_) wildcard character matches any single character. 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.' In this case, any of these names will match the pattern: Smithson Corp. Smithsen Corp. Smithsun Corp. 47 Wildcard characters can appear anywhere in the pattern string, and several wildcard characters can be within a single string. This query allows either the "Smithson" or "Smithsen" spelling and will also accept "Corp.," "Inc.," or any other ending on the company name: SELECT COMPANY, CREDIT_LIMIT Page 8 of 9 mukeshtekwani@hotmail.com
  • 9. SQL Simple Queries – Ch 5 FROM CUSTOMERS WHERE COMPANY LIKE 'Smiths_n %' 48 Find products whose product IDs start with the four letters "A%BC". SELECT ORDER_NUM, PRODUCT FROM ORDERS WHERE PRODUCT LIKE 'A$%BC%' ESCAPE '$' Here we are using the $ character as the “Escape” character. The escape character is specified as a one-character constant string in the ESCAPE clause of the search condition. The first percent sign in the pattern, which follows an escape character, is treated as a literal percent sign; the second functions as a wildcard. Prof. Mukesh N. Tekwani Page 9 of 9