Uploaded by Muhammad Rizwan

Lab Manual DB

advertisement
Lab Manual
Fall-2023
Database Systems
BSCS
Faculty of Information Technology
USA Lahore Pakistan
DATABASE MANAGEMENT SYSTEMS LAB
1
WEEKLY PLAN OF LECTURES
Week 1
Introduction of Database Systems and its Practical Use
Installation of SQL server and SSMS.
Week 2
Create Database ,Table in SQL, DDL, DML and DCL commands
Week 3
Select, From, Where all related Queries in SQL,
Distinct and Order by clause
Week 4
Arithmetic Operators in SQL.
Logical and Relational Operators In SQL.
Week 5
Group functions, Having clause, Column and Table Alias.
Week 6
Class Task to run queries using various clauses
Week 7
Commands to Alter Table, Add or Drop a Column, update data
Week 8
MID TERM EXAM
Week 9
Use queries Delete Table and a Row, Truncate a Table in SQL.
Week 10
JOINS in SQL Server.
Week 11
Subqueries
Week 12
Single Row functions in SQL
Week 13
Stored Procedure and Views
Week 14
Triggers
Week 15
Views and its types in SQL.
Week 16
CRUD operations using C# language with SQL server
Week 17
FINAL TERM EXAM
WEEK 01 (Fall 2022)
Instructor:
•
M. Rizwan Waseem (Lab)
Learning Objective(s):
•
•
•
•
Installation of SQL server and SSMS.
Create a new database named Northwind
Restore Schema using scripts northwind.sql
Restore schema data using northwind_data.sql
1. System Requirements for SQL Server 2019
1.1.
Operating system
Windows 10 TH1 1507 or greater and Windows Server 2016 or greater
1.2.
.NET Framework
SQL Server 2016 (13.x) RC1 and later require .NET Framework 4.6 for the Database Engine,
Master Data Services, or Replication. SQL Server setup automatically installs .NET Framework.
You can also manually install .NET Framework from Microsoft .NET Framework 4.6 (Web
Installer) for Windows.
1.3.
Disc Space
SQL Server requires a minimum of 6 GB of available hard-disk space.
1.4.
Memory
At least 4 GB and should be increased as database size increases to ensure optimal
performance.
1.5.
Processor
DATABASE MANAGEMENT SYSTEMS LAB
3
•
Minimum: x64 Processor: 1.4 GHz, Recommended: 2.0 GHz or faster
•
x64 Processor: AMD Opteron, AMD Athlon 64, Intel Xeon with Intel EM64T
support, Intel Pentium IV with EM64T support
1.6.
Monitor
SQL Server requires Super-VGA (800x600) or higher resolution monitor.
2. Installation guide
Important Note:
2.1.
connect your system with internet and download the developer edition using this given link:
https://www.microsoft.com/en-us/sql-server/sql-server-downloads
2.2.
Login on window with as Administrator
1:
2.3. Once downloaded then click on the .exe file and run.
DATABASE MANAGEMENT SYSTEMS LAB
4
2.4. Then click on Basic version to install.
DATABASE MANAGEMENT SYSTEMS LAB
5
Figure2: Selection of basic version
2.5.
Scroll down and then click on accept.
Figure3: Terms and conditions for installing SQL Server
2.6. Click on Install and eat pop corns until installation is done.
DATABASE MANAGEMENT SYSTEMS LAB
6
2.7.
After installation is done click on install SSMS
Figure5:
DATABASE MANAGEMENT SYSTEMS LAB
7
2.8. Click on highlighted link. It will download .exe file of SSMS. After
downloading run .exe file.
DATABASE MANAGEMENT SYSTEMS LAB
8
Figure6: Version of SSMSfor installation
2.9.
Click on Install and wait until installation is done successfully.
Figure 7: Installation of SSMS
DATABASE MANAGEMENT SYSTEMS LAB
9
3. Generate Scripts of a schema
• Step 1
Right click on your database and select Task -> generate script.
Figure 8: Database_Scripts_With_Data_Select_Option
DATABASE MANAGEMENT SYSTEMS LAB
10
Step 2
Click next in the introduction screen
Figure 9: Database_Scripts_With_Data_Introduction
DATABASE MANAGEMENT SYSTEMS LAB
11
•
Step 3
Select the database object which you are all you need and then click next.
Figure 10: Selecting database objects
DATABASE MANAGEMENT SYSTEMS LAB
12
Step 4
Now you will be shown a window which asks you about how your script should be published.
Figure 11: Database_Scripts_With_Data_Publish_Options
Click on advanced in that window.
DATABASE MANAGEMENT SYSTEMS LAB
13
Step 5
Select ‘Schema and data’ from type of data to script option and then click OK.
Figure 12: Database_Scripts_With_Data_Advanced Click on Next.
Page 14 of
2
Step 6
Click finish, now check the script file, it must be having the insert queries too.
Figure 13: Database_Scripts_With_Data_Finish
Now what else is pending, go ahead and run your script.
Page 15 of
2
Lab Tasks
1.
Create a new database named TestDB_2022_CS
2.
Create a new table named student using some attributes
3.
Generate Scripts of your database
4.
Restore your schema to another machine
5.
Generate scripts of data
6.
Restore data to other system as well
Page 16 of
2
Week 02 (Fall 2022)
Instructor: M. Rizwan Waseem
Learning Objective(s): To create database and table using SQL, Briefing various commands and their use.
Structured query language is mainly divided into 5 sub language
SQL Data
types
Datatypes define what type of data a column can hold
Numeric data types store all numerical values or integer values.
Page 17 of
2
Constraints in SQL
What is Data Integrity
Data integrity ensures that the data which is going to enter in the database is reliable, accurate and consistent.
Data integrity maintains the correctness and completeness of data.
What is Constraints
To maintain the data integrity, we use the constraints. Constraints are the rules which we applied on the
table’s column to ensure the data integrity.
We can add constraints on column while creating the table and can also add after creating the table.
Constraints are used to specify rules for data in a table.
The following constraints are commonly used in Sql:
NOT NULL - Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
FOREIGN KEY - Uniquely identifies a row/record in another table
CHECK - Ensures that all values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column when no value is specified
INDEX - Used to create and retrieve data from the database very quickly
Page 18 of
2
Create Database:
Syntax:
Create database database_ name;
Create Table:
Once a database is made it is easy to add tables in it, a table in SQL is like
Syntax:
CREATE TABLE table_name (
Column_1 data_type Identity (1 1) PRIMARY KEY,
Column_2 data_type NOT NULL,
Column_3 data_type NULL
Column_4 data_type
...,
);
INSERT:
Using this command we can Insert the records into the existing table
We can insert the records into the table in two methods
1. Explicit method
2. Implicit method
Explicit method
In this method user has to enter all the values into all the columns without anything omitting (or) left any
column data
Syntax:
INSERT INTO <TABLE NAME> VALUES <VAL1, VAL2,….VALN>;
Page 19 of
2
(OR)
INSERT <TABLE NAME> VALUES <VAL1, VAL2, .VALN>;
(Here “INTO” Keyword is optional)
Ex1: INSERT INTO EMP VALUES (101,‟RAJ‟,9500);
Ex2: INSERT EMP VALUES (101,‟RAJ‟,9500);
Implicit Method:
In this method we can enter the values into the required columns in the table, so that user can omit (or) left
some columns data while he enters the records into the table
If the user omit any column data in the table then it automatically takes NULL
Syntax: INSERT INTO <TABLE NAME> (COL1, COL2….COLN) VALUES (VAL1, VAL2… VALN);
Ex: INSERT INTO EMP (EID, SAL) VALUES (106,9999);
Lab Tasks:
1. Create a new database named Lab2
2. Create table with following schema Student (Registration Number: String, Name: String, Department:
String, Session: Number, CGPA: Number, Address: String)
3. Insert 10 records using both insert methods.
Page 20 of
2
Week 03:
Instructor: M. Rizwan Waseem
Learning Objective(s):
Understand use of basic queries in SQL Select, From, Where , Distint , Order By all related Queries in SQL
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, are the field names of the table you want to select data from. If you want to select all
the fields available in the table, use the following syntax:
SELECT * FROM table_name;
SELECT Column Example
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table:
Example
SELECT CustomerName, City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
The SQL WHERE Clause
The WHERE clause is used to filter records.
Page 21 of
2
The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
WHERE Clause Example
The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Example
SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers
WHERE CustomerID=1;
The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
The SELECT DISTINCT statement is used to return only distinct (different) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
The SQL ORDER BY Keyword
Page 22 of
2
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ... FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
column:
Example
SELECT * FROM Customers ORDER BY Country;
Lab Task
Task 01: Perform various queries on the inserted and saved data.
Task 02: Check output and practice by changing data.
Task 03: Perform various queries on the inserted and saved data.
Page 23 of
2
Week 4
Instrutor: M. Rizwan Waseem
Objective(s): Use of Logical and Relational Operators in SQL.
SQL Comparison Operators
Operator
Description
=
Equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
<>
Not equal to
Page 24 of
SQL Logical Operators
Operator
Description
AND
TRUE if all the conditions separated by AND is
TRUE
BETWEEN
TRUE if the operand is within the range of
comparisons
IN
TRUE if the operand is equal to one of a list of
expressions
LIKE
TRUE if the operand matches a pattern
NOT
Displays a record if the condition(s) is NOT
TRUE
OR
TRUE if any of the conditions separated by OR
is TRUE
Example
1. SELECT * FROM Customers
Page 25 of
WHERE City = "London" AND Country = "UK";
2. SELECT * FROM Customers
WHERE City NOT LIKE 's%';
3. SELECT * FROM Products
WHERE Price > 30;
4. SELECT * FROM Products
WHERE Price <= 30;
The SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
The SQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
Page 26 of
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" and "UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:


% - The percent sign represents zero, one, or multiple characters
_ - The underscore represents a single character
LIKE Syntax
SELECT column1, column2, ...
Page 27 of
FROM table_name
WHERE columnN LIKE pattern;
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
LIKE Operator
Description
WHERE CustomerName LIKE 'a%'
Finds any values that starts with "a"
WHERE CustomerName LIKE '%a'
Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%'
Finds any values that have "or" in
any position
WHERE CustomerName LIKE '_r%'
Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%_%'
Finds any values that starts with "a"
and are at least 3 characters in
length
WHERE ContactName LIKE 'a%o'
Finds any values that starts with "a"
and ends with "o"
The following SQL statement selects all customers with a CustomerName ending with "a":
Page 28 of
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
LAB TASK:
Task 01: Perform various operations on the fields on the inserted and saved data.
Task 02: Check output and practice by changing data.
Page 29 of
Week 5
Instructor:
•
M. Rizwan Waseem(Lab)
Learning Objectives:

Understanding of Group functions, Having clause, Column and Table Alias.
Helping Material:
1. AGGREGATE FUNCTIONS:
Aggregate functions allow you to perform a calculation on a set of values to return a single scalar value. The
most common aggregate functions are:

AVG

MIN

SUM

COUNT

STDEV

STDEVP

VAR

VARP

MAX
Note: All the Group function except COUNT ignore null values
2. THE GROUP BY CLAUSE
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
Page 30 of
groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
For example:
SELECT SupplierID, AVG(UnitPrice) FROM Products
GROUP BY SupplierID
3. THE HAVING CLAUSE
The WHERE clause is a row filter, the HAVING clause is a group filter. Only groups for which the HAVING
predicate evaluates to TRUE are returned by the HAVING phase to the next logical query processing phase.
Groups for which the predicate evaluates to FALSE or UNKNOWN are discarded. Because the HAVING clause
is processed after the rows have been grouped, you can refer to aggregate functions in the logical expression.
For example, in the query below, the HAVING clause has the logical expression COUNT(*) > 1, meaning that
the HAVING phase filters only groups (Title) with more than one row. The following fragment of query will
help to retrieve required data:
SELECT Title, COUNT(*)
FROM Employees
GROUP BY Title
HAVING COUNT(*)
>1
4. ALIASING TABLES AND COLUMNS
Aliases provide database administrators, as well as other database users, with the ability to reduce the
amount ofcode required for a query, and to make queries simpler to understand. In addition, aliasing can be
used as an obfuscation technique to protect the real names of database fields.
4.1. ALIASING COLUMNS
SELECT column_name AS alias_name FROM table_name;
4.2. ALIASING TABLES
SELECT column_name(s) FROM table_name AS alias_name;
5. FOOD FOR BRAIN
Here is some extra food for your brain which can help in further assignments:
• YEAR function is used to extract year from a date
• MONTH function is used to extract year from a date
• DAY function is used to extract day from a date.
Page 31 of
Lab Tasks:
 Perform all the group function on Northwind Schema.
 Perform all the group function using HAVING clause on Northwind Schema
 Apply aliasing syntax on arbitrary column on Northwind Schema.
 Bonus: Find an alternate method to alias tables and columns in SQL Server.
Page 32 of
Week 6
Instructor:Ms.Aisha Riaz
Objective(s): Class Task to run queries using various clauses
Task 01: Create a new database “Organization”and specify table “Employee” along with fields as given
Empid
Empname
Gender
Salary
001
Edward
M
30000
002
David
M
50000
005
Jane
F
70000
007
Elizabeth
F
30000
Task 02: Perform given queries and display required output
1. Write a query to display the id and Employee name for those employees whose salary is less than
50000.
2. Write a query to display the Empid for those employees whose name starts with ‘E’ or whose name’s
second letter is ‘a’.
3. Show only the output of those employees displaying the Empname if salary=50000 and gender=‘F’.
4. Write 3 queries of your own that use distinct, group by and having clasuses.
Page 33 of
Task 03:
All the given tasks should be performed in the context of Northwind Schema.
1.
2.
3.
4.
List name of all the products whose price is above average.
Write a query to generate report showing date wise orders shipped.
List name of all countries from where two or more suppliers belong to.
Write a query to generate report showing month wise orders delayed shipped. Your output should
look like this
Month Number
Orders Delayed
1
2
.
.
.
12
75
75
.
.
.
55
5. Report all the orders which have been discounted. Your result should show the total discount
against each order. Output should look like this
OrderID
Discount
10250
0.300000011920929
10251
0.100000001490116
10252
0.100000001490116
.
.
.
.
.
.
6. Write a query to list the number of orders which were shipped in the cities of USA in 1997. Show
thenumber of order against each city.
7. Write a query to generate report showing country wise orders delayed shipped. Your output should
looklike this:
8. Report all the orders which have been discounted with total price of order. Your result should show
thetotal discount against each order. Output should look like this:
Page 34 of
9. Write a query to list the number of orders which were shipped in the cities of each region in 1997.
Showthe number of order against each city. Your results should look like this:
What to Submit:
You are required to submit the following files.


Dbscript.sql
Pdf report.
Page 35 of
Week 7
Instructor:
•
M. Rizwan Waseem (Lab)
Learning Objective(s): Use of Commands to Alter Table, Add or Drop a Column
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
Page 36 of
SQL Server / MS Access:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
SQL ALTER TABLE Example
Look at the "Persons" table:
ID
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10 Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to add a column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons
ADD DateOfBirth date;
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data
type specifies what type of data the column can hold. For a complete reference of all the data
types available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.
Page 37 of
The "Persons" table will now look like this:
ID
LastName
FirstName Address
City
1
Hansen
Ola
Timoteivn Sandnes
10
2
Svendson
Tove
Borgvn 23 Sandnes
3
Pettersen
Kari
Storgt 20
DateOfBirth
Stavanger
Change Data Type Example
Now we want to change the data type of the column named "DateOfBirth" in the "Persons"
table.
We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a twoor four-digit format.
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons
Page 38 of
DROP COLUMN DateOfBirth;
The "Persons" table will now look like this:
ID
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
LAB TASK:
Task 01: Alter the name of your already added field
Task 02: Drop 2 columns
Task 03: Add 1 column and check the output
Page 39 of
Week 9
Instructor:

M. Rizwan Waseem
Objective(s): Use queries Delete Table and a Row, Truncate a Table in SQL.
The SQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name
WHERE condition;
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';
Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that the table structure,
attributes, and indexes will be intact:
DELETE FROM table_name;
or:
DELETE * FROM table_name;
In SQL, the TRUNCATE TABLE statement is a Data Definition Language (DDL) operation that marks the
extents of a table for deallocation (empty for reuse). The result of this operation quickly removes all data from
a table, typically bypassing a number of integrity enforcing mechanisms.
Task 01: Create a new table, add data in it and then apply these queries.
Page 1 of 2
Week 10
Instructor:
•
M. Rizwan Waseem (Lab)
Learning Objectives:

Understanding of JOINS in SQL Server.
Helping Material:
1. JOINS In SQL Server:
A JOIN clause is used to combine rows from two or more tables, based on a related column between
themSQL server provides the following joins:
 Cross Join
 Natural Join
 Equi Join
 Inner Join
 Left Outer Join
 Right Outer Join
 Full Outer Join
2. JOINS SYNTAX:
SELECT ColumnName(s)
FROM Table_1,Table_2
OR
SELECT ColumnName(s)
FROM Table_1 CROSS JOIN Table_2
SELECT column_name(s)
FROM table1 INNER JOIN/ CROSS JOIN/ NATURAL JOIN/ LEFT JOIN/ RIGHT JOIN/ FULL OUTER
JOIN table2
ON table1.column_name = table2.column_name;
Page 2 of 2
Lab Tasks + Home Tasks:
 Perform all JOIN queries on any table using Northwind Schema.


Perform self-cross join and see if there is any difference between cross join and self cross join.
SELECT Customers.custid, Customers.companyname, Orders.orderid, Orders.orderdate
FROM Sales.Customers AS C
INNER JOIN Sales.Orders AS O
ON Customers.custid = Orders.custid;
Advanced Tasks:
 Return customers and their orders, including customers who placed no orders (CustomerID, OrderID,
OrderDate)
 Report only those customer IDs who never placed any order. (CustomerID, OrderID, OrderDate)
 Report those customers who placed orders on July,1997. (CustomerID, OrderID, OrderDate)
 Report the total orders of each customer. (customerID, totalorders)
 Write a query to generate a five copies of each employee. (EmployeeID, FirstName, LastName)
 Write a query that returns a row for each employee and day in the range 04-07-1996 through 04-081997. (EmployeeID, Date)
 Return US customers, and for each customer return the total number of orders and total quantities.
(CustomerID, Totalorders, totalquantity)
 Write a query that returns all customers in the output, but matches them with their respective orders
only if they were placed on July 04,1997. (CustomerID, CompanyName, OrderID, Orderdate)
 Are there any employees who are older than their managers?
 List that names of those employees and their ages. (EmployeeName, Age, Manager Age)
 List the names of products which were ordered on 8th August 1997. (ProductName, OrderDate)
 List the addresses, cities, countries of all orders which were serviced by Anne and were shipped late.
(Address, City, Country)
 List all countries to which beverages have been shipped. (Country)
What to Submit:
You are required to submit the following files.


2020-CS-X.sql (You will replace the value of “X” with you roll number to keep name of file)
Pdf report.
Week 11
Instructor:
•
Ms.Aisha Riaz (Lab)
Learning Objectives:

Understanding of Subqueries.
Helping Material:
1. Subquery:
A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside
another subquery. A subquery can be used anywhere an expression is allowed.
A subquery nested in the outer SELECT statement has the following components:
 A regular SELECT query including the regular select list components.
 A regular FROM clause including one or more table or view names.
 An optional WHERE clause.
 An optional GROUP BY clause.
 An optional HAVING clause.
The SELECT query of a subquery is always enclosed in parentheses. It cannot include a COMPUTE or
FORBROWSE clause, and may only include an ORDER BY clause when a TOP clause is also specified.
A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT, INSERT, UPDATE,
or DELETE statement, or inside another subquery. Up to 32 levels of nesting is possible, although the limit
varies based on available memory and the complexity of other expressions in the query. Individual queries may
not support nesting up to 32 levels. A subquery can appear anywhere an expression can be used, if it returns a
singlevalue.
If a table appears only in a subquery and not in the outer query, then columns from that table cannot be included
in the output (the select list of the outer query).
Statements that include a subquery usually take one of these formats:
 WHERE expression [NOT] IN (subquery)
 WHERE expression comparison_operator [ANY | ALL] (subquery)
 WHERE [NOT] EXISTS (subquery)
In some Transact-SQL statements, the subquery can be evaluated as if it were an independent query.
Conceptually,the subquery results are substituted into the outer query (although this is not necessarily how SQL
Server actuallyprocesses Transact-SQL statements with subqueries). There are three basic types of subqueries.
Those that:



Operate on lists introduced with IN, or those that a comparison operator modified by ANY or ALL.
Are introduced with an unmodified comparison operator and must return a single value.
Are existence tests introduced with EXISTS.
2. Subquery Rules
A subquery is subject to the following restrictions:
 The select list of a subquery introduced with a comparison operator can include only one expression
orcolumn name (except that EXISTS and IN operate on SELECT * or a list, respectively).
 If the WHERE clause of an outer query includes a column name, it must be join-compatible with
thecolumn in the subquery select list.
 The ntext, text, and image data types cannot be used in the select list of subqueries.
 Because they must return a single value, subqueries introduced by an unmodified comparison operator
(one not followed by the keyword ANY or ALL) cannot include GROUP BY and HAVING clauses.
 The DISTINCT keyword cannot be used with subqueries that include GROUP BY.
 The COMPUTE and INTO clauses cannot be specified.
 ORDER BY can only be specified when TOP is also specified.
 A view created by using a subquery cannot be updated.
 The select list of a subquery introduced with EXISTS, by convention, has an asterisk (*) instead of a single
column name. The rules for a subquery introduced with EXISTS are the same as those for a standard
selectlist, because a subquery introduced with EXISTS creates an existence test and returns TRUE or
FALSE, instead of data
3. Subquery Syntax
SELECT column1 , column2 , column3 , ….
FROM table1
WHERE columnN = (SELECT columnM
FROM table2
WHERE
condition)
Lab Tasks + Home Tasks:






Return customers and their orders, including customers who placed no orders (CustomerID,
OrderID,OrderDate)
Report only those customer IDs who never placed any order. (CustomerID, OrderID, OrderDate)
Report those customers who placed orders on July,1997. (CustomerID, OrderID, OrderDate)
Report the total orders of each customer. (customerID, totalorders)
Write a query to generate a five copies of each employee. (EmployeeID, FirstName, LastName)
List all the products whose price is more than average price.

Find the second highest price of product.

Write a query that returns a row for each employee and day in the range 04-07-1996 through 04- 081997. (EmployeeID, Date)
Return US customers, and for each customer return the total number of orders and total quantities.
(CustomerID, Totalorders, totalquantity)






Write a query that returns all customers in the output, but matches them with their respective orders only
if they were placed on July 04,1997. (CustomerID, CompanyName, OrderID, Orderdate) Are there
any employees who are older than their managers?
List that names of those employees and their ages. (EmployeeName, Age, Manager Age)
List the names of products which were ordered on 8th August 1997. (ProductName, OrderDate)
List the addresses, cities, countries of all orders which were serviced by Anne and were shipped
late.(Address, City, Country)
List all countries to which beverages have been shipped. (Country)
What to Submit:
You are required to submit the following files.


2020-CS-X.sql (You will replace the value of “X” with you roll number to keep name of file)
Pdf report.
WEEK 12
Instructor:
 M. Rizwan Waseem
Learning Objective(s): To apply Single Row functions in SQL.
SQL Functions optionally take arguments from the user and mandatorily return a value.
On a broader category, there are two types of functions:Single Row functions - Single row functions are the one who work on single row and return one output per row.
For example, length and case conversion functions are single row functions.
Multiple Row functions - Multiple row functions work upon group of rows and return one result for the complete
set of rows. They are also known as Group Functions.
Single row functions
Single row functions can be character functions, numeric functions, date functions, and conversion functions.
Note that these functions are used to manipulate data items. These functions require one or more input arguments
and operate on each row, thereby returning one output value for each row. Argument can be a column, literal or
an expression. Single row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single
row functions can be 
General functions - Usually contains NULL handling functions. The functions under the category are
NVL, NVL2, NULLIF, COALESCE, CASE, DECODE.

Case Conversion functions - Accepts character input and returns a character value. Functions under the
category are UPPER, LOWER and INITCAP.

o
UPPER function converts a string to upper case.
o
LOWER function converts a string to lower case.
o
INITCAP function converts only the initial alphabets of a string to upper case.
Character functions - Accepts character input and returns number or character value. Functions under
the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE.
o
CONCAT function concatenates two string values.
o
LENGTH function returns the length of the input string.


o
SUBSTR function returns a portion of a string from a given start point to an end point.
o
INSTR function returns numeric position of a character or a string in a given string.
o
LPAD and RPAD functions pad the given string upto a specific length with a given character.
o
TRIM function trims the string input from the start or end.
o
REPLACE function replaces characters from the input string with a given character.
Date functions - Date arithmetic operations return date or numeric values. Functions under the category
are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC.
o
MONTHS_BETWEEN function returns the count of months between the two dates.
o
ADD_MONTHS function add 'n' number of months to an input date.
o
NEXT_DAY function returns the next day of the date specified.
o
LAST_DAY function returns last day of the month of the input date.
o
ROUND and TRUNC functions are used to round and truncates the date value.
Number functions - Accepts numeric input and returns numeric values. Functions under the category are
ROUND, TRUNC, and MOD.
o
ROUND and TRUNC functions are used to round and truncate the number value.
o
MOD is used to return the remainder of the division operation between two numbers.
General functions
The SELECT query below demonstrates the use of NVL function.
SELECT first_name, last_name, salary, NVL (commission_pct,0)
FROM employees
WHERE rownum < 5;
FIRST_NAME
LAST_NAME
Steven
King
Neena
Kochhar
Lex
De Haan
SALARY NVL(COMMISSION_PCT,0)
24000
17000
17000
0
0
0
Alexander
Hunold
9000
0
Case Conversion functions
The SELECT query below demonstrates the use of case conversion functions.
SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)
FROM employees
WHERE rownum < 5;
UPPER(FIRST_NAME)
STEVEN
King
NEENA
Kochhar
LEX
INITCAP(LAST_NAME)
De Haan
ALEXANDER
Hunold
LOWER(JOB_
ad_pres
ad_vp
ad_vp
it_prog
Character functions
The SELECT query below demonstrates the use of CONCAT function to concatenate two string values.
SELECT CONCAT (first_name, last_name)
FROM employees
WHERE rownum < 5;
CONCAT(FIRST_NAME,LAST_NAME)
EllenAbel
SundarAnde
MozheAtkinson
DavidAustin
The SELECT query below demonstrates the use of SUBSTR and INSTR functions. SUBSTR function returns
the portion of input string from 1st position to 5th position. INSTR function returns the numeric position of
character 'a' in the first name.
SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a')
FROM employees
WHERE rownum < 5;
SUBST INSTR(FIRST_NAME,'A')
Ellen
0
Sunda
5
Mozhe
0
David
2
The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print the employee and job
information.
SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')
FROM employees
WHERE rownum < 5;
RPAD(FIRST_NAME,10,'_')||
Steven
AD_PRES
Neena
AD_VP
Lex
AD_VP
Alexander
IT_PROG
Number functions
The SELECT query below demonstrates the use of ROUND and TRUNC functions.
SELECT ROUND (1372.472,1)
FROM dual;
ROUND(1372.472,1)
1372.5
SELECT TRUNC (72183,-2)
FROM dual;
TRUNC(72183,-2)
72100
Date arithmetic operations
The SELECT query below shows a date arithmetic function where difference of employee hire date and sysdate
is done.
SELECT employee_id, (sysdate - hire_date) Employment_days
FROM employees
WHERE rownum < 5;
EMPLOYEE_ID EMPLOYMENT_DAYS
100
3698.61877
101
2871.61877
102
4583.61877
103
2767.61877
Date functions
The SELECT query below demonstrates the use of MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY and
LAST_DAY functions.
SELECT employee_id, MONTHS_BETWEEN (sysdate, hire_date) Employment_months
FROM employees
WHERE rownum < 5;
EMPLOYEE_ID EMPLOYMENT_MONTHS
100
121.504216
101
94.3751837
102
150.633248
103
90.9558289
SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate)
FROM dual;
ADD_MONTH NEXT_DAY( LAST_DAY(
01-JAN-14 05-AUG-13 31-AUG-13
LAB TASK:
Task 01: Perform single row functions as discussed in class and check output.
Week 13
Instructor:
• M. Rizwan Waseem (Lab)
Learning Objectives:

Understanding of Stored Procedure
Helping Material:
A SQL stored procedure (SP) is a collection SQL statements and sql command logic, which is compiled
and stored on the database. Stored procedures in SQL allows us to create SQL queries to be stored and
executed on the server. Stored procedures can also be cached and reused. The main purpose of stored
procedures to hide directSQL queries from the code and improve performance of database operations such
as select, update, and delete data.
 Types of stored procedures
There are two types of stored procedures available in SQL Server:
I.
User defined stored procedures
II.
System stored procedures
 User defined stored procedures
User defined stored procedures are created by database developers or database administrators. These SPs
contains one more SQL statements to select, update, or delete records from database tables. User defined stored
procedure can take input parameters and return output parameters. User defined stored procedure is mixture of
DDL (Data Definition Language) and DML (Data Manipulation Language) commands.
User defined SPs are further classified into two types:
T-SQL stored procedures: T-SQL (Transact SQL) SPs receive and returns parameters. These SPs process the
Insert, Update and Delete queries with or without parameters and return data of rows asoutput. This is one of
the most common ways to write SPs in SQL Server.
CLR stored procedures: CLR (Common Language Runtime) SPs are written in a CLR basedprogramming
language such as C# or VB.NET and are executed by the .NET Framework.
 System stored procedures
System stored procedures are created and executed by SQL Server for the server administrativeactivities.
Developers usually don't interfere with system SPs.
Let's login to our SQL Server database, so we can achieve the following:





How to create a SELECT QUERY based stored procedure which return all records?
How to create a PARAMETER based SELECT QUERY stored procedure which return records based on
parameters?
How to create an INSERT query based stored procedure?
How to create an UPDATE query based stored procedure?
How to create a DELETE query based stored procedure?
Switch to your database. My database name is MBKTest.
Empty stored procedure will be created using the following:
The empty template created by SQL Server for a SP looks like the following. The CREATE PROCEDURE
SQL command is used to create a procedure, followed by a SP name and its parameters.The BEGIN and
END area is used to define the query for the operation. This is where you will write a select, update, insert,
or delete queries.
1. -- ================================================
2. -- Template generated from Template Explorer using:
3. -- Create Procedure (New Menu).SQL
4. -5. -- Use the Specify Values for Template Parameters
6. -- command (Ctrl-Shift-M) to fill in the parameter
7. -- values below.
8. -9. -- This block of comments will not be included in
10. -- the definition of the procedure.
11. -- ================================================
12. SET ANSI_NULLS ON
13. GO
14. SET QUOTED_IDENTIFIER ON
15. GO
16. -- =============================================
17. -- Author:
<Author,,Name>
18. -- Create date: <Create Date,,>
19. -- Description: <Description,,>
20. -- =============================================
21. CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
22. -- Add the parameters for the stored procedure here
Database system Lab
Department of Computer Science
25. AS
26. BEGIN
27. -- SET NOCOUNT ON added to prevent extra result sets from
28. -- interfering with SELECT statements.
29. SET NOCOUNT ON;
30.
31. -- Insert statements for procedure here
32. SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
33. END
34. GO
What is the naming convention for stored procedures?
We must follow standard naming conventions which may also depend on your project and coding policies.
For user defined stored procedure naming conventions, my suggestions are to add one of the following prefixes
to your SP names.
1.
2.
3.
4.
5.
sp
stp
stp_
udstp
udstp_
Naming conventions are just to identify objects. By adding these prefixes in the name, we can clearly identify
that this object is a stored procedure.
Create a database table
Before, we can create and execute any SPs, we need a database table. I create a database table named,
“tblMembers” using the following SQL query and execute it on the server. As you can see, my table has 4
column where the first column is an idenity column. Once the table is created, open table in your SSMS and add
some data by manually entering data to the table.
1. USE [MBKTest]
2. GO
3.
4. /****** Object: Table [dbo].[tblMembers]
5. SET ANSI_NULLS ON
6. GO
7.
8. SET QUOTED_IDENTIFIER ON
9. GO
10.
11. SET ANSI_PADDING ON
12. GO
13.
Script Date: 18-Nov-17,Sat 6:47:55 PM ******/
Database system Lab
Department of Computer Science
14. CREATE TABLE [dbo].[tblMembers](
15. [MemberID] [int] IDENTITY(1,1) NOT NULL,
16. [MemberName] [varchar](50) NULL,
17. [MemberCity] [varchar](25) NULL,
18. [MemberPhone] [varchar](15) NULL
19. )
20.
21. GO
22.
23. SET ANSI_PADDING OFF
24. GO
How to create a SELECT stored procedure?
Click on your Database and expand “Programmability” item and right click on “Stored Procedures” or press
CTRL + N to get new query window. In the query area between BEGIN and END, type your SELECT
statement to select records from the table. See the Select statement in the below code.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author:
Manoj Kalla
7. -- Create date: 18th Nov 2017
8. -- Description: Return all members
9. -- =============================================
10. --Store procedure name is --> stpGetAllMembers
11. CREATE PROCEDURE stpGetAllMembers
12. AS
13. BEGIN
14. -- SET NOCOUNT ON added to prevent extra result sets from
15. -- interfering with SELECT statements.
16. SET NOCOUNT ON;
17.
18. -- Select statements for procedure here
19. Select * from tblMembers
20. END
21. GO
Now, press F5 or click on Execute button to execute the SP.
Database system Lab
Department of Computer Science
You should see a message, “Command(s) completed successfully.”
Now go to Programmability -->Stored Procedures, Right Click and select Refresh.
You can see in the following image, the new SP called stpGetAllMembers is created.
Database system Lab
Department of Computer Science
Execute stored procedures in SQL Server
In below UI, right click on the SP name and select Execute Stored Procedure... to execute a SP. From here, you
can also modify an existing SP.
Alternatively, you can also execute a SP from the Query window.
To run stored procedure in SQL Server Management Studio, switch to Query window or CTRL +N to open an
new query window and type the following command.


Syntax - EXEC <stored procedure name>
Example - EXEC stpGetAllMembers
Now, we run our stored procedure called stpGetAllMembers. The output looks like the following:
Database system Lab
Department of Computer Science
OUTPUT
What are parameters in stored procedures?
Parameters in SPs are used to pass input values and return output values. There are two types of parameters:
1. Input parameters - Pass values to a stored procedure.
2. Output parameters - Return values from a stored procedure.
How to create a SELECT query SP with parameters?
Database system Lab
Department of Computer Science
In the previous steps, we created a simple SP that returned all rows from a table. Now, let's create a new SP that
will take a city name as an inpurt parameter and will return all rows where city name matches the input
parameter value.
Here is the updated SP with a parameter @CityName.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author:
Manoj Kalla
7. -- Create date: 20-Nov-2017
8. -- Description: Return specifc city records
9. -- =============================================
10. CREATE PROCEDURE stpGetMembersByCityName
11. -- Add the parameters for the stored procedure here
12. @CityName nvarchar(30)
13.
14. AS
15. BEGIN
16. -- SET NOCOUNT ON added to prevent extra result sets from
17. -- interfering with SELECT statements.
18. SET NOCOUNT ON;
19.
20. Select * From tblMembers
21. where MemberCity like '%'+@CityName+'%'
22.
23. END
24. GO
Execute it.
To run this SP, type the following command in SQL query tool:
EXEC GetMemberByCityName @CityName = 'mal'
OR from the UI, run the SP and provide the following input.
Database system Lab
Department of Computer Science
The code to execute looks like the following:
1. USE [MBKTest]
2. GO
3.
4. DECLARE @return_value int
6. EXEC @return_value = [dbo].[GetMemberByCityName]
7.
@CityName = N'mal'
8.
9. SELECT 'Return Value' = @return_value
10.
OUTPUT
Database system Lab
Department of Computer Science
How to create a INSERT query based stored procedure?
We can use an INSERT INTO SQL query to insert data into a table. The following SQL statement creates an
INSERT SP with three parameters.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author:
Manoj Kalla
7. -- Create date: 20-Nov-2047
8. -- Description: To create a new member
9. -- =============================================
10. CREATE PROCEDURE stpInsertMember
11. @MemberName varchar(50),
12. @MemberCity varchar(25),
13. @MemberPhone varchar(15)
14.
15. AS
16. BEGIN
17. -- SET NOCOUNT ON added to prevent extra result sets from
18. -- interfering with SELECT statements.
19. SET NOCOUNT ON;
20.
21. Insert into tblMembers (MemberName,MemberCity,MemberPhone)
22.
Values (@MemberName,@MemberCity, @MemberPhone)
23.
24. END
25. GO
Right click on stored procedure in Object Explorer and select Refresh.
Database system Lab
Department of Computer Science
Pass the value of parameter in Execute dialog box. Something like this:
Database system Lab
Department of Computer Science
The following code can be used to execute this SP in SSMS.
1. USE [MBKTest]
2. GO
3.
4. DECLARE @return_value int
6. EXEC @return_value = [dbo].[stpInsertMember]
7.
@MemberName = N'Mahesh Chand',
8.
@MemberCity = N'NewYork',
9.
@MemberPhone = N'9999945121'
10. SELECT 'Return Value' = @return_value
11. GO
OUTPUT
Database system Lab
Department of Computer Science
In the query window, you can check if a new record for Member Name 'Mahesh Chand' is added to the table.
You can also run the same SP in code.
EXEC stpInsertMember @MemberName = 'Suhana & Ashish Kalla ', @MemberCity = 'Mumbai ',
@MemberPhone = N'9022592774xxx'
OUTPUT
You can check “Suhana & Ashish Kalla” record is added successfully.
Database system Lab
Department of Computer Science
How to create an UPDATE quert based stored procedure?
Let's create a new SP that will update a table records based on the Member ID column. The ID is passed as an
input parameter. Here is the new SP that uses an UPDATE..SET..WHERE command.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author:
Manoj Kalla
7. -- Create date: 20-Nov-2017
8. -- Description: Update a member detail by ID
9. -- =============================================
10. CREATE PROCEDURE stpUpdateMemberByID
11. @MemberID int,
12. @MemberName varchar(50),
13. @MemberCity varchar(25),
14. @MemberPhone varchar(15)15.
16. AS
17. BEGIN
18. -- SET NOCOUNT ON added to prevent extra result sets from
19. -- interfering with SELECT statements.
20. SET NOCOUNT ON;21.
22. UPDATE tblMembers
23. Set MemberName = @MemberName,
Database system Lab
Department of Computer Science
24.
MemberCity = @MemberCity,
25.
MemberPhone = @MemberPhone
26. Where MemberID = @MemberID
27. END
28. GO
Right click on stored procedure in the Object Explorer and select Refresh. You will see the SP is created.
Now, Right click on SP name and select Execute stored procedure…. Provide the input values and execute.
We can use the following command in SSMS.
1. USE [MBKTest]
Database system Lab
Department of Computer Science
2. GO
3.
4. DECLARE @return_value int
5.
6. EXEC @return_value = [dbo].[stpUpdateMemberByID]
7.
@MemberID = 20,
8.
@MemberName = N'Nirupama Kalla',
9.
@MemberCity = N'Mumbai',
10.
@MemberPhone = N'904512541xxxx'
11.
12. SELECT 'Return Value' = @return_value
13.
14. GO
EXEC stpUpdateMemberByID 17,'Gopal Madhavrai','Bikaner','90454564xxx'
The results should show you the updated values.
How to create a DELETE query based stored procedure?
Let's create a SP that will delete records. The new SP uses a DELETE command and delete all records that
matches provided Member ID.
1.
2.
3.
4.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Database system Lab
Department of Computer Science
5. -- =============================================
6. -- Author:
Manoj Kalla
7. -- Create date: 21-Nov-2017
8. -- Description: Delete a Member by Member ID
9. -- =============================================
10. CREATE PROCEDURE stpDeleteMemberByMemberID
11. @MemberID int
12. AS
13. BEGIN
14. -- SET NOCOUNT ON added to prevent extra result sets from
15. -- interfering with SELECT statements.
16. SET NOCOUNT ON;
17.
18. Delete from tblMembers
19. where MemberId = @MemberID
20.
21. END
22. GO
Execute it.
Right click on Stored Procedures in the Object Explorer and select Refresh.
RUN stored procedure BY UI
Now again right click on stored procedure and select Execute stored procedure…
As you can see in the image, I passed @MemberID parameter value = 4.
Database system Lab
Department of Computer Science
RUN DELETE stored procedure BY MANUALLY (CODING)
EXEC stpDeleteMemberByMemberID 2
OUTPUT
You can see in image MemberID = 4 record has been deleted successfully.
Database system Lab
Department of Computer Science
In this article, we saw how to create stored procedures in a SQL Server database for inserting, updating,
anddeleting records.
Modifying the stored procedure
ALTER PROCEDURE GetProductDescAS
SELECT P.ProductID,P.ProductName,PD.ProductDescription FROMProduct
P
INNER JOIN ProductDescription PD ON P.ProductID=PD.ProductIDEND
Renaming the stored procedure
sp_rename 'GetProductDesc','GetProductDesc_new'
SQL Dropping a stored
procedure DROP PROCEDURE
procedure_name;
What to Submit:
You are required to submit the following files.

Run all the things in any table of Northwind database and create a pdf file similar like this.
Database system Lab
Department of Computer Science
Week 14
Instructor:
• M. Rizwan Waseem (Lab)
Learning Objectives:

Understanding of Triggers
A Trigger in Structured Query Language is a set of procedural statements which are executed automatically when
there is any response to certain events on the particular table in the database. Triggers are used to protect the
data integrity in the database.
In SQL, this concept is the same as the trigger in real life. For example, when we pull the gun trigger, the bullet
is fired.
The trigger is always executed with the specific table in the database. If we remove the table, all the triggers
associated with that table are also deleted automatically.
In Structured Query Language, triggers are called only either before or after the below events:
1. INSERT Event: This event is called when the new row is entered in the table.
2. UPDATE Event: This event is called when the existing record is changed or modified in the table.
3. DELETE Event: This event is called when the existing record is removed from the table.
Types of Triggers in SQL
Following are the six types of triggers in SQL:
1. AFTER INSERT Trigger
This trigger is invoked after the insertion of data in the table.
2. AFTER UPDATE Trigger
This trigger is invoked in SQL after the modification of the data in the table.
3. AFTER DELETE Trigger
This trigger is invoked after deleting the data from the table.
4. BEFORE INSERT Trigger
This trigger is invoked before the inserting the record in the table.
5. BEFORE UPDATE Trigger
This trigger is invoked before the updating the record in the table.
Database system Lab
Department of Computer Science
6. BEFORE DELETE Trigger
This trigger is invoked before deleting the record from the table.
Syntax of Trigger in SQL
CREATE TRIGGER Trigger_Name
[ BEFORE | AFTER ] [ Insert | Update | Delete]
ON [Table_Name]
[ FOR EACH ROW | FOR EACH COLUMN ]
AS
Set of SQL Statement
In the trigger syntax, firstly, we have to define the name of the trigger after the CREATE TRIGGER keyword. After
that, we have to define the BEFORE or AFTER keyword with anyone event.
Then, we define the name of that table on which trigger is to occur.
After the table name, we have to define the row-level or statement-level trigger
Example of Trigger in SQL
To understand the concept of trigger in SQL, first, we have to create the table on which trigger is to be executed.
The following query creates the Student_Trigger table in the SQL database:
CREATE TABLE Student_Trigger
(
Student_RollNo INT NOT NULL PRIMARY KEY,
Student_FirstName Varchar (100),
Student_EnglishMarks INT,
Student_PhysicsMarks INT,
Student_ChemistryMarks INT,
Student_MathsMarks INT,
Student_TotalMarks INT,
Database system Lab
Department of Computer Science
Student_Percentage );
The following query fires a trigger before the insertion of the student record in the table:
CREATE TRIGGER Student_Table_Marks
BEFORE INSERT
ON
Student_Trigger
FOR EACH ROW
SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_PhysicsMarks + new.Student_Chemist
ryMarks + new.Student_MathsMarks,
new.Student_Percentage = ( new.Student_TotalMarks / 400) * 100;
The following query inserts the record into Student_Trigger table:
INSERT INTO Student_Trigger (Student_RollNo, Student_FirstName, Student_EnglishMarks, Student_PhysicsMar
ks, Student_ChemistryMarks, Student_MathsMarks, Student_TotalMarks, Student_Percentage)
VALUES ( 201, Sorya, 88, 75, 69, 92, 0, 0);
To check the output of the above INSERT statement, you have to type the following SELECT statement:
1. SELECT * FROM Student_Trigger;
Output:
Student
_RollNo
Student_
FirstNam
e
Student_En
glishMarks
Student
_Physic
sMarks
Student_
chemistry
Marks
Student_Maths
Marks
Student
_Total
Marks
Student_P
ercentage
201
Sorya
88
75
69
92
324
81
Database system Lab
Department of Computer Science
Advantages of Triggers in SQL
Following are the three main advantages of triggers in Structured Query Language:
1. SQL provides an alternate way for maintaining the data and referential integrity in the tables.
2. Triggers helps in executing the scheduled tasks because they are called automatically.
3. They catch the errors in the database layer of various businesses.
4. They allow the database users to validate values before inserting and updating.
Disadvantages of Triggers in SQL
Following are the main disadvantages of triggers in Structured Query Language:
1. They are not compiled.
2. It is not possible to find and debug the errors in triggers.
3. If we use the complex code in the trigger, it makes the application run slower.
4. Trigger increases the high load on the database system
LAB TASK :
Practice Triggers on the data stored in your table.
Database system Lab
Department of Computer Science
Week 15
Instructor:

M. Rizwan Waseem
Learning Objective(s): To understand views and its types in SQL.
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were
coming from one single table.
CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SQL CREATE VIEW Examples
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued) from the "Products"
table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID, ProductName
FROM Products
WHERE Discontinued = No;
Then, we can query the view as follows:
SELECT * FROM [Current Product List];
Another view in the Northwind sample database selects every product in the "Products" table with a unit price
higher than the average unit price:
Database system Lab
Department of Computer Science
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, UnitPrice
FROM Products
WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products);
We can query the view above as follows:
SELECT * FROM [Products Above Average Price];
Another view in the Northwind database calculates the total sale for each category in 1997. Note that this view
selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName, Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName;
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997];
We can also add a condition to the query. Let's see the total sale only for the category "Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName = 'Beverages';
SQL Updating a View
You can update a view by using the following syntax:
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Now we want to add the "Category" column to the "Current Product List" view. We will update the view with the
following SQL:
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;
Database system Lab
Department of Computer Science
SQL Dropping a View
You can delete a view with the DROP VIEW command.
SQL DROP VIEW Syntax
DROP VIEW view_name;
LAB TASK:
Task 01: Practice views on the data stored in your table.
Week 16:
Instructor:

M. Rizwan Waseem
Learning Objectives:
•
CRUD operations using C# language with SQL server
Helping Material:
SQL CRUD Operations Queries Syntax

Insert Data into Table:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Update Data into Table:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Retrieve Data from Table:
SELECT column1, column2, ...
FROM table_name;

Delete Data from a Table:
DELETE FROM table_name WHERE condition;
Connection of SQL using C#
C# code to insert data in a table while clicking on a button is given below.
var con = Configuration.getInstance().getConnection();
SqlCommand cmd = new SqlCommand("Insert into Table_1 values (@ID, @Name,
@Department)", con);
cmd.Parameters.AddWithValue("@ID", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("@Name", textBox2.Text);
cmd.Parameters.AddWithValue("@Department", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
C# code to show data in a grid is given below.
var con = Configuration.getInstance().getConnection();
SqlCommand cmd = new SqlCommand("Select * from Table_1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
Lab Tasks
1. Create a new database named Lab2
2. Create table with following schema
Student(RegistrationNumber:String, Name:String , Department:String , Session:Number,
CGPA:Number, Address:String)
3. Use the student table to create the following CRUD operations
a. Add a Student
b. Edit Student
c. List of Students
d. Search Student
e. Delete Student
4. UI components for the fields should be appropriate. Change the Edit Use case to optimize such that all the
fields should not be updated in table, you need to detect, which field has been changed on frontend, then
update only those fields which have been changed. E.g. for editing of student, we change registration
number, then database should only update only registration number.
Download