Book Image

The SQL Workshop

By : Frank Solomon, Prashanth Jayaram, Awni Al Saqqa
Book Image

The SQL Workshop

By: Frank Solomon, Prashanth Jayaram, Awni Al Saqqa

Overview of this book

Many software applications are backed by powerful relational database systems, meaning that the skills to be able to maintain a SQL database and reliably retrieve data are in high demand. With its simple syntax and effective data manipulation capabilities, SQL enables you to manage relational databases with ease. The SQL Workshop will help you progress from basic to advanced-level SQL queries in order to create and manage databases successfully. This Workshop begins with an introduction to basic CRUD commands and gives you an overview of the different data types in SQL. You'll use commands for narrowing down the search results within a database and learn about data retrieval from single and multiple tables in a single query. As you advance, you'll use aggregate functions to perform calculations on a set of values, and implement process automation using stored procedures, functions, and triggers. Finally, you'll secure your database against potential threats and use access control to keep your data safe. Throughout this Workshop, you'll use your skills on a realistic database for an online shop, preparing you for solving data problems in the real world. By the end of this book, you'll have built the knowledge, skills and confidence to creatively solve real-world data problems with SQL.
Table of Contents (13 chapters)

8. SQL Programming

Activity 8.01: Building a Stored Procedure

Solution:

  1. Execute the following query:
    CREATE DEFINER=`root`@`localhost` PROCEDURE `spFilterOrdersByItemQuantity`(IN orderItemQuantityVal int)
    BEGIN
     SELECT  OI.OrderID, SUM(OI.Quantity)      AS 'Total Order Item Quantity'
     FROM  OrderItems OI
     GROUP BY OI.OrderID
     HAVING SUM(OI.Quantity) <= orderItemQuantityVal
     ORDER BY OI.OrderID;
    END
  2. Test the stored procedure using the following query:
    USE packt_online_shop;
    CALL spFilterOrdersByItemQuantity(25);

Activity 8.02: Working with MySQL Functions

Solution:

  1. Write the following query:
    CREATE DEFINER =`root`@`localhost` FUNCTION `fnProductTotalOrderQty`(ProductID INT)
    RETURNS INT
    DETERMINISTIC
    BEGIN
    DECLARE retVal INT;
    SET retVal = (
    SELECT
    CASE
        WHEN     SUM(OI.quantity) IS NULL THEN 0
    ELSE
        SUM(OI.quantity)
    END AS 'quantity'
    FROM     OrderItems...