



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Read: Chapter 3, pages 69 โ 81. Turn in homework More SQL Sometimes you'd like the output in textual format instead of columns. You can concatenate columns โ unfortunately, the syntax is not consistent between DBMSs: mySQL โ use CONCAT function SQLServer โ use + Example: Select concat( buyer, ' is in the ', department, ' department' ) AS 'Buyer In' from SKU_Data; Select buyer + ' is in the ', department, ' department' AS 'Buyer In' from SKU_Data; GROUP BY with WHERE, HAVING clause where clause โ filters raw data (before grouping) having clause โ filters group data (after grouping) select orderNumber, sum( extendedPrice ) from order_item group by orderNumber; select orderNumber, sum( extendedPrice ) from order_item where orderNumber != 1000 group by orderNumber; select orderNumber, sum( extendedPrice ) from order_item group by orderNumber having sum( extendedPrice ) > 500; Note: To be safe, put WHERE before GROUP BY. Not all DBMSs require this, but some do. select orderNumber, sum( extendedPrice ) from order_item
where extendedPrice > 50 group by orderNumber having sum( extendedPrice ) > 500 SQL applies the WHERE criteria before the group criteria โ this is to avoid ambiguity in the statements. Subqueries Up to this point, all of our queries have operated on a single table. We've been able to derive a lot of useful information this way, but by using multiple tables, we can derive a lot more. Suppose we want to look at the order details for the order that contains SKU 200100? Well, first we could use a query to look up the order that contains this SKU: select orderNumber from order_item where SKU = 200100; And then we could use that number in another query: select * from retail_order where orderNumber = 1000; But, this isn't very nice. We'd like to be able to do this in one step. We can! Use a subquery: select * from retail_order where orderNumber = ( select orderNumber from order_item where SKU = 200100 ); A subquery is a Select statement that is nested inside of another select statement. What if we are interested in the order containing SKU 302000? [Repeat above, using this number. What happens? How can we get around this problem?]. Use IN. select * from retail_order where orderNumber IN ( select orderNumber from order_item where SKU = 302000 );
from <table1, table2> where table1.column = table2.column; select
where s.sku = oi.sku and ( buyer in ('Mr. Spock', 'Deanna Troi' ) OR department = 'Lawn Sports'); select * from SKU_Data s JOIN order_item oi ON s.sku = oi.sku WHERE ( buyer in ('Mr. Spock', 'Deanna Troi' ) OR department = 'Lawn Sports'); Note that in above queries, SKU appears twice in the result table.