# Query in English Query in SQL 1. Show me all the details of all our customers. SELECT * FROM Customers; 2. Show me all the details of all our Mexican customers. SELECT * FROM Customers WHERE Country = “Mexico”; 3. To which cities our customers belong. SELECT DISTINCT City FROM Customers; 4. To which cities our Mexican customers belong. SELECT DISTINCT City FROM Customers WHERE Country = “Mexico”; 5. Tell me the name of our first customer. SELECT CustomerName FROM Customers WHERE CustomerID = 1; 6. Tell me the names of our first 10 customers. SELECT CustomerName FROM Customers LIMIT 10; 7. Tell me the names of our customers, who belong to either Spain or Germany. SELECT DISTINCT City FROM Customers WHERE Country = “Spain” OR Country=”Germany”; 8. Show me all customers sorted by their country and city. SELECT * FROM Customers ORDER BY Country, City; 9. For which customers, we do not have their address on record? SELECT * FROM Customers WHERE Address IS NULL; 10. Show me five customer records as a sample. SELECT * FROM Customers ORDER BY RAND() LIMIT 10; 11. How many products do we have? SELECT COUNT (*) FROM Products; 12. Which is the least expensive product? SELECT MIN (Price) FROM Products; 13. Which is the most expensive product? SELECT MAX (Price) FROM Products; 14. What is the average price of our products? SELECT AVG (Price) FROM Products; 15. Which all products have a price between 10 and 20? SELECT ProductName FROM Products WHERE PRICE BETWEEN 10 AND 20; 16. Which products do not belong to category IDs, 1, 2, and 3? SELECT ProductName FROM Products WHERE CategoryID NOT BETWEEN 1 AND 3; 17. How much is the total quantity ordered so far? SELECT SUM (Quantity) FROM OrderDetails; 18. Show me all customers whose name starts with "a". SELECT CustomerName FROM Customers WHERE CustomerName LIKE “a%”; 19. Show me all customers whose name ends with "a". SELECT CustomerName FROM Customers WHERE CustomerName LIKE “%a”; 20. Show me all customers whose name have "r" in the second position. SELECT CustomerName FROM Customers WHERE CustomerName LIKE “_r%”; 21. Show me all customers whose name does not end with "a". SELECT CustomerName FROM Customers WHERE CustomerName NOT LIKE “%a”; 22. Tell me the names of our customers, who belong to either UK or Germany or France. SELECT DISTINCT City FROM Customers WHERE Country IN (“UK”, “Germany”, “France”); 23. Tell me the names of our customers, who do not belong to UK or Germany or France. SELECT DISTINCT City FROM Customers WHERE Country NOT IN (“UK”, “Germany”, “France”); 24. Show me all customers that are from the same countries as the suppliers SELECT CustomerName FROM Customers WHERE Country IN ( SELECT DISTINCT Country FROM Suppliers) 25. Show me the customer details as name and full address. SELECT CustomerName, CONCAT (Address, City, Country) AS Full_Address FROM Customers; 26. Show me product names with their category names. SELECT Products.ProductName, Categories.CategoryName FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID; 27. Show me names of customers and their dates of order. SELECT Customers.CustomerName, Orders.OrderDate FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID; 28. Show me names of customers, their dates of order, and shipper names. SELECT Customers.CustomerName, Orders.OrderDate, Shippers.ShipperName FROM Orders INNER JOIN Customers ON Customers.CustomerID = Orders.CustomerID INNER JOIN Shippers ON Shippers.ShipperID = Orders.ShipperID; 29. Show me names of customers and suppliers belonging to the same city. SELECT Customers.CustomerName, Suppliers.SupplierName, Customers.City FROM Customers INNER JOIN Suppliers ON Customers.City = Suppliers.City; 30. Show me names of companies that are both suppliers and customers. SELECT Customers.CustomerName FROM Customers INNER JOIN Suppliers ON Customers.CustomerName = Suppliers.SupplierName; 31. Show me names of all customers with their order dates, if any. SELECT Customers.CustomerName, Orders.OrderDate FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID; 32. Show me names of all employees and any orders they might have placed. SELECT CONCAT (Employees.LastName, Employees.FirstName) as EmployeeName, Orders.OrderDate FROM Orders RIGHT OUTER JOIN Employees ON Employees.EmployeeID = Orders.EmployeeID; 33. Show me all customer names and all order IDs. SELECT Customers.CustomerName, Orders.OrderDate FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID; 34. Show me all cities where our customers and suppliers are located. SELECT City FROM Customers UNION SELECT City from Suppliers; 35. Show me all German cities where our customers and suppliers are located. SELECT City FROM Customers WHERE Country = “Germany” UNION SELECT City FROM Suppliers WHERE Country = “Germany”; 36. Show me names of all customers and suppliers in a table with Party Type as an additional column. SELECT “Customers” AS PartyType, CustomerName AS PartyName FROM Customers UNION SELECT “Suppliers”, SupplierName FROM Suppliers; 37. Prepare the mailing addresses for both the customers and suppliers. SELECT CONCAT (ContactName, CustomerName, Address, City, Country) FROM Customers UNION SELECT CONCAT (ContactName, SupplierName, Address, City, Country) from Suppliers; 38. Tell me the number of customers from each country. SELECT Country, COUNT (Country) FROM Customers GROUP BY Country ORDER BY COUNT(Country); 39. Tell me the number of orders sent by each shipper. SELECT Shippers.ShipperName, COUNT(Orders.OrderID) FROM Orders INNER JOIN Shippers ON Shippers.ShipperID = Orders.ShipperID GROUP BY Shippers.ShipperName; 40. Tell me the number of customers from each country but exclude the ones with less than five customers. SELECT Country, COUNT (Country) FROM Customers GROUP BY Country HAVING COUNT (Country) >= 5; 41. Show me the last names of the employees that have registered more than 20 orders. SELECT Employees.LastName, COUNT(OrderID) FROM Employees INNER JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID GROUP BY Employees.LastName HAVING COUNT(OrderID) > 20; 42. Show me Nancy’s count of orders if she has registered more than 25 orders. SELECT COUNT (Orders.OrderID) AS NumberOfOrders FROM Employees INNER JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID WHERE Employees.FirstName = "Nancy" HAVING COUNT(Orders.OrderID) > 25; 43. Show me the product names if any one of the product in the order details has quantity equals 10. SELECT ProductName FROM Products WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10); 44. Show me the product names if any one of the product in the order details has quantity more than 1000. SELECT ProductName FROM Products WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity > 1000); 45. Show me the product names if all the products in the order details have quantity equals 10. SELECT ProductName FROM Products WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10); No-SQL Scenario and Queries for Class Exercise: Myfun Tourist Company is famous for its Solo member engaging different loners to enjoy holidays in group tours across India. Each Tour has the start Location, Destination, number of days, Tour_name, Tour_description, Tour_Minimal_cost, Tour_Zone Each also has a Day-wise Itinerary in terms of Day_No, ActivityId, Activity_name, Activity_description, City, State, Cost_if_any A Tourist books a tour and captures details like Tourist_first_name , Tourist_last_name, Tourist_Address, Tourist_State, Tourist_city, Tourist PinCode, Tourist_Phone, Tourist_email_id, Tourist_adhaar_no Tourplan consists of Tour_name, Tour_start_date, Tour_end_date, Tour_cost, Tour_Tax, Tour_Manager_Name, Tour_status and The Tourist details booked for that Tour_plan. Tour_status can be "Yet to Start", "Fun Began", "Experienced", "Cancelled" A special gadget is designed by Myfun which is handed over to each Tourist on start of the Tour_plan and collected back before Tour_end. This gadget has a chat as well as myfun wall to capture tourists experiences, grapples, complaints as well as feedback. Question Response Design the database collections in NoSQL Database Name: myfunTour Collection Name: Tour with DayWiseItinerary Embedded Document Collection Name: TourPlan with TouristDetails Embedded Document TouristExperience Embedded Document Check on whether 1. Collections are created? 2. Give help on the database class 3. Give help on the collection class 1. show collections OR db.getCollectionName(); 2. db.help() 3. db,mycoll.help() Insert data into collection Tour, TourPlan Refer to Insert collection .text file 1. myfunTour_TourCollectionInsert.txt 2. myfunTour_TourPlanCollectionInsert.txt 3. myfunTour_TourExperienceCollectionInsert.txt It was observed that the Tour_manager_name is misspelt in many documents from "Mike" to "Mice". Help this to be db.TourPlan.updateOne( {"TourManagerName" : "Mice" }, { corrected $set: {"TourManagerName": "Mike"} },true ) One of the Tour p lan was created in month of 1st to 5 August 2023 but had lesser tourists booking. Mark the Tour_plan as cancelled. db.TourPlan.updateMany( {"$and" : [{"TourStartDate" : ISODate("2023-08- 01")}, {"TourEndDate" : ISODate("2023-08-05")}] }, { $set: {"TourStatus" : "Cancelled"} } ); In Tour_plan " Greenery Munnar " , tourists with last_name "Dirv" opted out and are required to be removed from the Tour plan // Note the delete query removes the entire plan rather than just one tourist. Also if u use deleteMany, it would remove all tourplans with this tourist db.TourPlan.deleteOne( {"Tourist.TouristName.LastName" : "Dev"} ); // Modify the delete statement if only 1 plan is to be removed. db.TourPlan.deleteOne( {"$and" : [ {"Tourist.TouristName.LastName" : "Dirv"}, {"TourStartDate" : {"$gte" : ISODate("2023-09- 01")}} ] } ); // Modify the delete statement if only 1 document is to be removed. Query Criteria, RegEx, Text Search, Projection, Sort, Limit SN0 Questions Response 1 Find tou r named " Blissful Nainital" db.Tour.find({"TourName":"Blissful Nainital"}); 2 Find tours whose tour minimal cost is less than db.Tour.find({"TourMinCost":{"$lt":5000}},{"Tou rName":1,_id:0}); 5000 3 Find tours whose tour minimal cost is greater than 4000 db.Tour.find({"TourMinCost":{"$gt":4000}},{"Tou rName":1,_id:0}); 4 Find tours whose tour tax is between 2000 and 4000 db.Tour.find({"TourMinCost":{"$gt":2000,"$lt": 4 000}},{"TourName":1,_id:0}); 5 Find tours whose itinerary cost is greater than 200. Display tour name, the itinerary day number which matches the criteria. db.Tour.find({"Itinerary.ActivityCost": {$gte : 200}},{TourName:1,_id:0,"Itinerary.Day_No.$":1} ); //Note .$ will display all those embedded //documents that match the criteria. In //display only on one attribute. 6 Find tour whose activity name has “DelhiCityVisit” db.Tour.find({"Itinerary.ActivityName":"DelhiCi tyVisit"},{_id:0,TourName:1,"Itinerary.Day_No": 1,"Itinerary.ActivityName":1}); 7 Find tourists who have taken "Blissful Nainital" // use the find operator db.TourPlan.find({"TourName" : "Blissful Nainital"}, {"_id": 0, "Tourist" : 1}); 8 Find tourists who are above 40 and taken " Blissful Nainital " // use of find with $and , $gte db.TourPlan.find( {"$and":[ {"TourName" : "Blissful Nainital"}, {"Tourist.TouristAge" : {"$gte" : 40}} ] } ); 9 Find tourist who are between 20 and 30 and their tour plan details. // use of $gte and $lte db.TourPlan.find( {"Tourist.TouristAge":{"$gte" : 20, "$lte" : 40 } } ); 10 Find all tours whose status is in cancelled, completed //use of $in db.TourPlan.find({"TourStatus": {"$in":["Cancelled","Completed"]}},{TourName:1, _id:0,TourStatus:1,TourManagerName:1}); 11 Find all tours whose status is not in “Cancelled”, “Fun Began" // use of $nin db.TourPlan.find( {"TourStatus":{"$nin" : ["Cancelled", "Fun Began" ] } } ); 12 Find those tours which are neither economical nor luxury. Economy is below or db.Tour.find({$nor : [{TourMinCost : {$gte : 80000}}, {TourMinCost : {$lte:10000}}]},{_id:0, TourName:1,TourMinCost:1}); equal 10k and luxury is equal and above 80k 13 Find tho se tours only whose cost are economical or ones which are luxury. Economy is where actual tour cost below 20K and luxury is above 50k db.Tour.find({$or : [{TourMinCost : {$gte : 50000}}, {TourMinCost : {$lte:20000}}]},{_id:0, TourName:1,TourMinCost:1}); 14 Find tours which has names containing blissful or BLISSFUL. // use of RegEx search db.TourPlan.find({"TourName" : /blissful/i}); 15 Find tours which has names start with Blis or blis db.Tour.find({"TourName":{$regex : /^Blis/i}}) 16 It is required to search all the tours which has been executed by tour_managers “Rajeev”,”Pritesh”, “Mice”. Let’s try the Text Search here. Restrict the columns to display in output to Tourname, manager name as well as tourstatus // Use of text Search db.TourPlan.createIndex({ TourManagerName : "text"}); db.TourPlan.find({$text:{$search:"Pritesh Rajeev Mice"}},{TourName:1, _id:0,TourStatus:1,TourManagerName:1}) 17 Find the tour name, Date when experience was given, Experience comments who have commented “awesome experience ” , “are changing” in their experiences. db.TourExperience.createIndex({ "ExpComment.TouristReview" : "text"}); db.TourExperience.find({$text:{$search:"'\aweso me experience\' '\are changing\'"}},{TourName:1, _id:0,TourStatus:1,ExpDate:1,"ExpComment" : 1}); 18 Find the Tours available. Get only the 3 out of them. //Use of limit db.Tour.find({},{"Itinerary":0,_id:0,TourDesc:0 }).limit(3); 19 Find the TourName and Tourdesc for all the tours available. //Use of inclusion projection db.Tour.find({},{TourName:1,TourDesc:1}); //In this case, we cannot give any other //fields to 0 except _id. 20 Find the Tour details for all the tours available without the itinerary details. // use of Exclusion projection db.Tour.find({},{"Itinerary":0,_id:0}); // in this case, we cannot give any fields for display as :1, We have to identify fields to exclude. 21 Find all the Tour sorted on the Tour Name alphabetically. // use of sort db.Tour.find({},{"TourName":1,"TourDesc":1}).so rt({"TourName": 1}); 22 Find all the Tour sorted on the Tour Name reverse // use of sort db.Tour.find({},{"TourName":1,"TourDesc":1}).so rt({"TourName": - 1}); 23 Find the tours which has itinerary Activity cost greater or equal to 200 and also have ActivityCity as “Assam, Cochin” // here we need to use $elemMatch as we //need to get both embedded document value //to be matched with $and. db.Tour.find({"Itinerary": {"$elemMatch":{"ActivityCost" : {"$gte" : 200},"City" : {"$in" : ["Cochin","Assam"]} }} }); 24 Find all the tour plans which started between 20 July 2022 to 1 Jan 2023. Aggrega Ɵ on FW : Sno Queries Response 1 For the tour plans with status completed and Tour start date is greater than 1 Oct 2022, get their tour details. Get the tour_name, tour_description, tourNoofdays, tour_start_date, tour_end_date, tour_plan_status, tour_managerName // Here we use two aggregation f/w stages //$match – this is to extract data matching the criteria. In our case, its tour status as completed and Tour plan start date is greater than 1 oct 2022.. //$lookup – this is to get parent tour details using the tour_name which is common in tour_plan and tour. //$set – to set the fields which are to be displayed from the referenced collection. //$unset – to remove the other fields from the referenced collection. Refer to AggregationFW_Response.txt, Ans-1 2 Find all the t our s available and get the relevant tour details like Tour Name, Tour Number of days, Day number, daywise total ActivityCost, total number of activities per day sorting them on the Tour Name and day number // Here we use two aggregation f/w stages //$unwind : This makes the parent fields attributes to be repeated for each embedded document. Here for each day no, tour details like tour name, start location all those details will be repeated. // $group : This does a grouping on the selected fields and helps in doing sum or average on numerical fields. // $sort : This sorts the output in ascending or descending order Refer to AggregationFW_Response.txt, Ans-2 3 Find Tours with number of activities per day. Provide details like Tour Name, Tour Start Location, Tour End location, Day_No, Count of // This is a case of unwinding the day //itinerary and // using the $group, $count.. Note to get //the tour start locn, end location u //might have to add them in the $group var pipeline = [ Activities per day // unwind Itinerary {"$unwind": "$Itinerary"}, //Group by TourName {"$group" : {"_id" : {"TourName" : "$TourName", "TourStartLocn" : "$TourStartLocn", "TourEndLocn" : "$TourEndLocn" , "TourNoOfDays" : "$TourNoOfDays", "Day_No" : "$Itinerary.Day_No"}, "TotalActivities" : { $sum : 1 } } }, // Omit unwanted fields {"$unset": [ "Itinerary", ]}, // sort on Tourname, day_no {"$sort": { "_id": 1, }}, ]; db.Tour.aggregate(pipeline); 4 Find all the t our _plan for current financial year and get the relevant tour details like TourstartLocation, end location, number of days, count of tourists // Use of $match to find the plans in the current year // Use of $lookup for the tour related details from Tour. var pipeline = [ {"$match": {"TourStartDate": {"$gt" : ISODate("2023-04-01"), "$lt": ISODate("2024-03-31") } } }, // unwind Tourists {"$unwind": "$Tourist"}, //Group by TourName {"$group" : {"_id" : {"TourName" : "$TourName"}, "TotalTourists" : { $count : {} } } }, // lookup to the Tour for details of tour. { $lookup: { from: "Tour", localField: "_id.TourName", // field in the TourPlan collection foreignField: "TourName", // field in the Tour collection as: "fromTour", }}, // For this data model, will always be 1 record in right-side // of join, so take 1st joined array element {"$set": { "fromTour": {"$first": "$fromTour"}, }}, // Extract the joined embeded fields into top level fields {"$set": { "TourStartLocn": "$fromTour.TourStartLocn", "TourEndLocn": "$fromTour.TourEndLocn", "TourNoOfDays": "$fromTour.TourNoOfDays", }}, // Omit unwanted fields {"$unset": [ "fromTour", ]}, // sort on TourName {"$sort": { "_id": 1, }}, ]; db.TourPlan.aggregate(pipeline);