Lab 12
Lab 12
Laboratory Manuals
for
Page 1 of 18
Lab Manual 12
SQL
SQL tutorial gives unique learning on Structured Query Language and it helps to make practice on SQL
commands which provides immediate results. SQL is a language of database, it includes database
creation, deletion, fetching rows and modifying rows etc. SQL is an ANSI (American National Standards
Institute) standard, but there are many different versions of the SQL language.
Why SQL?
● Allows users to access data in relational database management systems.
● Allows users to describe the data.
● Allows users to define the data in the database and manipulate that data.
● Allows embedding within other languages using SQL modules, libraries & pre-compilers.
● Allows users to create and drop databases and tables.
● Allows users to create views, stored procedure, functions in a database.
● Allows users to set permissions on tables, procedures and views
SQL Process
When you are executing an SQL command for any RDBMS, the system determines the best way to carry
out your request and SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher,
Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine handles
all non-SQL queries, but SQL query engine won't handle logical files.
Page 2 of 18
1. CTEs
A CTE (Common Table Expression) is a temporary named result set in SQL that you can
reference within a SELECT, INSERT, UPDATE, or DELETE statement.
Think of it as a temporary view that's only available during the execution of a single query.
2. PRINT KEYWORD
● Used to display a message in the query output (mainly in SQL Server).
● Helpful for debugging and tracking execution flow inside stored procedures or scripts.
3. RAND() FUNCTION
● Returns a random float value between 0 and 1.
● Useful for generating test data or randomizing results.
Page 3 of 18
● To generate a random integer between two numbers:
PL SQL
PL/SQL stands for Procedural Language extensions to SQL. It is Oracle's procedural programming
language, designed to extend the power of SQL with the ability to use programming constructs like
variables, loops, conditions, and error handling.
Key Features:
b. Supports control flow: Includes IF, LOOP, WHILE, FOR, CASE, etc.
e. Tightly integrated with SQL: Allows use of DML/DDL statements within procedural code.
Handling Variables
● Declaration
○ You declare a variable to store and reuse data within SQL blocks, procedures,
or functions.
● Setting
● Using
○ Once declared and set, variables can be used in conditions, calculations, and output.
Page 4 of 18
Code Block
● A group of statements executed together, often enclosed in BEGIN ... END
IF...ELSE
CASE Expression
● Inline conditional logic—used in SELECT, WHERE, ORDER BY, etc.
Page 5 of 18
WHILE Loop
● Repeats code block while a condition is true.
Page 6 of 18
GOTO
● Transfers execution to a labeled part of the script (less recommended for clarity).
Page 7 of 18
Trigger (For Detail, refer previous manuals specific to triggers)
● Automatically executes in response to a SQL event (INSERT, UPDATE, DELETE).
Scalar Function
A scalar function is a user-defined or built-in SQL function that returns a single value (a scalar), based on
input values or expressions. Unlike table-valued functions (which return rows/columns), scalar
functions always return only one value of a defined data type.
Built-In Types
These are provided by SQL and categorized into:
Page 8 of 18
Example
Page 9 of 18
Using Scalar Function as Computed Column in ALTER TABLE
Applications
1. Scalar Function
2. Trigger
3. Stored Procedure
Page 10 of 18
Comparison of Stored Procedures, Triggers and Scalar Functions
Page 11 of 18
Happy learning and querying!
Download sql file provided with this manual. Run that file and a schema with
following details will be created:
Page 12 of 18
In Lab Exercises
Characters:
● Super Dog – The hero! Can fly, analyze data at super-speed, and communicate with AI systems.
● EcoCat – Expert in Scope 1, 2, and 3 emissions, has infrared vision to detect direct emissions.
● PandaBytes – The coder panda, good with spreadsheets, databases, and modeling.
● Chameleon Camo – Disguises herself to infiltrate polluting facilities and collect raw data.
Mission Objective:
Help Super Dog and his team gather, calculate, and analyze carbon emissions data from different
suppliers, sites, and emission scopes to build a full emissions profile for EcoMetra’s organizations.
Page 13 of 18
Write these queries to getting started with in-lab work
1. SuperDog noticed that Site Managers accidentally submit the same emission patrol record
multiple times for the same source on the same day. Help SuperDog by writing a trigger
that blocks duplicate entries for the same site_id, source_id, and record_date
2. Professor Bark wants to classify all emission records into “Low,” “Moderate,” or “High” levels so
he can assign cleanup teams accordingly. Create a scalar function called
fn_GetEmissionCategory that:
Use this function in a SELECT query to show all records and their category!
3. GadgetTail wants each emission record to show its category right in the table for
dashboard display.
5. If a site consumes > 20000 liters of diesel in a single record, it's considered an emergency
fuel burn. This requires:
Page 14 of 18
○ Detects this case on insert/update
Page 15 of 18
Part-II: Snake & Ladder Game Simulation using SQL
Simulate a two-player Snake & Ladder game using SQL. Players take turns rolling a dice, and their
positions on a board are updated based on the dice roll. The game alternates between Player 1 and
Player 2, with every odd record being Player 1's turn and every even record being Player 2's turn
Requirements:
1. Table Design: Create a table LudoGamePlay to track each player's move. The table should
store the following
2. Game Flow
○ Player 1 starts first. Each player rolls a dice and moves accordingly.
Page 16 of 18
○ If the dice roll takes a player past position 100, they remain at position 100.
○ The game alternates between Player 1 and Player 2 until one of them reaches
position 100.
1. Dice Roll
A record will be inserted into the LudoGamePlay table having the value for dice_roll
calculated by rand()
roll e.g.
LudoGamePlay
AFTER INSERT
Page 17 of 18
Submission Guidelines
Page 18 of 18