View
2.410
Download
4
Category
Preview:
DESCRIPTION
SQL
Citation preview
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 1 of 14
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’
SQL Simple Queries – WK 5
Page 2 of 14 mukeshtekwani@hotmail.com
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'
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 3 of 14
• 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
SQL Simple Queries – WK 5
Page 4 of 14 mukeshtekwani@hotmail.com
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
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 5 of 14
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
SQL Simple Queries – WK 5
Page 6 of 14 mukeshtekwani@hotmail.com
(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
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 7 of 14
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
SQL Simple Queries – WK 5
Page 8 of 14 mukeshtekwani@hotmail.com
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’.
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 9 of 14
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.
SQL Simple Queries – WK 5
Page 10 of 14 mukeshtekwani@hotmail.com
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)
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 11 of 14
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))
SQL Simple Queries – WK 5
Page 12 of 14 mukeshtekwani@hotmail.com
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)
SQL Simple Queries – WK5
Prof. Mukesh N. Tekwani Page 13 of 14
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
SQL Simple Queries – WK 5
Page 14 of 14 mukeshtekwani@hotmail.com
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
Recommended