SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
SQL Simple Queries – WK5

                            SQL Queries - Basics
                                   Worksheet - 5
1   Get the last name and first name of all authors whose lastname has 5 or more
    characters.
    SELECT LNAme, FName
    FROM Authors
    WHERE LEN(Lname) >= 5

2   Find the Employee number, Sales, and DeptID of each employee. If the employee has
    no sales, then four dashes should be printed
    SELECT EmpID,
              IFNULL(Sales, ‘----‘), DeptID
    FROM Employee

3   Find the cities that repeat in the Authors table.
    SELECT CITY
    FROM AUTHORS
    GROUP BY CITY
    HAVING COUNT(*) > 1
    ORDER BY CITY

4   Find all the cities where the company has customers.
    SELECT CITY
    FROM AUTHORS
    GROUP BY CITY
    ORDER BY CITY

5   Find the names of employees who joined the company 22 years or later after they were
    born.
    SELECT EMPID, LNAME
    FROM EMPLOYEE
    WHERE YEAR(DOB) + 22 >= YEAR(DOJ)

6   Find the EmpID of all male workers born before Jan 1, 1990.
    SLEECT EmpID
    FROM Employee
    WHERE Gender = ‘M’ AND YEAR(DOB) < 1990

7   Find the names of all employees who do not live in ‘Mumbai’.
    SELECT LName
    FROM Employee
    WHERE City <> ‘Mumbai’

8   Find the employee number of all employees born between 1-1-1980 and 1-1-1990
    SELECT EmpID
    FROM Employee
    WHERE DOB >= ’01-01-1980’ AND DOB <= ’01-01-1990’
Prof. Mukesh N. Tekwani                                                     Page 1 of 14
SQL Simple Queries – WK 5

    This can also be written as :

    SELECT EmpID
    FROM Employee
    WHERE DOB BETWEEN ’01-01-1980’ AND ’01-01-1990’

9   Find the names of employees who have worked in one of the following depts.: Sales,
    Mktg, Accounts, PR.
    SELECT LNAme
    FROM Employee
    WHERE Dept IN (‘Sales’, ‘Mktg’, ‘Accounts’, ‘PR’)

10 Find the names of all employees whose lastname starts with C.
   SELECT LName
   FROM Employee
   WHERE LNAME LIKE ‘C%’

11 Find the names of all employees whose lastname ends with C.
   SELECT LName
   FROM Employee
   WHERE LNAME LIKE ‘%C’

12 Find the names of all employees whose lastname has the penultimate letter ‘e’.
   SELECT LName
   FROM Employee
   WHERE LNAME LIKE ‘%e_’

13 Find the names of all employees whose lastname has the letter ‘e’.
   SELECT LName
   FROM Employee
   WHERE LNAME LIKE ‘%#e%’ ESCAPE #

14 Wildcard explained
   The LIKE operator allows us to perform basic pattern-matching using wildcard characters.

          Wildcard                                  Description
        _ (underscore) matches any single character
              %        matches a string of one or more characters
                       matches any single character within the specified range (e.g. [a-f]) or
              []
                       set (e.g. [abcdef]).
                       matches any single character not within the specified range (e.g. [^a-
             [^]
                       f]) or set (e.g. [^abcdef]).

    Examples:

    •   WHERE FirstName LIKE '_im' finds all three-letter first names that end with 'im' (e.g.
        Jim, Tim).
    •   WHERE LastName LIKE '%stein' finds all employees whose last name ends with 'stein'
Page 2 of 14                                                         mukeshtekwani@hotmail.com
SQL Simple Queries – WK5

    •   WHERE LastName LIKE '%stein%' finds all employees whose last name includes
        'stein' anywhere in the name.
    •   WHERE FirstName LIKE '[JT]im' finds three-letter first names that end with 'im' and
        begin with either 'J' or 'T' (that is, only Jim and Tim)
    •   WHERE LastName LIKE 'm[^c]%' finds all last names beginning with 'm' where the
        following (second) letter is not 'c'.

    For Q 15 to Q 27, the table structure is :

    Sales_Header          (OrderNo , OrderDate , CustomerID ,
    Salesmanid ,          PaymentStatus , TransactionType)

    Sales_Detail(OrderNo , ProductID , Qty , Rate, Amt)

15 Display the orders that were issued in the first quarter of the current year.    (Nov 04)
   SELECT       Orderno
   FROM Orders
   WHERE MONTH(Orderdate) < 4
          AND YEAR(Orderdate) = YEAR(GETDATE())

16 Display the order number, order date , customer name and order amount for
   orders having value of Rs 500 and above.                           (Nov 04)
   SELECT Orderno, Orderdate, Customer_Name, Amt
   FROM Sales_Header H, Sales_Detail D
   WHERE H.Orderno = D.Orderno AND Amt >= 500

17 Display the order detail where RIN001 soap is sold for minimum of Rs 50 (Nov 04)
   SELECT Sales_Header.*
   FROM Sales_Header H, Sales_Detail D
   WHERE H.Orderno = D.Orderno AND Productid = ’RIN001’                         AND
   Rate >= 50

18 Display the order collected by Executive no. ‘S120’                              Nov 04
   SELECT O.Orderid , D.Productid, D.Quantity
   FROM Orders O, [Order Details] D
   WHERE O.Orderid = D.Orderid AND O.Employeeid = ‘S120’

19 Assign the privileges to see the data from both tables to ‘Raj’.                 Nov 04
   GRANT SELECT
   ON SALES_HEADER, SALES_DETAILS
   TO RAJ

20 Grant the INSERT and UPDATE privileges to Raj, for all columns in the
   SALES_DETAILS table.
   GRANT INSERT, UPDATE
   ON SALES_DETAILS
   TO RAJ

21 Display the various types of product sold to Customers.                          Nov 04

Prof. Mukesh N. Tekwani                                                            Page 3 of 14
SQL Simple Queries – WK 5

    SELECT DISTINCT Productid
    FROM SalesDetails

22 Display all Credit transactions , with their payment status done in Dec 2003.
   SELECT *
   FROM SALES_HEADER
   WHERE TRANSACTIONTYPE = ‘CREDIT’
         AND PAYMENTSTATUS = ’PAID’
         AND MONTH(ORDERDATE) = 12
         AND YEAR(ORDERDATE) = 2003

23 Display the details of total cash transactions done by each sales executive.
   SELECT *
   FROM Sales_Header
   GROUP BY Salesmanid
   HAVING TransactionType = ’Cash’

24 Update salary of employee ‘Raj’ by giving him the salary of ‘Radha’ working in
   same company.                                                          Nov 04
   UPDATE Emp
   SET salary =
   (SELECT salary FROM Emp WHERE Ename = ’Radha’)
   WHERE Ename = ’Raj’ AND
   Compid = (SELECT compid FROM emp WHERE ename=’Radha’)

25 Display how many male and female members have joined in January 2004. Nov 04
   SELECT COUNT (ename)
   FROM emp
   GROUP BY gender
   HAVING TO_CHAR(joindate,’mon-yyyy’) = ’JAN-2004’

26 Display the total number of customers.
   SELECT COUNT(customerId)
   FROM customers

27 Display the total number of customers located in each city.          Nov 04
   The city with maximum number of customers should be at the top of the list.
   SELECT count(customerid) , city
   FROM customers
   GROUP BY city
   ORDER BY 1 DESC

    Assume the following table structure:
    Emp (Empid , ename, city, CompID , salary , Joindate )
    Company (CompID , CompName , City)

28 Give name of companies located in those cities where ‘TATA’ is located. Nov 04
   SELECT Companyname
   FROM company
Page 4 of 14                                                  mukeshtekwani@hotmail.com
SQL Simple Queries – WK5

     WHERE city IN
          (SELECT city
          FROM company
          WHERE companyName = ’TATA’)

29 Give the names of the employees living in the same city where their company is
   located.                                                              Nov 04
   SELECT ename
   FROM Emp e, company c
   WHERE e.city = c.city

30 Display all customers who stay in the same city as the employees.
   SELECT c.customerid, e.employeeid
   FROM customers c, employees e
   WHERE c.city = e.city

     Consider the following table structure for questions below:
     Book (BookID , Title , Author , Publisher , Year , Price , DistID)
     Distributors (DistID , Name , City)                                                    Nov 04

31 Find the title and price of the most expensive book(s).
   SELECT Title, Price
   FROM Book
   WHERE price = (SELECT MAX(Price) FROM Titles)

32 Display the details of books whose price is more than the average price of all
   books.                                                                  Nov 04
   SELECT *
   FROM book
   WHERE Price > (SELECT AVG (Price) FROM book )

33 Display the details of books written by ‘Groff’ and supplied by ‘TMH’                    Nov 04
   SELECT *
   FROM book
   WHERE Author = ’Groff’ AND Publisher = ’TMGH’

34 Create a view to show the Title, Author, Publisher and Distributer’s Name &
   name this view as ShowDetails. Display the records held in this view. Nov 04
   CREATE VIEW ShowDetails
   AS
   SELECT title, author, publisher, distributor
   FROM book
35 Create the table RIVERS according to the description shown below.
      Attribute          Data type                           Constraint
      Name               Upto 20 characters long             Unique and not null
      Length             Upto 4 digits                       Values between 100 and 4160
      Outflow            Upto 20 characters long             Required

     CREATE TABLE river
Prof. Mukesh N. Tekwani                                                                    Page 5 of 14
SQL Simple Queries – WK 5

    (Name VARCHAR(20) UNIQUE NOT NULL,
    Length NUMERIC CHECK (LENGTH BETWEEN 101 AND 4160),
    Outflow VARCHAR(20) NOT NULL)

36 Add a new column called Maxdepth to the rivers table. Make sure that the values
   of this column range from 100 to 250 feet.
   ALTER TABLE river
   ADD maxdepth NUMERIC
   CHECK (maxdepth BETWEEN 100 AND 250)

37 Create table ‘CITY’ With the following fields:
      Field                           Data type      Constraint
      CID                             INTEGER        PRIMARY KEY
      CNAME                           Upto 20 char
      State                           2 char
      Latitude                        Number
      Longitude                       Number
    CREATE TABLE city
    (
         CId INTEGER PRIMARY KEY,
         CName VARCHAR(20),
         State CHAR(2),
         Latitude NUMERIC(5),
         Longitude NUMERIC(5)
    )

38 Create table DATA with following fields:

     Field          Data type  Constraint
     CID            Integer    Foreign Key Matching City Id
     MONTH          Integer    Must Be Between 1 And 12
     TEMP_F         Number     Must Be Between -80 And 150
     Rain_I         Number     Must be between 0 and 100
     (ID+MONTH)                Primary key
    CREATE TABLE data
    (
           CID INTEGER,
           Month INTEGER CHECK(month BETWEEN 1 AND 12),
           Temp_f NUMERIC(3) CHECK(temp_f BETWEEN -80 AND 150),
           Rain_i NUMERIC(3) CHECK(rain_i BETWEEN 0 AND 100),
           PRIMARY KEY (CID, MONTH),
           CONSTRAINT fkey FOREIGN KEY(CID) REFERENCES city
    )

39 List the temperatures for July from table Data, Lowest temperatures first, picking
   up city name and latitude by joining with the table city.
   SELECT Temp_f, cname, Latitude
   FROM Data d, City c
   WHERE d.cId = c.cId AND month = 7
   ORDER BY Temp_f ASC
Page 6 of 14                                                   mukeshtekwani@hotmail.com
SQL Simple Queries – WK5


40 List (using Subquery) the cities with year round average temperature above 50
   degrees.
   SELECT name
   FROM City
   WHERE Id IN
   (
          SELECT cid FROM Data WHERE 50 < All
          (SELECT avg(temp_f) FROM data GROUP BY CID)
   )

    Note:
    When the ANY clause is used, a value from the current row is compared to each result
    set of the subquery using the comparison operator. If any of the comparisons are true,
    the entire comparison is considered to be true.

    The ALL clause is similar to the ANY clause except that after the value is compared to
    all the items returned by the subquery, if any of the comparisons is false, the entire
    clause is false. That is, if there is a comparison based on equality, the value on the left
    of the comparison must be equal to every item in the result set for the ALL clause to
    evaluate to true.

    Consider the following tables and answer the queries that follow:

                                             CUSTOMER
     Attribute                     Data Type          Constraints
     Custid                        Varchar(2)         Primary key
     Lname                         Varchar(15)
     Fname                         Varchar(15)
     Area                          Varchar(2)
     Phone                         Number(8)

                                                 MOVIE
     Attribute                     Datatype               Constraints
     Mvno                          Number(2)              Primary key
     Title                         Varchar(25)
     Type                          Varchar(10)
     Star                          Varchar(25)
     Price                         Number(8,2)

                                                INVOICE
     Attribute                     Datatype               Constraints
     Invno                         Varchar(3)             Primary key
     Mvno                          Number(2)              Foreign key movie(mvno)
     Custid                        Varchar(3)             Foreign Key customer(custid)
     Issue date                    Date
     Return date                   Date

41 Find out the movies that cost more than 159 and also find the new cost as original
    cost*15
    SELECT mvno, price*15 “NEW COST”
    FROM movie
Prof. Mukesh N. Tekwani                                                  Page 7 of 14
SQL Simple Queries – WK 5

    WHERE price > 159

42 Print the names and types of all the movies except horror movies.
   SELECT title, type
   FROM movie
   WHERE type NOT IN(‘horror’)

43 List the various movie types available
   SELECT DISTINCT type
   FROM movie

44 List the mvno, title of movies whose stars begin with the letter ’m’
   SELECT mvno, title, type
   FROM movie
   WHERE star LIKE ‘m%’

45 Determine the maximum and minimum of price. Rename the columns as max-
   price and min_price respectively.
   SELECT MAX(price) “max_price”, MIN(price) “min_price”
   FROM movie

46 Find out number of movies in each type,
   SELECT COUNT (type)
   FROM movie
   GROUP BY type

47 Print the information of invoice table in the following format for all records.
   The invoice no of customer id.{ custid} is { invno} and movie no is { movno}
   SELECT ‘The invoice no of customer id : ’, custid, ’is ‘,
   invno, ‘ and movie No. is ‘, movno
   FROM invoice

48 Display the month(in alphabets) in which customers are supposed to return the
   movies
   SELECT MONTH(returnDate)
   FROM Invoice

49 Delete all records having return date before 10th July ‘05
   DELETE FROM invoice
   WHERE returndate < ’10-JUL-05’

50 Find out if the movie starring ‘Tom Cruise’ is issued to any customer and list the
   custid to whom it is issued
   SELECT custid
   FROM invoice, movie
   WHERE invoice.mvno = movie.mvno AND
   movie.star LIKE ‘Tom Cruise’

51 Find the names of customers who have been issued movie of type ’drama’.
Page 8 of 14                                                    mukeshtekwani@hotmail.com
SQL Simple Queries – WK5

    SELECT Fname, ’ ‘, lname, “Name”
    FROM customer c, movie M, invoice i
    WHERE c.custid = i.custid AND m.mvno = i.mvno
    AND m.type LIKE ‘drama’

52 Find out the title of the movies that have been issued to the customer whose
   Fname is’ Mary’
   SELECT title
   FROM customer, movie, invoice
   WHERE customer.custid = invoice.custid AND
   Movie.mvno = invoice.mvno AND Customer.Fname LIKE ‘Mary’

53 Add a column Remark of type varchar and size 25 to the invoice table
   ALTER TABLE invoice
   ADD (Remark VARCHAR(25))

54 Find the names of all customers having ‘a’ in the second letter in their fname.
   SELECT Fname, lname
   FROM customer
   WHERE fname LIKE ’_a%’

55 Find out the movie number which has been issued to customer whose first name
   is ‘IVAN’
   SELECT i.mvno
   FROM customer c, invoice I
   WHERE c.custid = i.custid AND fname LIKE ‘IVAN’

56 Display the title, Lname, Fname for customers having movie number greater than
   or equal to three in the following format.
   The movie taken by { Fname} { Lname} is { Title}
   SELECT ‘The movie taken by’, Fname, ‘ ‘, Lname, ’ is ‘, Title
   FROM customer c, movie m, invoice i
   WHERE c.custid = i.custid AND m.mvno = i.mvno AND m.mvno >= 3

57 Find the second highest sales.
   SELECT MAX(sales)
   WHERE sales NOT IN
   (SELECT MAX(sales) FROM sales)

   Answer the following questions based on the following tables:
   Student ( sid number, sname varchar, previous_percentage number,
   aptitude_test_status number, grade char)
58 Write an ALTER TABLE statement that defines a single CHECK constraints for the
   following: Column previous_percentage must be a value between 40 to 100.
   ALTER TABLE Student
   MODIFY Previous_percentage NUMERIC(5)
   CHECK (Previous_percentage between 40 and 100)

59 Make the sid column unique.
Prof. Mukesh N. Tekwani                                                    Page 9 of 14
SQL Simple Queries – WK 5

    ALTER TABLE Student
    ADD CONSTRAINT ID_UNIQ UNIQUE (sid)

60 Add a column called TestDate with default value as today’s
   date.
   ALTER TABLE Student
   ADD TestDate datetime DEFAULT (GETDATE())

61 Aptitude_test_status must be a value in between 60 to 100.
   ALTER Table Student
   ADD Check (Aptitude_test_status BETWEEN 60 AND 100)

62 The grade column should allow values ‘a’, ’b’ and ‘c’ only.
   ALTER TABLE Student
   ADD CHECK (grade IN ('a', 'b', 'c'))

   Following queries are based on these tables:
   Supplier (sno, sname, status, city)
   Parts (pno, pname, color, weight, city)
   Shipment (sno, pno, quantity, sdate)
63 Change the status of each supplier to its double for suppliers in ‘Mumbai’.
   UPDATE supplier
   SET status = status * 2
   WHERE city = 'Mumbai'

64 Get the sno for suppliers with status less than current maximum status in the
   supplier table.
   First we form the subquery to find the maximum status, as follows:
   SELECT MAX(status)
   FROM supplier

    Now, the complete query is :
    SELECT sno
    FROM supplier
    WHERE status < (SELECT MAX(status)FROM supplier)

65 Create a view of Suppliers whose status is above 2.
   CREATE VIEW suppliers_view (sno,sname,status,city)
   AS
   SELECT * FROM supplier WHERE status > 2

66 Get all parts whose weight is 10, 20 or 30.
   SELECT pno, pname
   FROM parts
   WHERE weight IN (10,20,30)

67 Get sname for suppliers who do not supply at least one part.
   SELECT sname
   FROM supplier s, shipment sh
   WHERE s.sno = sh.sno AND s.sno NOT IN
   (SELECT DISTINCT sno FROM shipment)
Page 10 of 14                                                    mukeshtekwani@hotmail.com
SQL Simple Queries – WK5


   The following queries are based on the following tables:
   Employee (ecode, ename, salary, status, deptno, city)
   Dept(deptno, dname, city)
   Product (pno, sno, pname, unitsinstock, unitprice)
   Order(ono, pno, quantity, odate)
68 Create the Employee table
   CREATE TABLE employee
   (
         ecode INTEGER,
         ename VARCHAR(50),
         salary MONEY,
         status CHAR,
         deptno INTEGER,
         city VARCHAR(20)
   )

69 Alter the table to add a column for qualifications.
   ALTER TABLE Employee
   ADD qual VARCHAR(20)

70 Alter the table to drop the qual column.
   ALTER TABLE Employee
   DROP COLUMN qual

71 Alter the table to add a column pfnum which is unique (add a column with a
   constraint)
   ALTER TABLE Employee
   ADD pfnum INTEGER
   CONSTRAINT ct_pfnum UNIQUE

72 Alter the table to add a column totalsalary with the constraint that this cannot be
   greater than 10000.
   ALTER TABLE employee
   ADD totalsalary MONEY
   CONSTRAINT maxsal CHECK (totalsalary <= 10000)

73 Alter the employee table so that the ecode is less than 100
   ALTER TABLE employee
   ADD CONSTRAINT validecode CHECK (ecode <= 100)

74 Remove the constraint on ecode.
   ALTER TABLE employee
   DROP CONSTRAINT validecode

75 Add a constraint that the dept code can be one of 11, 22, 33, 44 or 55.
   ALTER TABLE employee
   ADD CONSTRAINT validdept CHECK
   (deptno in(11, 22, 33, 44, 55))
Prof. Mukesh N. Tekwani                                                      Page 11 of 14
SQL Simple Queries – WK 5


76 Multiple check constraints:
   Assume there is a column called ‘SalaryType’ (Hourly, Monthly, Annual). Create a
   single constraint that checks both the salary and the salary type
   ALTER TABLE Payroll
   ADD CONSTRAINT CK_Payroll
   CHECK
   (SalaryType in ('Hourly','Monthly','Annual')
   AND
   (Salary > 100 AND Salary < 150000)

77 Add the following constraint in a single ALTER statement:
   If SalaryType is Hourly, salary must be less than 100.
   If SalaryType is Monthly, salary must not be more than 10000
   If SalaryType is Annual, any salary amount is valid.
   ALTER TABLE Payroll
   ADD CONSTRAINT CK_Payroll
   CHECK
   (
          (SalaryType = 'Hourly' AND Salary < 100.00)
          OR
          (SalaryType = 'Monthly' AND Salary < 10000.00)
          OR
          (SalaryType = 'Annual')
   )

78 Alter the table so that the SalaryType is not null and SalaryType is one of these:
   Hourly, Monthly, Annual.
   ALTER TABLE Payroll
   ADD CONSTRAINT CK_Payroll
   CHECK
   (
          (SalaryType IN ('Hourly','Monthly','Annual'))
          AND
          SalaryType IS NOT NULL
   )

79 Write an ALTER table statement that allows only the following cities: ‘BOSTON’,
   ‘DALLAS’, and ‘AUSTIN’
   ALTER TABLE employee
   ADD CONSTRAINT validcity
   CHECK (CITY IN ('BOSTON', 'DALLAS', 'AUSTIN'))

80 Define a view for Sue (employee number 102) containing only orders placed by customers
    assigned to her. (horizontal view)
    CREATE VIEW SUEORDERS AS
    SELECT *
    FROM ORDERS
    WHERE CUST IN
    (SELECT CUST_NUM FROM CUSTOMERS WHERE CUST_REP = 102)

Page 12 of 14                                                  mukeshtekwani@hotmail.com
SQL Simple Queries – WK5


82 A vertical view restricts a user’s access to only certain columns of a table.
     CREATE VIEW STUD_ADDRESS AS
     SELECT ROLLNO, NAME, ADD1, ADD2, CITY
     FROM STUDENTS

83 Define a view that contains summary order data for each salesperson. (grouped view)
     CREATE VIEW ORD_BY_REP (WHO, HOW_MANY, TOTAL, LOW, HIGH, AVERAGE)
     AS
     SELECT REP, COUNT(*), SUM(AMOUNT), MIN(AMOUNT), MAX(AMOUNT), AVG(AMOUNT)
     FROM ORDERS
     GROUP BY REP

84 Create a view to print names of all movies in capital letters.
     CREATE VIEW Movies_upper(title)
     AS
     SELECT UPPER(movie_title)
     FROM Movies

85 Create a view to find the total revenue from all movies.
     CREATE VIEW TRev (total_revenue)
     AS
     SELECT SUM(gross)
     FROM Movies

86 Create a view to find all people who live in a state where a movie studio is located.
     CREATE VIEW PS
     AS
     SELECT FName, LName, StudioName, Person_State
     FROM People, Studio
     WHERE Person_State = Studio_State

87 Create a view that returns the list of all the studios with an average budget of over $50 million.
     (view with a sub-query)
     CREATE VIEW Big_Movies
     AS
     SELECT movie_title, budget, gross
     FROM Movies
     WHERE studio_id IN
     (SELECT studio_id
     FROM Movies
     GROUP BY studio_id
     HAVING AVG(budget) > 50)

88 Add a single field to the 'Sales' table by specifying the new field name and data
   type.
   ALTER TABLE Sales
   ADD UnitPrice MONEY

89 The following example adds the reserved words NOT NULL to require valid data
   to be added to that field. However, you must also specify a default value for any
   data already inserted in the table.
   ALTER TABLE Sales
   ADD UnitPrice MONEY
Prof. Mukesh N. Tekwani                                                                  Page 13 of 14
SQL Simple Queries – WK 5

    DEFAULT 3.00 NOT NULL

90 This example changes the data type of the column 'ItemCount' to an integer (INT)
   ALTER TABLE Sales
   ALTER COLUMN ItemCount INT

91 This example demonstrates how to use DROP COLUMN to delete a single field.
   ALTER TABLE Sales
   DROP COLUMN UnitPrice

92 Display all students whose surname is between ‘N’ and ‘R’
   SELECT *
   FROM STUDENTS
   WHERE SURNAME BETWEEN ‘N’ and ‘R’

93 Display the highest salary paid in each department.
   SELECT max(salary), dept
   FROM employee
   GROUP BY dept


    Tables:
    items_ordered
    customerid order_date item quantity        price

    Cutsomer


    customerid firstname lastname city state

94 How many people are in each unique state in the customers table? Select the
    state and display the number of people in each. Hint: count is used to count
    rows in a column, sum works on numeric data only.
    SELECT state, COUNT(state)
    FROM customers
    GROUP BY state

95 Write a query using a join to determine which items were ordered by each of
    the customers in the customers table. Select the customerid, firstname,
    lastname, order_date, item, and price for everything each customer purchased
    in the items_ordered table.
    SELECT c.customerid, c.firstname, c.lastname,
           i.order_date, i.item, i.price
    FROM customers c, items_ordered i
    WHERE c.customerid = i.customerid




Page 14 of 14                                              mukeshtekwani@hotmail.com

Mais conteúdo relacionado

Mais procurados

Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
jhe04
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
vijaybusu
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
Nawaz Sk
 

Mais procurados (20)

My Sql
My Sql My Sql
My Sql
 
Sql Queries
Sql QueriesSql Queries
Sql Queries
 
Sql queires
Sql queiresSql queires
Sql queires
 
Complex queries in sql
Complex queries in sqlComplex queries in sql
Complex queries in sql
 
Sql task
Sql taskSql task
Sql task
 
Q on subquery
Q on subqueryQ on subquery
Q on subquery
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
Plsql task
Plsql taskPlsql task
Plsql task
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
Sql task answers
Sql task answersSql task answers
Sql task answers
 
Plsql task answers
Plsql task answersPlsql task answers
Plsql task answers
 
SQL practice questions set
SQL practice questions setSQL practice questions set
SQL practice questions set
 
Sql query [select, sub] 4
Sql query [select, sub] 4Sql query [select, sub] 4
Sql query [select, sub] 4
 
Sql queries
Sql queriesSql queries
Sql queries
 
DBMS 6 | MySQL Practice List - Rank Related Queries
DBMS 6 | MySQL Practice List - Rank Related QueriesDBMS 6 | MySQL Practice List - Rank Related Queries
DBMS 6 | MySQL Practice List - Rank Related Queries
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
Dump Answers
Dump AnswersDump Answers
Dump Answers
 
Sql operators & functions 3
Sql operators & functions 3Sql operators & functions 3
Sql operators & functions 3
 

Semelhante a Sql wksht-5

Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
Belal Arfa
 
CIS276DB Module 6 Assignment 1. Write a select sta.docx
CIS276DB Module 6 Assignment   1. Write a select sta.docxCIS276DB Module 6 Assignment   1. Write a select sta.docx
CIS276DB Module 6 Assignment 1. Write a select sta.docx
clarebernice
 
Below is my code- I have an error that I still have difficulty figurin.pdf
Below is my code- I have an error that I still have difficulty figurin.pdfBelow is my code- I have an error that I still have difficulty figurin.pdf
Below is my code- I have an error that I still have difficulty figurin.pdf
armanuelraj
 

Semelhante a Sql wksht-5 (20)

Sql wksht-1
Sql wksht-1Sql wksht-1
Sql wksht-1
 
SQL
SQLSQL
SQL
 
SQL Practice Question set
SQL Practice Question set SQL Practice Question set
SQL Practice Question set
 
Introduction to Databases - Assignment_1
Introduction to Databases - Assignment_1Introduction to Databases - Assignment_1
Introduction to Databases - Assignment_1
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfolio
 
Data Manipulation
Data ManipulationData Manipulation
Data Manipulation
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
 
Sql functions
Sql functionsSql functions
Sql functions
 
CIS276DB Module 6 Assignment 1. Write a select sta.docx
CIS276DB Module 6 Assignment   1. Write a select sta.docxCIS276DB Module 6 Assignment   1. Write a select sta.docx
CIS276DB Module 6 Assignment 1. Write a select sta.docx
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 
21390228-SQL-Queries.doc
21390228-SQL-Queries.doc21390228-SQL-Queries.doc
21390228-SQL-Queries.doc
 
Les03
Les03Les03
Les03
 
sql ppt for students who preparing for sql
sql ppt for students who preparing for sqlsql ppt for students who preparing for sql
sql ppt for students who preparing for sql
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
 
Below is my code- I have an error that I still have difficulty figurin.pdf
Below is my code- I have an error that I still have difficulty figurin.pdfBelow is my code- I have an error that I still have difficulty figurin.pdf
Below is my code- I have an error that I still have difficulty figurin.pdf
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptx
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 

Mais de Mukesh Tekwani

Mais de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
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
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Último (20)

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 

Sql wksht-5

  • 1. SQL Simple Queries – WK5 SQL Queries - Basics Worksheet - 5 1 Get the last name and first name of all authors whose lastname has 5 or more characters. SELECT LNAme, FName FROM Authors WHERE LEN(Lname) >= 5 2 Find the Employee number, Sales, and DeptID of each employee. If the employee has no sales, then four dashes should be printed SELECT EmpID, IFNULL(Sales, ‘----‘), DeptID FROM Employee 3 Find the cities that repeat in the Authors table. SELECT CITY FROM AUTHORS GROUP BY CITY HAVING COUNT(*) > 1 ORDER BY CITY 4 Find all the cities where the company has customers. SELECT CITY FROM AUTHORS GROUP BY CITY ORDER BY CITY 5 Find the names of employees who joined the company 22 years or later after they were born. SELECT EMPID, LNAME FROM EMPLOYEE WHERE YEAR(DOB) + 22 >= YEAR(DOJ) 6 Find the EmpID of all male workers born before Jan 1, 1990. SLEECT EmpID FROM Employee WHERE Gender = ‘M’ AND YEAR(DOB) < 1990 7 Find the names of all employees who do not live in ‘Mumbai’. SELECT LName FROM Employee WHERE City <> ‘Mumbai’ 8 Find the employee number of all employees born between 1-1-1980 and 1-1-1990 SELECT EmpID FROM Employee WHERE DOB >= ’01-01-1980’ AND DOB <= ’01-01-1990’ Prof. Mukesh N. Tekwani Page 1 of 14
  • 2. SQL Simple Queries – WK 5 This can also be written as : SELECT EmpID FROM Employee WHERE DOB BETWEEN ’01-01-1980’ AND ’01-01-1990’ 9 Find the names of employees who have worked in one of the following depts.: Sales, Mktg, Accounts, PR. SELECT LNAme FROM Employee WHERE Dept IN (‘Sales’, ‘Mktg’, ‘Accounts’, ‘PR’) 10 Find the names of all employees whose lastname starts with C. SELECT LName FROM Employee WHERE LNAME LIKE ‘C%’ 11 Find the names of all employees whose lastname ends with C. SELECT LName FROM Employee WHERE LNAME LIKE ‘%C’ 12 Find the names of all employees whose lastname has the penultimate letter ‘e’. SELECT LName FROM Employee WHERE LNAME LIKE ‘%e_’ 13 Find the names of all employees whose lastname has the letter ‘e’. SELECT LName FROM Employee WHERE LNAME LIKE ‘%#e%’ ESCAPE # 14 Wildcard explained The LIKE operator allows us to perform basic pattern-matching using wildcard characters. Wildcard Description _ (underscore) matches any single character % matches a string of one or more characters matches any single character within the specified range (e.g. [a-f]) or [] set (e.g. [abcdef]). matches any single character not within the specified range (e.g. [^a- [^] f]) or set (e.g. [^abcdef]). Examples: • WHERE FirstName LIKE '_im' finds all three-letter first names that end with 'im' (e.g. Jim, Tim). • WHERE LastName LIKE '%stein' finds all employees whose last name ends with 'stein' Page 2 of 14 mukeshtekwani@hotmail.com
  • 3. SQL Simple Queries – WK5 • WHERE LastName LIKE '%stein%' finds all employees whose last name includes 'stein' anywhere in the name. • WHERE FirstName LIKE '[JT]im' finds three-letter first names that end with 'im' and begin with either 'J' or 'T' (that is, only Jim and Tim) • WHERE LastName LIKE 'm[^c]%' finds all last names beginning with 'm' where the following (second) letter is not 'c'. For Q 15 to Q 27, the table structure is : Sales_Header (OrderNo , OrderDate , CustomerID , Salesmanid , PaymentStatus , TransactionType) Sales_Detail(OrderNo , ProductID , Qty , Rate, Amt) 15 Display the orders that were issued in the first quarter of the current year. (Nov 04) SELECT Orderno FROM Orders WHERE MONTH(Orderdate) < 4 AND YEAR(Orderdate) = YEAR(GETDATE()) 16 Display the order number, order date , customer name and order amount for orders having value of Rs 500 and above. (Nov 04) SELECT Orderno, Orderdate, Customer_Name, Amt FROM Sales_Header H, Sales_Detail D WHERE H.Orderno = D.Orderno AND Amt >= 500 17 Display the order detail where RIN001 soap is sold for minimum of Rs 50 (Nov 04) SELECT Sales_Header.* FROM Sales_Header H, Sales_Detail D WHERE H.Orderno = D.Orderno AND Productid = ’RIN001’ AND Rate >= 50 18 Display the order collected by Executive no. ‘S120’ Nov 04 SELECT O.Orderid , D.Productid, D.Quantity FROM Orders O, [Order Details] D WHERE O.Orderid = D.Orderid AND O.Employeeid = ‘S120’ 19 Assign the privileges to see the data from both tables to ‘Raj’. Nov 04 GRANT SELECT ON SALES_HEADER, SALES_DETAILS TO RAJ 20 Grant the INSERT and UPDATE privileges to Raj, for all columns in the SALES_DETAILS table. GRANT INSERT, UPDATE ON SALES_DETAILS TO RAJ 21 Display the various types of product sold to Customers. Nov 04 Prof. Mukesh N. Tekwani Page 3 of 14
  • 4. SQL Simple Queries – WK 5 SELECT DISTINCT Productid FROM SalesDetails 22 Display all Credit transactions , with their payment status done in Dec 2003. SELECT * FROM SALES_HEADER WHERE TRANSACTIONTYPE = ‘CREDIT’ AND PAYMENTSTATUS = ’PAID’ AND MONTH(ORDERDATE) = 12 AND YEAR(ORDERDATE) = 2003 23 Display the details of total cash transactions done by each sales executive. SELECT * FROM Sales_Header GROUP BY Salesmanid HAVING TransactionType = ’Cash’ 24 Update salary of employee ‘Raj’ by giving him the salary of ‘Radha’ working in same company. Nov 04 UPDATE Emp SET salary = (SELECT salary FROM Emp WHERE Ename = ’Radha’) WHERE Ename = ’Raj’ AND Compid = (SELECT compid FROM emp WHERE ename=’Radha’) 25 Display how many male and female members have joined in January 2004. Nov 04 SELECT COUNT (ename) FROM emp GROUP BY gender HAVING TO_CHAR(joindate,’mon-yyyy’) = ’JAN-2004’ 26 Display the total number of customers. SELECT COUNT(customerId) FROM customers 27 Display the total number of customers located in each city. Nov 04 The city with maximum number of customers should be at the top of the list. SELECT count(customerid) , city FROM customers GROUP BY city ORDER BY 1 DESC Assume the following table structure: Emp (Empid , ename, city, CompID , salary , Joindate ) Company (CompID , CompName , City) 28 Give name of companies located in those cities where ‘TATA’ is located. Nov 04 SELECT Companyname FROM company Page 4 of 14 mukeshtekwani@hotmail.com
  • 5. SQL Simple Queries – WK5 WHERE city IN (SELECT city FROM company WHERE companyName = ’TATA’) 29 Give the names of the employees living in the same city where their company is located. Nov 04 SELECT ename FROM Emp e, company c WHERE e.city = c.city 30 Display all customers who stay in the same city as the employees. SELECT c.customerid, e.employeeid FROM customers c, employees e WHERE c.city = e.city Consider the following table structure for questions below: Book (BookID , Title , Author , Publisher , Year , Price , DistID) Distributors (DistID , Name , City) Nov 04 31 Find the title and price of the most expensive book(s). SELECT Title, Price FROM Book WHERE price = (SELECT MAX(Price) FROM Titles) 32 Display the details of books whose price is more than the average price of all books. Nov 04 SELECT * FROM book WHERE Price > (SELECT AVG (Price) FROM book ) 33 Display the details of books written by ‘Groff’ and supplied by ‘TMH’ Nov 04 SELECT * FROM book WHERE Author = ’Groff’ AND Publisher = ’TMGH’ 34 Create a view to show the Title, Author, Publisher and Distributer’s Name & name this view as ShowDetails. Display the records held in this view. Nov 04 CREATE VIEW ShowDetails AS SELECT title, author, publisher, distributor FROM book 35 Create the table RIVERS according to the description shown below. Attribute Data type Constraint Name Upto 20 characters long Unique and not null Length Upto 4 digits Values between 100 and 4160 Outflow Upto 20 characters long Required CREATE TABLE river Prof. Mukesh N. Tekwani Page 5 of 14
  • 6. SQL Simple Queries – WK 5 (Name VARCHAR(20) UNIQUE NOT NULL, Length NUMERIC CHECK (LENGTH BETWEEN 101 AND 4160), Outflow VARCHAR(20) NOT NULL) 36 Add a new column called Maxdepth to the rivers table. Make sure that the values of this column range from 100 to 250 feet. ALTER TABLE river ADD maxdepth NUMERIC CHECK (maxdepth BETWEEN 100 AND 250) 37 Create table ‘CITY’ With the following fields: Field Data type Constraint CID INTEGER PRIMARY KEY CNAME Upto 20 char State 2 char Latitude Number Longitude Number CREATE TABLE city ( CId INTEGER PRIMARY KEY, CName VARCHAR(20), State CHAR(2), Latitude NUMERIC(5), Longitude NUMERIC(5) ) 38 Create table DATA with following fields: Field Data type Constraint CID Integer Foreign Key Matching City Id MONTH Integer Must Be Between 1 And 12 TEMP_F Number Must Be Between -80 And 150 Rain_I Number Must be between 0 and 100 (ID+MONTH) Primary key CREATE TABLE data ( CID INTEGER, Month INTEGER CHECK(month BETWEEN 1 AND 12), Temp_f NUMERIC(3) CHECK(temp_f BETWEEN -80 AND 150), Rain_i NUMERIC(3) CHECK(rain_i BETWEEN 0 AND 100), PRIMARY KEY (CID, MONTH), CONSTRAINT fkey FOREIGN KEY(CID) REFERENCES city ) 39 List the temperatures for July from table Data, Lowest temperatures first, picking up city name and latitude by joining with the table city. SELECT Temp_f, cname, Latitude FROM Data d, City c WHERE d.cId = c.cId AND month = 7 ORDER BY Temp_f ASC Page 6 of 14 mukeshtekwani@hotmail.com
  • 7. SQL Simple Queries – WK5 40 List (using Subquery) the cities with year round average temperature above 50 degrees. SELECT name FROM City WHERE Id IN ( SELECT cid FROM Data WHERE 50 < All (SELECT avg(temp_f) FROM data GROUP BY CID) ) Note: When the ANY clause is used, a value from the current row is compared to each result set of the subquery using the comparison operator. If any of the comparisons are true, the entire comparison is considered to be true. The ALL clause is similar to the ANY clause except that after the value is compared to all the items returned by the subquery, if any of the comparisons is false, the entire clause is false. That is, if there is a comparison based on equality, the value on the left of the comparison must be equal to every item in the result set for the ALL clause to evaluate to true. Consider the following tables and answer the queries that follow: CUSTOMER Attribute Data Type Constraints Custid Varchar(2) Primary key Lname Varchar(15) Fname Varchar(15) Area Varchar(2) Phone Number(8) MOVIE Attribute Datatype Constraints Mvno Number(2) Primary key Title Varchar(25) Type Varchar(10) Star Varchar(25) Price Number(8,2) INVOICE Attribute Datatype Constraints Invno Varchar(3) Primary key Mvno Number(2) Foreign key movie(mvno) Custid Varchar(3) Foreign Key customer(custid) Issue date Date Return date Date 41 Find out the movies that cost more than 159 and also find the new cost as original cost*15 SELECT mvno, price*15 “NEW COST” FROM movie Prof. Mukesh N. Tekwani Page 7 of 14
  • 8. SQL Simple Queries – WK 5 WHERE price > 159 42 Print the names and types of all the movies except horror movies. SELECT title, type FROM movie WHERE type NOT IN(‘horror’) 43 List the various movie types available SELECT DISTINCT type FROM movie 44 List the mvno, title of movies whose stars begin with the letter ’m’ SELECT mvno, title, type FROM movie WHERE star LIKE ‘m%’ 45 Determine the maximum and minimum of price. Rename the columns as max- price and min_price respectively. SELECT MAX(price) “max_price”, MIN(price) “min_price” FROM movie 46 Find out number of movies in each type, SELECT COUNT (type) FROM movie GROUP BY type 47 Print the information of invoice table in the following format for all records. The invoice no of customer id.{ custid} is { invno} and movie no is { movno} SELECT ‘The invoice no of customer id : ’, custid, ’is ‘, invno, ‘ and movie No. is ‘, movno FROM invoice 48 Display the month(in alphabets) in which customers are supposed to return the movies SELECT MONTH(returnDate) FROM Invoice 49 Delete all records having return date before 10th July ‘05 DELETE FROM invoice WHERE returndate < ’10-JUL-05’ 50 Find out if the movie starring ‘Tom Cruise’ is issued to any customer and list the custid to whom it is issued SELECT custid FROM invoice, movie WHERE invoice.mvno = movie.mvno AND movie.star LIKE ‘Tom Cruise’ 51 Find the names of customers who have been issued movie of type ’drama’. Page 8 of 14 mukeshtekwani@hotmail.com
  • 9. SQL Simple Queries – WK5 SELECT Fname, ’ ‘, lname, “Name” FROM customer c, movie M, invoice i WHERE c.custid = i.custid AND m.mvno = i.mvno AND m.type LIKE ‘drama’ 52 Find out the title of the movies that have been issued to the customer whose Fname is’ Mary’ SELECT title FROM customer, movie, invoice WHERE customer.custid = invoice.custid AND Movie.mvno = invoice.mvno AND Customer.Fname LIKE ‘Mary’ 53 Add a column Remark of type varchar and size 25 to the invoice table ALTER TABLE invoice ADD (Remark VARCHAR(25)) 54 Find the names of all customers having ‘a’ in the second letter in their fname. SELECT Fname, lname FROM customer WHERE fname LIKE ’_a%’ 55 Find out the movie number which has been issued to customer whose first name is ‘IVAN’ SELECT i.mvno FROM customer c, invoice I WHERE c.custid = i.custid AND fname LIKE ‘IVAN’ 56 Display the title, Lname, Fname for customers having movie number greater than or equal to three in the following format. The movie taken by { Fname} { Lname} is { Title} SELECT ‘The movie taken by’, Fname, ‘ ‘, Lname, ’ is ‘, Title FROM customer c, movie m, invoice i WHERE c.custid = i.custid AND m.mvno = i.mvno AND m.mvno >= 3 57 Find the second highest sales. SELECT MAX(sales) WHERE sales NOT IN (SELECT MAX(sales) FROM sales) Answer the following questions based on the following tables: Student ( sid number, sname varchar, previous_percentage number, aptitude_test_status number, grade char) 58 Write an ALTER TABLE statement that defines a single CHECK constraints for the following: Column previous_percentage must be a value between 40 to 100. ALTER TABLE Student MODIFY Previous_percentage NUMERIC(5) CHECK (Previous_percentage between 40 and 100) 59 Make the sid column unique. Prof. Mukesh N. Tekwani Page 9 of 14
  • 10. SQL Simple Queries – WK 5 ALTER TABLE Student ADD CONSTRAINT ID_UNIQ UNIQUE (sid) 60 Add a column called TestDate with default value as today’s date. ALTER TABLE Student ADD TestDate datetime DEFAULT (GETDATE()) 61 Aptitude_test_status must be a value in between 60 to 100. ALTER Table Student ADD Check (Aptitude_test_status BETWEEN 60 AND 100) 62 The grade column should allow values ‘a’, ’b’ and ‘c’ only. ALTER TABLE Student ADD CHECK (grade IN ('a', 'b', 'c')) Following queries are based on these tables: Supplier (sno, sname, status, city) Parts (pno, pname, color, weight, city) Shipment (sno, pno, quantity, sdate) 63 Change the status of each supplier to its double for suppliers in ‘Mumbai’. UPDATE supplier SET status = status * 2 WHERE city = 'Mumbai' 64 Get the sno for suppliers with status less than current maximum status in the supplier table. First we form the subquery to find the maximum status, as follows: SELECT MAX(status) FROM supplier Now, the complete query is : SELECT sno FROM supplier WHERE status < (SELECT MAX(status)FROM supplier) 65 Create a view of Suppliers whose status is above 2. CREATE VIEW suppliers_view (sno,sname,status,city) AS SELECT * FROM supplier WHERE status > 2 66 Get all parts whose weight is 10, 20 or 30. SELECT pno, pname FROM parts WHERE weight IN (10,20,30) 67 Get sname for suppliers who do not supply at least one part. SELECT sname FROM supplier s, shipment sh WHERE s.sno = sh.sno AND s.sno NOT IN (SELECT DISTINCT sno FROM shipment) Page 10 of 14 mukeshtekwani@hotmail.com
  • 11. SQL Simple Queries – WK5 The following queries are based on the following tables: Employee (ecode, ename, salary, status, deptno, city) Dept(deptno, dname, city) Product (pno, sno, pname, unitsinstock, unitprice) Order(ono, pno, quantity, odate) 68 Create the Employee table CREATE TABLE employee ( ecode INTEGER, ename VARCHAR(50), salary MONEY, status CHAR, deptno INTEGER, city VARCHAR(20) ) 69 Alter the table to add a column for qualifications. ALTER TABLE Employee ADD qual VARCHAR(20) 70 Alter the table to drop the qual column. ALTER TABLE Employee DROP COLUMN qual 71 Alter the table to add a column pfnum which is unique (add a column with a constraint) ALTER TABLE Employee ADD pfnum INTEGER CONSTRAINT ct_pfnum UNIQUE 72 Alter the table to add a column totalsalary with the constraint that this cannot be greater than 10000. ALTER TABLE employee ADD totalsalary MONEY CONSTRAINT maxsal CHECK (totalsalary <= 10000) 73 Alter the employee table so that the ecode is less than 100 ALTER TABLE employee ADD CONSTRAINT validecode CHECK (ecode <= 100) 74 Remove the constraint on ecode. ALTER TABLE employee DROP CONSTRAINT validecode 75 Add a constraint that the dept code can be one of 11, 22, 33, 44 or 55. ALTER TABLE employee ADD CONSTRAINT validdept CHECK (deptno in(11, 22, 33, 44, 55)) Prof. Mukesh N. Tekwani Page 11 of 14
  • 12. SQL Simple Queries – WK 5 76 Multiple check constraints: Assume there is a column called ‘SalaryType’ (Hourly, Monthly, Annual). Create a single constraint that checks both the salary and the salary type ALTER TABLE Payroll ADD CONSTRAINT CK_Payroll CHECK (SalaryType in ('Hourly','Monthly','Annual') AND (Salary > 100 AND Salary < 150000) 77 Add the following constraint in a single ALTER statement: If SalaryType is Hourly, salary must be less than 100. If SalaryType is Monthly, salary must not be more than 10000 If SalaryType is Annual, any salary amount is valid. ALTER TABLE Payroll ADD CONSTRAINT CK_Payroll CHECK ( (SalaryType = 'Hourly' AND Salary < 100.00) OR (SalaryType = 'Monthly' AND Salary < 10000.00) OR (SalaryType = 'Annual') ) 78 Alter the table so that the SalaryType is not null and SalaryType is one of these: Hourly, Monthly, Annual. ALTER TABLE Payroll ADD CONSTRAINT CK_Payroll CHECK ( (SalaryType IN ('Hourly','Monthly','Annual')) AND SalaryType IS NOT NULL ) 79 Write an ALTER table statement that allows only the following cities: ‘BOSTON’, ‘DALLAS’, and ‘AUSTIN’ ALTER TABLE employee ADD CONSTRAINT validcity CHECK (CITY IN ('BOSTON', 'DALLAS', 'AUSTIN')) 80 Define a view for Sue (employee number 102) containing only orders placed by customers assigned to her. (horizontal view) CREATE VIEW SUEORDERS AS SELECT * FROM ORDERS WHERE CUST IN (SELECT CUST_NUM FROM CUSTOMERS WHERE CUST_REP = 102) Page 12 of 14 mukeshtekwani@hotmail.com
  • 13. SQL Simple Queries – WK5 82 A vertical view restricts a user’s access to only certain columns of a table. CREATE VIEW STUD_ADDRESS AS SELECT ROLLNO, NAME, ADD1, ADD2, CITY FROM STUDENTS 83 Define a view that contains summary order data for each salesperson. (grouped view) CREATE VIEW ORD_BY_REP (WHO, HOW_MANY, TOTAL, LOW, HIGH, AVERAGE) AS SELECT REP, COUNT(*), SUM(AMOUNT), MIN(AMOUNT), MAX(AMOUNT), AVG(AMOUNT) FROM ORDERS GROUP BY REP 84 Create a view to print names of all movies in capital letters. CREATE VIEW Movies_upper(title) AS SELECT UPPER(movie_title) FROM Movies 85 Create a view to find the total revenue from all movies. CREATE VIEW TRev (total_revenue) AS SELECT SUM(gross) FROM Movies 86 Create a view to find all people who live in a state where a movie studio is located. CREATE VIEW PS AS SELECT FName, LName, StudioName, Person_State FROM People, Studio WHERE Person_State = Studio_State 87 Create a view that returns the list of all the studios with an average budget of over $50 million. (view with a sub-query) CREATE VIEW Big_Movies AS SELECT movie_title, budget, gross FROM Movies WHERE studio_id IN (SELECT studio_id FROM Movies GROUP BY studio_id HAVING AVG(budget) > 50) 88 Add a single field to the 'Sales' table by specifying the new field name and data type. ALTER TABLE Sales ADD UnitPrice MONEY 89 The following example adds the reserved words NOT NULL to require valid data to be added to that field. However, you must also specify a default value for any data already inserted in the table. ALTER TABLE Sales ADD UnitPrice MONEY Prof. Mukesh N. Tekwani Page 13 of 14
  • 14. SQL Simple Queries – WK 5 DEFAULT 3.00 NOT NULL 90 This example changes the data type of the column 'ItemCount' to an integer (INT) ALTER TABLE Sales ALTER COLUMN ItemCount INT 91 This example demonstrates how to use DROP COLUMN to delete a single field. ALTER TABLE Sales DROP COLUMN UnitPrice 92 Display all students whose surname is between ‘N’ and ‘R’ SELECT * FROM STUDENTS WHERE SURNAME BETWEEN ‘N’ and ‘R’ 93 Display the highest salary paid in each department. SELECT max(salary), dept FROM employee GROUP BY dept Tables: items_ordered customerid order_date item quantity price Cutsomer customerid firstname lastname city state 94 How many people are in each unique state in the customers table? Select the state and display the number of people in each. Hint: count is used to count rows in a column, sum works on numeric data only. SELECT state, COUNT(state) FROM customers GROUP BY state 95 Write a query using a join to determine which items were ordered by each of the customers in the customers table. Select the customerid, firstname, lastname, order_date, item, and price for everything each customer purchased in the items_ordered table. SELECT c.customerid, c.firstname, c.lastname, i.order_date, i.item, i.price FROM customers c, items_ordered i WHERE c.customerid = i.customerid Page 14 of 14 mukeshtekwani@hotmail.com