SQL in Action Amit Bhawnani & Nimesh Shah. Basic Structure SQL is based on set and relational operations with certain modifications and enhancements A.

Slides:



Advertisements
Similar presentations
Advanced SQL (part 1) CS263 Lecture 7.
Advertisements

Union, Intersection, Difference (subquery) UNION (subquery) produces the union of the two relations. Similarly for INTERSECT, EXCEPT = intersection and.
Database Languages Chapter 7. The Relational Algebra.
Information Resources Management February 27, 2001.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Query by example (based on notes by Silberchatz,Korth, and Sudarshan.
1 SQL-Structured Query Language SQL is the most common language used for creating and querying relational databases. Many users can access a database applications.
1 Creating a Non-Conditional List A- What are you going to do? You will “list” “all of the records” in a database. (it means you will not use any condition!)
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Tutorial 5 Multi-table queries. Tutorial 5 objectives Displaying Data from Multiple Tables –[ ]Write SELECT statements to access data from more than one.
Chapter 7: SQL, the Structured Query Language Soid Quintero & Ervi Bongso CS157B.
02 | Advanced SELECT Statements Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE) Datalog.
Introduction to Databases Chapter 7: Data Access and Manipulation.
C H A P T E R 4 Designing Database E-Commerce Hassanin M. Al-Barhamtoshy
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
Oracle Database Administration Lecture 2 SQL language.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
Final Exam Guide PHP NOTE: PHP CODE WILL BE BLUE, HTML IS BLACK EXAMPLE
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
INTERACTIVE SQL PART II Prepared By: Mitali Sonar (Assistant Prof.) 1 10/17/2015.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
SELECT e.NationalIDNumber, p.FirstName,p.LastName, City FROM HumanResources.Employee e INNER JOIN Person.Person p on p.BusinessEntityID = e.BusinessEntityID.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE)
1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement.
SQL from the Trenches Presented by: Robert Arce.
Recap of SQL Lab no 8 Advance Database Management System.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Computing & Information Sciences Kansas State University Monday, 17 Sep 2007CIS 560: Database System Concepts Lecture 12 of 42 Monday, 18 February 2008.
Source: Database System Concepts, Silberschatz etc Edited: Wei-Pang Yang, IM.NDHU, Introduction to Database CHAPTER 5 Other Relational Languages.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Relational Schema and SQL Queries James Wang.
Structured Query Language
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
1 Introduction to Database Systems CSE 444 Lecture 04: SQL April 7, 2008.
More SQL (and Relational Algebra). More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Drill Consider the following tables with the following fields: Student: FName, LName, StudentID, Age, Yr, Course Grades: ID, P1, P2, P3 1.Display the.
IMS 4212: Intro to Multi-Table SELECT Statements 1 Dr. Lawrence West, MIS Dept., University of Central Florida Multi-Table SELECT Statements—Topics.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
Thinking in Sets and SQL Query Logical Processing.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
1 All Powder Board and Ski SQL Server Workbook Chapter 5: Advanced Queries Jerry Post Copyright © 2003.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
CFUNITED – The premier ColdFusion conference Beyond Basic SQL for CF Nate Nelson
SQL, the Structured Query Language
How to: SQL By: Sam Loch.
CS3220 Web and Internet Programming More SQL
Structured Query Language
Lecture 05: SQL Wednesday, January 12, 2005.
Outerjoins, Grouping/Aggregation Insert/Delete/Update
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
02 | Advanced SELECT Statements
Schedule Today: Next After that Subqueries, Grouping and Aggregation.
Introduction to Database Systems CSE 444 Lecture 04: SQL
Data warehouse Design Using Oracle
Web Services שפת SQL כתבה: זהבה יעקובסון ליווי מקצועי : ארז קלר
RELATIONAL DATABASES AND XML
Chapter 4 Summary Query.
Structured Query Language – The Fundamentals
Advanced Joins IN ( ) Expression Subqueries with IN ( ) Expression
More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation
Manipulating Data Lesson 3.
Presentation transcript:

SQL in Action Amit Bhawnani & Nimesh Shah

Basic Structure SQL is based on set and relational operations with certain modifications and enhancements A typical SQL query has the form: select A 1, A 2,..., A n from r 1, r 2,..., r m where P – A i s represent attributes – r i s represent relations – P is a predicate. This query is equivalent to the relational algebra expression.  A1, A2,..., An (  P (r 1 x r 2 x... x r m )) The result of an SQL query is a relation.

SELECT What are the names and prices of all the products we carry? Select product name, retail price from the products table SELECT ProductName, RetailPrice FROM Products

DISTINCT Which states do our customers come from ? Select the distinct state values from the customers table Select DISTINCT custState FROM Customers Tip: Use only when necessary

SELECT ALL Display all the information on our employees SELECT * FROM employees Tip: explicitly specify columns instead of querying with *

ORDER BY Display a list of vendor names in ZIP Code order. SELECT VendName, VendZipCode FROM Vendors ORDER BY VendZipCode

ORDER BY Display the names of our employees, including their phone number and ID number, and list them by last name and first name. SELECT EmpLastName, EmpFirstName,EmpPhoneNumber, EmployeeID FROM Employees ORDER BY EmpLastName, EmpFirstName

Concatenation Expression Give me a list of employee full names and their dates of birth. Select EmpFirstname || ‘ ‘ || EmpLastName as EmployeeName, DOB AS DateOfBirth FROM Employees

Mathematical Expression What is the inventory value of each product? SELECT ProductName, RetailPrice * QuantityOnHand AS InventoryValue FROM Products

Aggregate Functions - SUM What is the total amount we pay in salaries to ALL our employees? SELECT SUM(Salary) AS TotalSalaryAmount FROM Employees

Aggregate Functions - MIN What is the lowest price we charge for a product? SELECT MIN(Price) AS LowestProductPrice FROM Products

FILTER What are the names of our customers who live in the state of washington (WA)? SELECT CustFirstName, CustLastName FROM Customers WHERE CustState = 'WA'

COUNT How many of our customers live in the state of washington (WA)? SELECT count(*) as NumberOfCustomers FROM Customers WHERE CustState = 'WA'

FILTER - Inequality Display a list of vendor names and phone numbers for all our vendors,with the exception of those here in Bellevue. SELECT VendName, VendPhone FROM Vendors WHERE VendCity <> 'Bellevue'

Filter - Less Than and Greater Than Are there any orders where the ship date was accidentally posted earlier than the order date? SELECT OrderNumber FROM Orders WHERE ShipDate < OrderDate

LIKE Show me an alphabetical list of products with names that begin with ‘Dog’ SELECT ProductName FROM Products WHERE ProductName LIKE 'Dog%‘ ORDER BY ProductName

Multiple Filters Display customers with the last name 'Patterson’ and the customer should belong to the state CA or the zip code should end in 9. SELECT CustFirstName, CustLastName, CustState, CustZipCode FROM Customers WHERE CustLastName = 'Patterson‘ AND (CustState = 'CA‘ OR CustZipCode LIKE '%9‘)

BETWEEN Display the list of Orders that were placed in September 2007 Select * from Orders WHERE OrderDate BETWEEN ' ' AND ' ‘

IS NULL Which vendors do we work with that don’t have a Web site select vendorID,VendName from vendors where VendWebPage is null

IN Give me the names of all vendors based in Ballard, Bellevue, and Redmond select vendorID,VendName from vendors where VendCity in ( 'Ballard', 'Bellevue', 'Redmond' )

TOP Display the name and retail price of the 10 most expensive products Select top 10 productName,RetailPrice from products order by retailPrice desc

GROUP BY Display the numbers of customers from each city in descending order of the number of customers. SELECT CustCity, Count(*) as CustPerCity FROM Customers GROUP BY Customers.CustCity ORDER by CustPerCity desc

GROUP BY Display product number and total sales for each product SELECT productNumber, SUM(QuotedPrice*QuantityOrdered) as total_price FROM Order_Details GROUP BY productNumber ORDER BY total_price desc

HAVING Display for the productnumber for all the products where the total sales for the product is greater than SELECT productNumber, SUM(QuotedPrice*QuantityOrdered) as total_price FROM Order_Details GROUP BY productNumber HAVING sum(QuotedPrice*QuantityOrdered) > order by total_price desc Tip: Having clause is used to filter rows after all the rows are selected. Do not try to use HAVING instead of WHERE

INNER Join Display all product names and their category descriptions. SELECT Categories.CategoryDescription, Products.ProductName FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID

More then two tables List of customer names who have ever ordered a helmet. SELECT DISTINCT Customers.CustFirstName, Customers.CustLastName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID INNER JOIN Order_Details ON Orders.OrderNumber = Order_Details.OrderNumber INNER JOIN Products ON Products.ProductNumber = Order_Details.ProductNumber WHERE Products.ProductName LIKE '%Helmet%'

Left Outer Join What products have never been ordered ? SELECT Products.ProductNumber, Products.ProductName FROM Products LEFT OUTER JOIN Order_Details ON Products.ProductNumber = Order_Details.ProductNumber WHERE Order_Details.OrderNumber IS NULL

LEFT OUTER JOIN List product number, Product name and the quantity ordered for each product. Also include the products that have not been ordered. Order in descending order of products sold. SELECT Products.ProductNumber, Products.ProductName, b.cnt FROM Products LEFT OUTER JOIN ( select productNumber,sum(quantityOrdered) as cnt from Order_Details group by productNumber ) as b ON Products.ProductNumber = b.ProductNumber

Subqueries as Filters (IN) Find all the customers who have placed an order on select customerId,custFirstName,CustLastName from customers where customerid in (select customerid from orders where OrderDate = ' ')

Correlated subquery Find all the customers that have placed over 40 orders select customerId,CustFirstName,CustLastName from Customers c where 40 < (select count(*) from orders o where o.customerId = c.customerId)

EXISTS List of all employees who generated a sale on the select EmpFirstName,EmpLastName from employees where exists (select 1 from Orders where Orders.EmployeeId = employees.EmployeeId and OrderDate = ' ')

NOT EXISTS List of all employees who did not make any sales on the select EmpFirstName,EmpLastName from employees where not exists (select 1 from Orders where Orders.EmployeeId = employees.EmployeeId and OrderDate = ' ')

Subqueries as Column Expressions Display a list of customers and the last date on which they placed an order SELECT Customers.CustFirstName, Customers.CustLastName, (SELECT MAX(OrderDate) FROM Orders WHERE Orders.CustomerID = Customers.CustomerID) AS LastOrderDate FROM Customers

Subqueries as Column Expressions List vendors and a count of the products they sell to us Select VendName,(select count(productNumber) from product_vendors where vendorId = vendors.vendorid) from vendors

EXCEPT Find all the customers who have placed an order on but NOT on select customerId,custFirstName,CustLastName from customers where customerid in ( select customerid from orders where OrderDate = ' ‘ except select customerid from orders where OrderDate = ' ‘ )

UNION Give a list of customer full and vendor full names that belong to the state of texas. SELECT CustFirstName + ' ' + CustLastName as CustName from customers where custState = 'TX‘ union select VendName from vendors where VendState = 'TX' Tip: try to use UNION ALL in place of UNION.

Update Increase the retail price of all products by 10 percent. UPDATE Products SET Price = Price + (0.1 * Price)

Update – with filters Modify products by increasing the retail price by 4 percent for products that are clothing UPDATE Products SET RetailPrice = RetailPrice * 1.04 WHERE CategoryID = (SELECT CategoryID FROM Categories WHERE CategoryDescription = 'Clothing')

Delete Delete all order details for orders placed before January 1, 2008 DELETE FROM Order_Details WHERE OrderNumber IN (SELECT OrderNumber FROM Orders WHERE OrderDate < ' ')

Delete Delete vendors who do not provide any products DELETE FROM Vendors WHERE VendorID NOT IN (SELECT VendorID FROM Product_Vendors)

Insert Insert into the employees table in the columns first name,last name, street address, city, state, ZIP Code, area code, and phone number the values Susan, Metters, NE 132nd St, Woodinville,WA, 98072, 425, and INSERT INTO Employees (EmpFirstName, EmpLastName, EmpStreetAddress, EmpCity, EmpState,EmpZipCode, EmpAreaCode, EmpPhoneNumber) VALUES ('Susan', 'Metters','16547 NE 132nd St', 'Woodinville', 'WA','98072', 425, ' ')

Insert data by using SELECT Copy to the Employees table the relevant columns in the Customers table for customer David Smith. INSERT INTO Employees (EmpFirstName, EmpLastName, EmpStreetAddress, EmpCity, EmpState, EmpZipCode, EmpAreaCode, EmpPhoneNumber) SELECT Customers.CustFirstName,Customers.CustLastName, Customers.CustStreetAddress, Customers.CustCity, Customers.CustState, Customers.CustZipCode, Customers.CustAreaCode, Customers.CustPhoneNumber FROM Customers WHERE Customers.CustFirstName = 'David' AND Customers.CustLastName = 'Smith'

Create table Create a dept table with dept_id (PK), description, insert_date Modify the employees table and associate the department id with the employees create table department ( dept_id integer primary key, description varchar(50) not null, addition_date datetime default getdate() ) Alter table employees add dept_id integer foreign key references department(dept_id)