0% found this document useful (0 votes)
139 views87 pages

Dms Lab Manual Updated

1. The document discusses SQL (Structured Query Language) which is used to create, update and query relational databases. 2. It describes the basic syntax of SQL statements including SELECT statements to retrieve data, INSERT/UPDATE/DELETE statements to manipulate data, and CREATE/ALTER/DROP statements to define database objects. 3. Examples are provided of basic SELECT statements showing how to select all columns, specific columns, use column aliases, join columns, and perform calculations in the SELECT clause. The WHERE clause is also introduced to filter retrieved data.

Uploaded by

Muhammad Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views87 pages

Dms Lab Manual Updated

1. The document discusses SQL (Structured Query Language) which is used to create, update and query relational databases. 2. It describes the basic syntax of SQL statements including SELECT statements to retrieve data, INSERT/UPDATE/DELETE statements to manipulate data, and CREATE/ALTER/DROP statements to define database objects. 3. Examples are provided of basic SELECT statements showing how to select all columns, specific columns, use column aliases, join columns, and perform calculations in the SELECT clause. The WHERE clause is also introduced to filter retrieved data.

Uploaded by

Muhammad Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

DBMS

LAB # 1

OBJECTIVE
Explore SQL Server Management Studio 2012

THEORY
A database (db) is an organized collection of data, typically stored in electronic
format. It allows you to input, organize, and retrieve data quickly. Traditional
databases are organized by fields, records, and files. To better understand what a
database is, consider the telephone book as a simple example.

If you had the telephone book stored on disk, the book would be the file. Within the
telephone book, you would have a list of records each of which contains a name,
address, and telephone number. These single pieces of information (name, address,
phone number) would each constitute a separate field.

Because a database can store thousands of records, it would be a chore if you had to
open a table and go through each record one at a time until you found the record you
needed. Of course, the process would be even more difficult if you had to retrieve
multiple records.

Thankfully, you don’t have to go through database records in this way. Rather, to
retrieve data within a database, you run a database query, which is an inquiry into the
database that returns information back from the database. In other words, a query is
used to ask for information from a database.

Databases are often found on database servers so that they can be accessed by
multiple users and provide a high level of performance. One popular database server
is Microsoft SQL Server. Database servers like SQL Server do not actually house
graphical programs, word-processing applications, or any other type of applications.
Instead, these servers are entirely optimized to serve only the purposes of the database
itself, usually using advanced hardware that can handle the high processing needs of
the database. It is also important to note that these servers do not act as workstations;
they generally are mounted on racks located in a central data center and can be
accessed only through an administrator’s desktop system.

Creating Database by SQL SERVER Management Studio

Select Start-->All Programs-->Microsoft SQL Server-->SQL SERVER Management


Studio

CE301: Database Management Systems 1


DBMS

CREATE A DATABASE USING SSMS

The following steps demonstrate how to create a database in SQL Server 2012 using
SQL Server Management Studio.

1. From the Object Explorer, right click on the Databases folder/icon and select
New database...:

O
Name your database (I called mine TaskTracker) andK click :

CE301: Database Management Systems 2


DBMS

Your New Database


Your new database will appear under the Databases section of the Object Explorer
(just under the System Databases folder). Here's mine:

CE301: Database Management Systems 3


DBMS

CREATE A TABLE USING SSMS

Before you begin, be sure to launch SQL Server Management Studio. Make sure
you’ve expanded the particular database in which you wish to create the new table,
then follow these steps:

Step1 . Right-click the Table folder and select New Table, as shown in Figure 1-1:

Figure 1-1 Creating a new table

Step 2. Use the information shown in Figure 1-2 to complete the details for Column
Name, Data Type, and Length, as specified in the parentheses and Allow Nulls
columns.

CE301: Database Management Systems 4


DBMS

Figure 1-2 Column names and identifying informatio


Step 3. Set the Default Value of the DateCreated column to (getdate()); this will insert
the current date within each new record for that specific field. See Figure 1-3.

Figure 1-3 Setting the Table Designer properties

Step 4. Save your new table by selecting File > Save Table_1, as shown in Figure 1-4.

CE301: Database Management Systems 5


DBMS

Figure 1-4 Saving the new table


Step 5. Type the new name of the table you are saving, as shown in Figure 1-5.

Figure 1-5 Naming the table

Your new table will appear under the Tables section, as depicted in Figure 1-6.

CE301: Database Management Systems 6


DBMS

Figure 1-6 The newly created


table

ADDING DATA

We can use the Edit Top 200 Rows option to manually type data directly into the table
rows.
Manually entering data is OK if you only have a little bit of data to enter. But it's a bit
clunky and can impractical if you have a lot of data. Plus it doesn't really suit most
business needs, where non-technical users need to be able to update the database.
In any case, here's how to manually enter data directly into the table:
1. In the Object Explorer, right click on the table you wish to open, and select
Edit Top 200 Rows:

CE301: Database Management Systems 7


DBMS

You can now start entering the data directly into your table.

LAB TASK
1. Create below tables

LAB # 2

CE301: Database Management Systems 8


DBMS

OBJECTIVE
Apply Data Retrieval Operations in SQL

THEORY
Introduction to SQL

SQL (Structured Query Language) is the standard language used for creating,
updating and querying relational databases. It is supported by all modern database
management systems (e.g. Oracle, IBM DB2, Microsoft Access, Microsoft SQL
Server, PostgreeSQL, MySQL, etc.).

SQL is a declarative language (as opposed to a procedural language like C, Perl, etc.).
This means that the language is used by the programmer to directly describe what end
result is required (e.g. what data is required from a query operation), as opposed to
explicitly describing all the steps required to retrieve the required data from storage).
Thus, SQL is high-level, quite easy to learn, allowing complex tasks on a database to
be specified simply.

SQL has a defined syntax that specifies how standard keywords can be combined to
form valid SQL statements. SQL statements can be divided into three categories,
according to their function:
1. Data Manipulation: Statements that retrieve, insert, update, edit or delete
data stored in database tables. These statements begin with the keywords: SELECT,
INSERT, UPDATE or DELETE.

2. Data Definition: Statements that create, modify, or destroy database objects


(such as tables). These statements begin with the keywords: CREATE, ALTER or
DROP.

3. Data Control: Statements that authorise certain users to view, change or


delete data. These statements begin with the keywords: GRANT or REVOKE. We do
not consider data control in the lab exercises.

Using SELECT Statement:


The SELECT statement retrieves rows and columns from one or more tables and
presents data in the result set i.e. output of SELECT statement in a grid.
1. Choose All Columns or Fields
The asterisk (*) sign is used for retrieving all columns from a table.

SYNTAX
SELECT * FROM table_name Examples:
select * from bonus select
* from employee select *

CE301: Database Management Systems 9


DBMS

from department select *


from salary

2. Choose Selected Columns or Fields


For selecting specific columns, we mention the columns by listing their names.
SYNTAX:
SELECT column1, column2, … FROM table_name Examples:

1. SELECT ename, job, sal FROM Employee


2. SELECT dno, dname from department

3. Using the Column Alias with the AS Clause

SELECT DName AS 'Department Name' FROM Department

We have use AS clause to as the heading of ‘Department Name’ instead of Dname


from the Department table as shown below.

4. Joining Constant Characters in the SQL Statement

Join column Emp_Name and Emp_Job column of Employee table having the
same data type by this query:

SELECT EName + ' does the work of ' + Job AS


'Employee Work' FROM Employee

This will work only for the columns of the same data type; otherwise SQL Server
will generate an error as shown below:
SELECT ENo + ' is the employee number of ' + EName AS EMP FROM
Employee

5. Computing Values in SELECT Statements

To obtain an increase of 25 percent in the salary of employees in the employees


table can be calculated like this:

CE301: Database Management Systems 10


DBMS

SELECT ENo, EName, Job, Sal AS 'Previous Salary', Sal * 0.25 AS increment,
Sal + Sal * 0.25 AS 'Current Salary' FROM Employee

Single quote ‘ ‘ is used in the second AS-Clause because it contains space


between two words, otherwise it is not necessary.

6. Using WHERE-Clause in SELECT statement


You can restrict the rows returned from the query by using the WHERE clause. A
WHERE-clause has a condition that must be true and should directly follow from the
FROM clause.

SYNTAX:
SELECT column_name FROM table_name WHERE condition(s)

Comparison operators are used in conditions that compare one expression to another.
Following is a list of comparison operators:
OPERATOR MEANING
= Equal to
> Greater than
>= Greater than or equal
to
< Less than
<= Less than or equal to
<> Not equal to
! Not

Using the Comparison Operators


Type in the following query in the Editor Pane using a comparison operator in the
condition of WHERE clause.

a. select * from employee where sal>18000

b. select * from employee where eno=525

c. select * from employee where ename='Jamil'

Following point must be kept in mind when using the WHERE clause:

o Character strings and dates are enclosed in single quotation


marks.
o Character values are not case sensitive and date values are
format sensitive.

CE301: Database Management Systems 11


DBMS

o The default date format is MM/DD/YYYY

7. Limiting Records By WHERE Clause

Using the WHERE clause, following query will retrieve details of all those employees
whose Emp_head number is 125:

SELECT * FROM Employee WHERE Head = 125

Try these as well:

select * from employee where hiredate='1991-09-06' or


select * from employee where hiredate='9/6/1991'

8. Using DISTINCT keyword

Using DISTINCT keyword with our query, repeating records can be eliminated.

Type in the following query in the Editor Pane.

SELECT Head FROM Employee

Head column from the Employee table will be retrieved and as used here without
DISTINCT keyword, all records will be displayed.

Now edit the same query with the DISTINCT keyword.

SELECT distinct Head FROM Employee

Repeating records will be eliminated.

9. Using TOP-Clause
The TOP-Clause limits the rows retrieved from the query result.

SYNTAX:

SELECT TOP (n) column_name_list FROM table_name


10. Limiting Records by Using ‘TOP’ and ‘PERCENT’ In
SELECT Statement
The following query will retrieve first five rows from the employee table using the
TOP-clause:

CE301: Database Management Systems 12


DBMS

SELECT TOP 5 * FROM Employee

Asterisk (*) sign again provides all the columns of the table, and column names
can be provided to restrict the number of columns retrieved as:

SELECT TOP 5 eno,ename FROM Employee

Similarly a percent of records can be retrieved from a table. For example

SELECT TO P 60 PERCENT * FROM Salary

LAB TASK:
1. Create a database as mentioned in lab 01 and enter atleast 15
records.
2. Find all the employees whose salaries are greater than 20000.
3. Select TOP 6 rows from department table.
4. Select all different values from designation column in employee
table.
5. Find all employees whose salaries are less than 30000 and jobs are
manager or salesman.

LAB # 3

OBJECTIVE
Apply Comparison and logical operators in SQL

THEORY

CE301: Database Management Systems 13


DBMS

1. The BETWEEN Operator


You can retrieve rows in a range of values by using this operator. The range of values
should contain a lower and an upper range.

select * from employee where sal between 10000 and 15000

Salary of employees ranging from 10000 to 15000 is shown in the results pane.

Find all the employees whose salaries are between 15000 to 50000.

2. The IN Operator
To check for values in a specific list or column, we use the IN operator.

select * from employee where ename in ('Mukaram')

You should try the following query and observe the result:

select * from employee where emp_name in ('Mukaram', 'Jamil')

select * from employee where emp_commission is null

select * from employee where emp_head in(525,125,231)

3. Using the LIKE operator


When not knowing the exact value to search for, then you should use the LIKE
operator to match a character pattern. The character pattern matching operation is
termed as wildcard search. Following is a list of possible wildcard searches:

WILDCARD DESCRIPTION
_ Represents single character.
% Represents a string of any length.
Represents a single character within the range
[]
enclosed in brackets.
Represents any single character not within the range
[^]
enclosed in the brackets.

The following query list the name(s) of those employees in the employee table whose
names start with the letter „B‟.

select ename from employee where ename like 'b%'

CE301: Database Management Systems 14


DBMS

Run these queries using the wildcards:

select * from employee where ename like '%al%'


select * from employee where ename like '_a%'
select * from employee where ename like 'a%' select
* from employee where ename like 'ar[s]%' select *
from employee where ename like 'a_e_l' select *
from employee where ename like 'a[e-z]%' select *
from employee where ename like 'a[^r-z]%'

The LIKE operator can be used as a shortcut for some BETWEEN comparisons.
Following is an example displaying the names and hire dates of employees
January 1997 to December 1997.

select * from employee where hiredate like '%97%'

4. Using the IS NULL operator


The IS NULL operator looks for values that are null. A null value means that the
value is unavailable, unassigned, unknown, or inapplicable. That is why we do not
use (=) sign when testing with the IS NULL operator, because a null value cannot be
equal or unequal to any value.
For example if you want to know the detail of those employees whose head is null,
then use the following SQL statement:

select * from employee where head is null

Test this yourself :


select ename,head,sal,comm from employee where comm is null

Logical operators
A logical operator combines the result of two component conditions to produce a
single result based on them or to invert the result of a single condition. The logical
operators are AND, OR, and NOT. AND and OR are used to connect search
conditions in WHERE clauses. NOT negates the search condition. The following table
shows a summary of these operators.

OPERATOR MEANING
AND Returns TRUE if both or all conditions are
true

CE301: Database Management Systems 15


DBMS

OR Returns TRUE if any of the component


conditions is true
NOT Returns TRUE if the following condition
is false

5. Using the NOT operator


The query showing the details of those employees whose employee number is not
greater than or equal to 200.

select * from employee where not eno>=200

In the following example the AND operator joins two conditions (not
ename='Karim') and (not ename='Jamil')and returns TRUE only when both
conditions are true. The query showing the result of employees number, their names,
and salary whereas whose names are not Karim and Jamil.

Run these queries yourself:

select ename, job, sal from employee where


job not in ('Manager','clerk','assistant')

select ename, job, sal from employee where ename not like 'j%'

6. Using the AND operator

Type the following query. It will show a department information such that
department name is sales and located in Lahore.

select * from department where dname='sales' and dept_location='lahore'

Run this query yourself:

select * from employee where(comm IS NULL and dno=10)

7. Using the OR operator

OR operator connects two conditions, but returns TRUE for any of the condition
being true.

Type the following query. It shows information from department table where
department number is either 10 or 20.

select * from department where dno=10 or dno=20

CE301: Database Management Systems 16


DBMS

RULES OF PRECEDENCE
We can use a mix of logical operators within a single SELECT statement. Following
are the rules:

ORDER OPERATOR
EVALUATED
1 All comparison
operators
2 NOT
3 AND
4 OR

You can override rules of precedence by using parentheses.


Consider the following example:

select * from employee


where eno>=500 or eno<=150 and ename like 'j%'

In this statement first the last two conditions are tested for the AND operator as shown
in the shaded region above then its result is compared to the OR operator i.e. “select
those employees whose names start with the letter ‘J’ and whose employee number is
smaller than or equal to 150 or if the employee number is greater than or equal to
500”.

Test the query yourself:

Using Parentheses to force priority


Now consider the same example with a change by using parentheses.

select * from employee


where (eno>=500 o eno<=150) and ename like 'j%'

Now the precedence will shift from the AND operator to the parentheses (shaded
region).
Second line will be evaluated first, and third line will be evaluated second i.e. “select
employees whose employee number is greater than or equal 500 or less than or equal
to 150 and if the employee name starts with the letter ‘J’.

CE301: Database Management Systems 17


DBMS

LAB # 4
OBJECTIVE
Apply creating and altering tables commands in SQL

THEORY
Creating a Table
When you started this section, you looked at the standard CREATE syntax of:

CREATE <object type> <object name>

And then you moved on to a more specific start (indeed, it’s the first line of the
statement that creates the table) and created a table called Customers:

CE301: Database Management Systems 18


DBMS

SQL PRIMARY KEY Constraint on CREATE TABLE

CREATE TABLE Persons (
    P_ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT PK_Person PRIMARY KEY (P_ID)
);
To DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons DROP CONSTRAINT PK_Person 

SQL FOREIGN KEY Constraint on CREATE TABLE

CREATE TABLE Orders


(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

To DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders

Adding Data with the INSERT Statement


We can add a new record or row into a table by using the INSERT statement.

SYNTAX
INSERT [INTO] <table> [(column_list)]
VALUES (data_values)
Where:
Table is the name of the table
Column is the name of the column in the table to populate
Value is the corresponding value for the column

CE301: Database Management Systems 19


DBMS

INTO is optional and columns list is also optional and may be omitted if you list
values in the default order of the columns in the table.

1. Type the following query.

insert into department(dno, dname,dloc) values


(50,'Development','Karachi')

This result could also have been achieved by using this query if the column order
is default:

insert into department values (50,'Development','Karachi')

INSERTING NULL VALUES IN ROWS

Implicit Method: Omit the Column Name From the Column List

insert into department(dno,dname) values(60,'MIS')

Explicit Method: Specify the NULL keyword or empty string (‘ ‘) in the values
list.

insert into department values(70,'Finance',NULL)

INSERTING SPECIAL VALUES USING SQL FUNCTIONS


Considering the following query:

insert into employee(eno,ename,job,head,hiredate,sal,comm,dno)


values(601,'Shahnawaz','Salesman',125,GETDATE(),20000,1500,10)

Here an employee names Shahnawaz has been added to the employee table, it uses
the GETDATE() function for current date and time. To confirm the addition of
new employee data into the employee’s table, type this query into SSMS:

select * from employee where eno=601

CE301: Database Management Systems 20


DBMS

INSERTING SPECIFIC DATE VALUES


To insert a row or record with some specific date, consider the following query:

insert into employee(eno,ename,job,head,hiredate,sal,comm,dno)


values(602,'Iqbal','Salesman',125,'02/11/2009',20000,2500,10)

Verify your insertion by using SELECT statement.

INSERTING VALUES BY USING SUBSTITUTION VARIABLE


You can also declare and set different variables in a T-SQL which can be passed to an
INSERT statement. Consider the following example.
DECLARE @dept_number int
set @dept_number=90
DECLARE @dept_name nvarchar(50)
set @dept_name='Training'
DECLARE @dept_location nvarchar(50)
set @dept_location='Karachi'

Here we have declared three variables @dept_number, @dept_name, and


@dept_location with data types as int, nvarchar (50) and nvarchar (50)
respectively. Before using them into our INSERT statement we have set their
values accordingly as 90, ‘Training’, and ‘Karachi’. Now we can use them into an
insert statement and run them concurrently/simultaneously.

DECLARE @dept_number int


set @dept_number=90
DECLARE @dept_name nvarchar(50)
set @dept_name='Training'
DECLARE @dept_location nvarchar(50)
set @dept_location='Karachi'

insert into department values(@dept_number,@dept_name,@dept_location)

The above example is treated as a script that is you are running the entire script or
nothing at all. They are all working in unison to accomplish one task—to insert
one record into the database.
Check it existence by running the following query:

select * from department

CE301: Database Management Systems 21


DBMS

COPYING ROWS FROM ANOTHER TABLE


You can use the INSERT statement to add rows to a table whereas the values come
from existing tables. We do not use values clause, instead use a subquery (which we
may discuss later). You should match the number of columns in the INSERT clause to
those in the subquery.

Syntax
INSERT INTO table(column_list)
Subquery

Where: table is the table name where insert statement


is sought for
Column_list name of the columns in the table to be populated
Subquery subquery that returns values into the table

Consider the following query:

insert into bonus(ename,job,sal,comm)


select ename,job,sal,comm
from employee
where job='Manager'

Here Bonus table has been populated by a SELECT statement from Employee
table using the INSERT statement. Check the Bonus table by using this query.

select * from bonus

Updating/Changing Data With The UPDATE Statement


You can update an existing record or row in a table by using the UPDATE statement.

Syntax
UPDATE <table name>
SET <column> = <value>
[WHERE condition

Where: Table is the name of the table


Column is the name of the column(s) in the table to updated
Value is the corresponding value for the column

Updating Rows in a Table


The update statement can modify rows specified by the WHERE clause condition.
Omitting the WHERE will result in updating all the records in the table.

CE301: Database Management Systems 22


DBMS

a. Consider the following query: Specific row(s) can be updated while using the
WHERE clause.

update employee set dno=10 where eno=259

This query updates the department number information in the employee table
from 30 to 10.

i. Consider the following query: All rows in the table will be updated, if we
omit the WHERE clause.

update temp set Dno=20

Temp table has the same data as of the Employee table. You will be provided this
in the lab.

Updating with Multiple Columns Subquery


Multiple column sub-query can be used to be implemented in the SET clause to
update a row.
Syntax
UPDATE table
SET (column, column,) =
(SELECT column, column, …
FROM table
WHERE condition

Consider the following query:

update employee set job=(Select job from employee


Where eo=231), dno=(Select dno FROM employee
Where eno=231) where eno=760

Updating Rows Based on another Table


You can use subqueries to update records of a table. Consider the following example:

update temp set dno=(select dno from employee


where eno=104), job=(select job from employee
where eno=104)

This changes the department number of all employees in the temp table with that of
the employee number 104 in the Employee table and vice versa his job title.

Removing Data With The DELETE Statement

CE301: Database Management Systems 23


DBMS

You can delete records of table by the DELETE statement.

Syntax
DELETE FROM table
WHERE condition

Here FROM keyword is optional. Always remember that all the rows of the table will
be deleted if not mentioning the WHERE clause.

Deleting Rows from a Table


a. Consider the following query: Specific row(s) can be deleted while using the
WHERE clause.

delete from department where dname='development'

b. Consider the following query: All rows in the table will be deleted, if we
omit the WHERE clause.

delete from dept

Dept table will be provided to you in lab.

Deleting Rows Based on Another Table


You can use subqueries for deleting rows from a table based on values of some other
table. Consider the following example:

delete from temp


where dno=(select dno from department where dname='Research')

All records of temp table will vanish.

LAB # 5
OBJECTIVE
Apply Sorting commands and Set Operators to retrieve data from tables in SQL

THEORY
SORTING ROWS WITH ORDER BY CLAUSE
The order of rows retrieved by a query result is undefined. You can use the ORDER
BY clause to display the rows in a specified order. The ORDER BY clause sorts
query results by one or more columns. The ORDER BY clause is placed last in the
query. You can specify and expression or an alias to sort. Sorting can be ascending
(ASC) or descending (DESC). By default, records are in ASC order. The sort limit is
the number of columns in the given table.

CE301: Database Management Systems 24


DBMS

SYNTAX

SELECT expression
FROM table
WHERE condition(s)
ORDER BY {column, expression} [ASC|DESC]

• Numeric values are shown with the lowest values first e.g. 1-10000.
• Date values are shown with the earlier values first e.g. 1st Jan, 2009 before 1st
Feb, 2009.
• Character values are shown in alphabetical order e.g. from A-Z.

The following query retrieves records from the employee table in an order of their
appointments.

select * from employee order by hiredate

Test different columns for ORDER BY clause by writing more queries yourself.

Sorting in Descending Order


To reverse the order of rows simply put DESC after the column name in the ORDER
BY clause.

select * from employee order by hiredate desc

Results will be reversed by placing DESC

Sorting by Column Alias


You can use a column alias in the ORDER BY clause.
1. The following example illustrates this:

select ename,job,sal,sal*12 'Annual Income' from employee


order by 'Annual Income'

CE301: Database Management Systems 25


DBMS

Sorting by Multiple Columns


You can sort by more than one column. Specify the columns, and separate the column
name by commas. Columns names which are not present in the SELECT statement
can also be used in the ORDER BY clause.
1. Type this query:

select * from employee order by dno,sal desc

2. First ORDER BY clause orders the results thus obtained by department number.
3. Second ORDER BY clause then orders each ordered result on the basis of
employee salary.
4. Check the results yourself.
5. Test this query yourself.

select * from employee order by dno,sal

SET OPERATORS:
Set operators operate on two result sets of queries, comparing complete rows between
the results. Depending on the result of the comparison and the set operator used, the
operator determines whether to return the row or not. T-SQL supports three set
operators: UNION, INTERSECT, and EXCEPT; it also supports one multiset
operator: UNION ALL.

The general form of code using a set operator is as follows.

<query 1>
<set operator>
<query 2>
[ORDER BY <order_by_list>]

Working with set operators follows a number of guidelines

• Because complete rows are matched between the result sets, the number of
columns in the queries has to be the same and the column types of
corresponding columns need to be compatible (implicitly convertible).

• Set operators consider two NULLs as equal for the purpose of comparison.
This is quite unusual when compared to filtering clauses like WHERE and
ON.

• Because the operators are set operators and not cursor operators, the individual
queries are not allowed to have ORDER BY clauses.

CE301: Database Management Systems 26


DBMS

• You can optionally add an ORDER BY clause that determines presentation


ordering of the result of the set operator.

• The column names of result columns are determined by the first query
UNION and UNION ALL

The UNION set operator unifies the results of the two input queries. As a set operator,
UNION has an implied DISTINCT property, meaning that it does not return duplicate
rows

As an example for using the UNION operator, the following query returns locations
that are employee locations or customer locations or both.

SELECT country, region, city FROM HR.Employees


UNION
SELECT country, region, city FROM Sales.Customers;

As an example, the following query unifies employee locations and customer


locations using the UNION ALL operator.

SELECT country, region, city FROM HR.Employees


UNION ALL
SELECT country, region, city FROM Sales.Customers;

INTERSECT

The INTERSECT operator returns only distinct rows that are common to both sets. In
other words, if a row appears at least once in the first set and at least once in the
second set, it will appear once in the result of the INTERSECT operator.

As an example, the following code uses the INTERSECT operator to return distinct
locations that are both employee and customer locations (locations where there’s at
least one employee and at least one customer).

SELECT country, region, city FROM HR.Employees


INTERSECT
SELECT country, region, city FROM Sales.Customers;

EXCEPT

The EXCEPT operator performs set difference. It returns distinct rows that appear in
the first query but not the second. In other words, if a row appears at least once in the
first query and zero times in the second, it’s returned once in the output.

CE301: Database Management Systems 27


DBMS

As an example for using EXCEPT, the following query returns locations that are
employee locations but not customer locations.

SELECT country, region, city FROM HR.Employees


EXCEPT
SELECT country, region, city FROM Sales.Customers;

With UNION and INTERSECT, the order of the input queries doesn’t matter.
However, with EXCEPT, there’s different meaning to

<query 1> EXCEPT <query 2> vs. <query 2> EXCEPT<query 1>
.
Finally, set operators have precedence: INTERSECT precedes UNION and EXCEPT,
and UNION and EXCEPT are considered equal. Consider the following set operators.

<query 1> UNION <query 2> INTERSECT <query 3>;

First, the intersection between query 2 and query 3 takes place, and then a union
between the result of the intersection and query 1. You can always force precedence
by using parentheses. So, if you want the union to take place first, you use the
following form.

(<query 1> UNION <query 2>) INTERSECT <query 3>;

CE301: Database Management Systems 28


DBMS

LAB TASKS:

Employees (employee_id, first_name, last_name, email, phone_number,


hire_date, job_id, salary, commission_pct, manager_id, department_id)

1. From the following schema, write a SQL query to find those employees
whose first name contains the letters R, A, or N. Sort the result-set in
ascending order by salary. Return all fields.

2. From the following schema, write a SQL query to find those employees
who earn above 21000 or the fifth character in their phone number is 8..
Sort the result-set in ascending order by last name. Return full name (first
name and last name), hire date, commission percentage, email, and
telephone separated by '-', and salary.

Orders(ord_no, purch_amt, ord_date, customer_id,


salesman_id)
Salesman (salesman_id, name, city, commission)
Customer (customer_id, cust_name, city, grade, salesman_id)

3. From the above tables, write a SQL query to find all salespeople and
customers located in the city of London.
4. Let’s assume we want to find all job titles for positions held by both male
and female employees, find out which titles are in common

CE301: Database Management Systems 29


DBMS

LAB # 6

OBJECTIVE
Apply Join Operations in SQL.

THEORY
By using joins, you can retrieve data from two or more tables based on logical
relationships between the tables. Joins indicate how SQL should use data from one
table to select the rows in another table.

A join condition defines the way two tables are related in a query by:

 Specifying the column from each table to be used for the join. A typical join
condition specifies a foreign key from one table and its associated key in the
other table.
 Specifying a logical operator (for example, = or <>,) to be used in comparing
values from the columns.

There are various forms of the JOIN clause. These will include:
 INNER JOIN
 OUTER JOIN (both LEFT and RIGHT)
 FULL OUTER JOIN
 CROSS JOIN

A JOIN does just what it sounds like—it puts the information from two tables
together into one result set. We can think of a result set as being a “virtual” table. It
has both columns and rows, and the columns have data types. How exactly does a
JOIN put the information from two tables into a single result set? Well, that depends
on how you tell it to put the data together—that’s why there are four different kinds of
JOINs. The thing that all JOINs have in common is that they match one record up
with one or more other records to make a record that is a superset created by the
combined columns of both records.

For example, let’s take a record from a table we’ll call Films:

Now let’s follow that up with a record from a table called Actors:

With a JOIN, we could create one record from two records found in totally separate
tables:

CE301: Database Management Systems 30


DBMS

1) INNER JOINs
INNER JOINs are far and away the most common kind of JOIN. They match
records together based on one or more common fields, as do most JOINs, but
an INNER JOIN returns only the records where there are matches for
whatever field(s) you have said are to be used for the JOIN. In our previous
examples, every record has been included in the result set at least once, but
this situation is rarely the case in the real world.
Let’s modify our tables and see what we would get with an INNER JOIN.
Here’s our Films table:

And our Actors table:

Using an INNER JOIN, our result set would look like this:

Syntax
SELECT <select list>FROM <first_table><join_type><second_table>[ON
<join_condition>]

Natural Join:

CE301: Database Management Systems 31


DBMS

Creating Natural Joins

• The NATURAL JOIN clause is based on all columns in the two tables
that have the same name.
• It selects rows from the two tables that have equal values in all
matched columns.
• If the columns having the same names have different data types, an error
is returned.

Retrieving Records with Natural Joins

Creating Joins with the USING Clause

• If several columns have the same names but the data types do not
match, the NATURAL JOIN clause can be modified with the USING clause
to specify the columns that should be used for an equijoin.
• Use the USING clause to match only one column when more than one
column matches.

CE301: Database Management Systems 32


DBMS

• Do not use a table name or alias in the referenced columns.


• The NATURAL JOIN and USING clauses are mutually exclusive.

Joining Column Names

Retrieving Records with the USING Clause

Qualifying Ambiguous Column Names

• Use table prefixes to qualify column names that are in multiple tables.
• Use table prefixes to improve performance.
• Use column aliases to distinguish columns that have identical names
but reside in different tables.
• Do not use aliases on columns that are identified in the USING clause
and listed elsewhere in the SQL statement.

Using Table Aliases

• Use table aliases to simplify queries.


• Use table aliases to improve performance

CE301: Database Management Systems 33


DBMS

Creating Joins with the ON Clause

• The join condition for the natural join is basically an equijoin of all
columns with the same name.
• Use the ON clause to specify arbitrary conditions or specify columns
to join.
• The join condition is separated from other search conditions.
• The ON clause makes code easy to understand.

Retrieving Records with the ON Clause

Self -Joins Using the ON Clause

Self-Joins Using the ON Clause

CE301: Database Management Systems 34


DBMS

Applying Additional Conditions to a Join

Creating Three-Way Joins with the ON Clause

Nonequi jo ins

Retrieving Records with Nonequijoins

CE301: Database Management Systems 35


DBMS

Outer Joins

INNER Versus OUTER Joins

• In SQL: 1999, the join of two tables returning only matched rows is
called an inner join.
• A join between two tables that returns the results of the inner join as
well as the unmatched rows from the left (or right) tables is called a left (or
right) outer join.


• A join between two tables that returns the results of an inner join as
well as the results of a left and right join is a full outer join.

LEFT OUTER JOIN

RIGHT OUTER JOIN

FULL OUTER JOIN

CE301: Database Management Systems 36


DBMS

Cartesian Products

• A Cartesian product is formed when:


1. A join condition is omitted

2. A join condition is invalid


3. All rows in the first table are joined to all rows in the second table

• To avoid a Cartesian product, always include a valid join condition.

Creating Cross Joins

• The CROSS JOIN clause produces the cross-product of two tables.


• This is also called a Cartesian product between the two tables.

LAB TASK:
EmployeeDetail Table - EmployeeID,
FirstName,LastName,Salary,JoiningDate,Department,Gender

ProjectDetail Table - ProjectDetailID, EmployeeID,ProjectName

 Get employee name, project name order by firstname from "EmployeeDetail" and
"ProjectDetail" for those employee which have assigned project already.
 Get all project name even they have not matching any employeeid, in left table,
order by firstname from "EmployeeDetail" and "ProjectDetail".
 Get employee name, project name order by firstname from "EmployeeDetail" and
"ProjectDetail" for all employee even they have not assigned project.

CE301: Database Management Systems 37


DBMS

LAB # 07
TASKS:
Consider a company database with the following data and execute the mentioned
statements using SQL queries.
TABLE 01
Employee

Employee no, Firstname , lastname, bdate, address, department, dno,


salary
TABLE 02
Department
Department number, employee number, department name, extension,

location

TABLE 03
Salary

Employee number, department number, salary, bonus, lowest salary,


highest salary

COMMANDS:
1) Create company database
2) Create tables using primary and foreign key constraints (allow null values in any one
column)
3) Insert at least 5 records in each table
4) Update and delete any one record from department table
5) Rename the table department as dept
6) Drop primary key from employee table
7) Retrieve employee number and their salaries and insert this data in another table using
sub query
8) Declare department number=30, department name=reaserch, extension=10,
location=multan and insert this record in the department table where employee
number=any
9) Display details of employee whose names start with A and salaries greater than 10000
10) Retrieve all employees whose salaries are between highest and lowest salaries using join
clause
11) Display the name of employees and their departments using join
12) Write sql query to retrieve employee number, department number, department name from
employee and department table using set operator, it may include duplicate rows.

CE301: Database Management Systems 38


DBMS

LAB # 8

OBJECTIVE
Apply single-row and multiple-row functions in SQL

THEORY
• Identify the available group functions
• Describe the use of group functions
• Group data by using the group by clause
• Include or exclude grouped rows by using the having clause
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.
What Are Group Functions?
Group functions operate on sets of rows to give one result per group
.

CE301: Database Management Systems 39


DBMS

Types of Group Functions


• AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE

Group Functions: Syntax

Using the AVG and SUM Functions


You can use AVG and SUM for numeric data

CE301: Database Management Systems 40


DBMS

Creating Groups of Data

GROUP BY Clause Syntax

You can divide rows in a table into smaller groups by using the GROUP BY clause.
All columns in the SELECT list that are not in group functions must be in the GROUP
BY clause.

CE301: Database Management Systems 41


DBMS

The GROUP BY column does not have to be in the SELECT list.

SELECT AVG(salary) FROM employees GROUP BY department_id ;

Grouping by More Than One Column

CE301: Database Management Systems 42


DBMS

Restricting Group Results with the HAVING Clause

When you use the HAVING clause, the Oracle server restricts groups as follows:
1. Rows are grouped.
2. The group function is applied.
3. Groups matching the HAVING clause are displayed.

Using the HAVING Clause

Nesting Group Functions


Display the maximum average salary

CE301: Database Management Systems 43


DBMS

TASKS:
Execute all queries using group by and having clause.
1. Get all jobs of the employees
2. Group all employees using their project numbers and jobs
3. Get project numbers for all projects employing fewer than four persons
4. Group rows of the works_on table by job and eliminate those jobs that do
not begin with the letter M

LAB # 9

CE301: Database Management Systems 44


DBMS

OBJECTIVE
Explore management of tables and views, the nature of views, and how they can be
used, how to create, alter, and drop views using T-SQL. Also explore and run Stored
Procedures.

THEORY

A view is, at its core, nothing more than a stored query. What’s great is that you can
mix and match your data from base tables (or other views) to create what will, in
most respects, function just like an ordinary base table. You can create a simple
query that selects from only one table and leaves some rows or columns out, or you
can create a complex query that joins several tables and makes them appear as one.

SQL CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE conditio

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
WHE RE Discontinued=No

We can query the view above 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:
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:

CE301: Database Management Systems 45


DBMS

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. Now we want to 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

FROM table_name
WHERE condition

CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)

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

CE301: Database Management Systems 46


DBMS

SQL Dropping a View


You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax


DROP VIEW view_name
STORED PROCEDURE:
A Stored Procedure is precompiled collection of T-SQL statements. Stored
procedures are named and processed as a single unit.

System Stored Procedures


SQL Server provides some readily available stored procedures form managing SQL
Server and for users and database information retrieval. These can only be executed.
The following table list some system stored procedures.

SYSTEM STORED PROCEDURES DESCRIPTION


sp_databases List all the available databases on the server
sp_server_info Lists long list of server information like
DBMS_NAME, DBMS_VER,
SYS_SPROC_VERSION,
ACCESSIBLE_TABLES etc
sp_stored_procedures Lists all the stored procedures available in the
current environment.
sp_tables Lists all the objects that can be queried in the
current environment.
sp_configure Changes the global configuration options of
the server. When using it without options, then
the current server settings are displayed.
sp_help Shows information about database objects
specified.
sp_helptext Shows complete text for a database object.

Here we shall focus on user defined stored procedures.

1. Creating User defined Stored Procedures:


Users can create their customized stored procedures using the CREATE
PROCEDURE statement which are stored in the current database.

Syntax
CREATE PROC procedure_name AS T-SQL statement(s)
Create a Stored Procedure
1. Consider the following query (stored procedure):

CE301: Database Management Systems 47


DBMS

CREATE PROCEDURE EMP_20 AS SELECT * FROM EMPLOYEE WHERE


DNO=20

A stored procedure will be created that will show the details of all the employees
from the employee table whose department number is 20.

2. Executing User defined Stored Procedures:


User-defined stored procedures can be executed using the EXECUTE statement.

Syntax
EXECUTE procedure_name

Execute a Stored Procedure

Consider the following query which executes the EMP_20 stored procedure
(output is shown in figure):

EXECUTE EMP_20

3. Using Parameters in Stored Procedures:

Parameters can be passed to a stored procedure from the EXECUTE statement.

Syntax
CREATE PROCEDURE procedure_name
@parameter_name <data type>
AS
T-SQL Statement(s)

4. Passing Parameters to a Stored Procedure


Now we create a stored procedure that will show the details of the employee
department whilst department number will be passed as a parameter opposed to
EMP_20 stored procedure which can show the details of department number 20 only.
1. Consider the following stored procedure:

create procedure edetail


@deptno int
As select * from employee where eno=@deptno Now you can execute this
stored procedure while passing the argument as of the data type of the parameter
as shown below:
execute edetail 20

CE301: Database Management Systems 48


DBMS

Lab Task:
The following SELECT statement returns a list of products from products
table in the abc sample database:the p

roducts table in the BikeStores sample database:

SELECT
product_name,
list_price
FROM
production.products
ORDER BY
product_name;

1. Create a stored procedure that wraps this query.


2. Modify a above stored procedure by sorting the products by list prices
instead of product names:
3. Define both statements
a DROP PROCEDURE sp_name
b DROP PROC sp_name;

LAB # 10

OBJECTIVE
Apply SQL Functions and User defined Functions in SQL.

CE301: Database Management Systems 49


DBMS

THEORY

SQL has many built-in functions for performing calculations on data.


• Aggregate Functions in SQL Server
• DateTime Function in SQL Server
• String Functions in SQL Server

1. THE UPPER() Function

the Upper() function converts the value of a field to uppercase.

Syntax
SELECT UPPER(column_name) FROM table_name;

2. THE LOWER() Function

The LOWER() function converts the value of a field to lowercase.

Syntax
SELECT LOWER(column_name) FROM table_name;

3. The AVG() Function

The AVG() function returns the average value of a numeric column.

Syntax
SELECT AVG(column_name) FROM table_name

Example
The following SQL statement gets the average value of the "Price" column from the
"Products" table:
SELECT AVG(Price) AS PriceAverage FROM Products;
4. SQL COUNT() FUNCTION
The COUNT(column_name) function returns the number of values (NULL values
will not be counted) of the specified column:

Syntax
SELECT COUNT(column_name) FROM table_name;

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name;

CE301: Database Management Systems 50


DBMS

The COUNT(DISTINCT column_name) function returns the number of distinct


values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;

Example

SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders


WHERE CustomerID=7;

5. The MAX() Function

The MAX() function returns the largest value of the selected column.

Syntax
SELECT MAX(column_name) FROM table_name;

Example

SELECT MAX(Price) AS HighestPrice FROM Products;

6. The MIN() Function

The MIN() function returns the smallest value of the selected column.

Syntax
SELECT MIN(column_name) FROM table_name;

Example
SELECT MIN(Price) AS SmallestOrderPrice FROM Products;

7. The SUM() Function

The SUM() function returns the total sum of a numeric column.


Syntax
SEL ECT SUM(column_name) FROM table_name;

Example

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;

8. STDEVP Function
The STDEVP function calculates the standard deviation for the population of items in
the SELECT statement. This function can only be used with numeric columns.

CE301: Database Management Systems 51


DBMS

Syntax

STDEVP(ALL or DISTINCT numeric expression)

ALL keyword is optional and is assumed by default. You can specify the DISTINCT
keyword if you want to take into account only the unique occurrence of each value.
The STDEVP function always returns a FLOAT data type value.

Example
The following example returns the standard deviation of population for amounts in
the FactFinance table:

SELECT STDEVP(amount) FROM FactFinance

9. VAR Function
The VAR function calculates the statistical variance of all values in the SELECT
statement. This function can only be used with numeric columns.

Syntax
VAR(ALL or DISTINCT numeric column)

ALL keyword is optional and is assumed by default. You can specify the DISTINCT
keyword if you want to take into account only the unique occurrence of each value.
The VAR function always returns a FLOAT data type value.

Example
The following example returns the variance of amounts from FactFinance table:

SELEC VAR(amount) FROM FactFinance

DateTime Function in SQL Server

1. GETDATE()
The GETDATE() function returns the current date and time from the SQL Server.
SELECT GETDATE() AS CurrentDateTime

2. DATEADD()

DATEADD() is used to add or subtract datetime. Its return a new datetime based on
the added or subtracted interval.

CE301: Database Management Systems 52


DBMS

Syntax
DATEADD(datepart, number, date)

datepart is the parameter that specifies on which part of the date to return a new
value. Number parameter is used to increment datepart.

Declare @Date datetime set @Date =


(SELECT GETDATE()); print
@Date -- Print Current Date --
Adding 5 days with Current Date
SELECT DATEADD(day, 2,@Date ) AS NewTime

3. DATEPART()

DATEPART() is used when we need a part of date or time from a datetime


variable. We can use DATEPART() method only with select command. Syntax

DATEPART(datepart, date)
Example :
SELECT DATEPART(year, GETDATE()) AS 'Year'
-- Get Only Month
SELECT DATEPART(month, GETDATE()) AS 'Month'
-- Get Only hour
SELECT DATEPART(hour, GETDATE()) AS 'Hour

4. DATEDIFF()
DATEDIFF() is very common function to find out the difference between
two DateTime elements.

Syntax
DATEDIFF(datepart, startdate, enddate)

Where startdate and enddate are valid date expressions and datepart can be one of the
following:

datepart: year, quarter, month, dayofyear, day, week, weekday, hour, minute,
second, millisecond, microsecond, nanosecond

Example :
Now we want to get the number of days between two dates.

SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate

CE301: Database Management Systems 53


DBMS

5. DATENAME()

DATENAME() is very common and most useful function to find out the date name
from the datetime value.

Example

-- Get Today
SELECT DATENAME(dw, getdate()) AS 'Today Is'
-- Get Mont name
SELECT DATENAME(month, getdate()) AS 'Month'

6. DAY()

DAY() is used to get the day from any date time object.

Example:

SELECT DAY(getdate()) AS 'DAY'

7. MONTH()

SELECT MONTH(getdate()) AS 'Month'

8. YEAR()

SELECT YEAR(getdate()) AS 'Year'

String Functions

1. ASCII()

Returns the ASCII code value of the leftmost character of a character expression.

Syntax

ASCII ( character_expression )

CE301: Database Management Systems 54


DBMS

Example

SELECT ASCII('AB')
SELECT ASCII('BC')

2. LEFT()

Returns the left most characters of a string.

Syntax

LEFT(string, length)

string
Specifies the string from which to obtain the left-most characters.
length
Specifies the number of characters to obtain.

Example

SELECT LEFT('Marufuzzaman',5)

3. RIGHT()

Returns the right most characters of a string.

Syntax

RIGHT(string, length)

Example
SELECT RIGHT('Md. Marufuzzaman',5)

4. LTRIM()

Returns a character expression after it removes leading blanks.


Example :

SELECT LTRIM(' Md. Marufuzzaman')


5. RTRIM()

CE301: Database Management Systems 55


DBMS

Returns a character string after truncating all trailing blanks.

Example

SELECT RTRIM('Md. Marufuzzaman ')

6. REPLACE()

Returns a string with all the instances of a substring replaced by another substring.

Syntax
REPLACE(find, replace, string)

Find Specifies the string that contains the substring to replace all instances of with
another.

Replace Specifies the substring to locate.

String Specifies the substring with which to replace the located substring.

Example

SELECT REPLACE('my name is sana','sana','zehra')

USER-DEFINED FUNCTIONS:
Like functions in programming languages, Microsoft SQL Server user-defined
functions are routines that accept parameters, perform an action, such as a complex
calculation, and return the result of that action as a value. The return value can either
be a single scalar value or a result set.

CREATE FUNCTION creates a user-defined function. This is a saved Transact-SQL


routine that returns a value. User-defined functions cannot be used to perform actions
that modify the database state. User-defined functions, like system functions, can be
invoked from a query.

There are three types of User-Defined functions in SQL Server and they are
Scalar, Inline Table-Valued and Multi-statement Table-valued.

SYNTAX

Scalar Functions

CE301: Database Management Systems 56


DBMS

CREATE FUNCTION function_name


@parameter_name_list parameter_data_type
RETURNS return_data_type
AS
BEGIN
function_body
RETURN scalar_expression
END

The following statement shows how to create a function that accepts two input
parameters, sums them together and then returns the sum to the calling statement.

The structure of the CREATE FUNCTION statement is fairly straightforward.


You provide an object name (fn_Sum), input parameters (@Val1 and @Val2). The
type of data the function will return () and The statement(s) the function executes are
located between the BEGIN…END block.

The following SELECT statement calls the function. Note that the two-part name
(owner.object_name) is required when calling this function.

SELECT dbo.fn_Sum(1,98) AS SumResult

When the SELECT is executed, the input parameters 1 and 98 are added together and
the sum 99 is returned.

UDF Design Guidelines


A user-defined function is stored as a database object providing reusable code that
can be used in these ways:
• In Transact-SQL statements such as SELECT
• In applications calling the function
• In the definition of another user-defined function
• To parameterize a view or improve the functionality of an indexed view
• To define a column in a table
• To define a CHECK constraint on a column
• To replace a stored procedure

CE301: Database Management Systems 57


DBMS

Three Types of User-Defined Functions

Now that you have seen how easy it is to create and implement a simple function, let’s
cover the three different types of user-defined functions and some of the nuances of
how they are implemented.

1. Scalar Functions
A scalar function returns a single value of the data type referenced in the RETURNS
clause of the CREATE FUNCTION statement. The returned data can be of any type
except text, ntext, image, cursor, or timestamp.

CREATE FUNCTION DiscountPrice(@OriginalPrice money, @Discount float)


RETURNS money
AS
BEGIN
RETURN @OriginalPrice * @Discount END

The parameters to the function are placed in brackets after the name of the function in
the CREATE FUNCTION statement.
Make sure you select the Northwind database from the drop-down list box on the
Query Analyzer toolbar before running the script. That way, the function is created in
the Northwind database.
Executing the procedure results in this as shown in figure:

2. Inline Table-Valued Functions


An inline table-valued function returns a variable of data type table whose value is
derived from a single SELECT statement.
• Since the return value is derived from the SELECT statement, there is no
BEGIN/END block needed in the CREATE FUNCTION statement.

• There is also no need to specify the table variable name (or column definitions
for the table variable) because the structure of the returned value is generated
from the columns that compose the SELECT statement.
• Because the results are a function of the columns referenced in the SELECT,
no duplicate column names are allowed and all derived columns must have an
associated alias.
The following uses the Employee table in the CompanyDB database to show how an
inline table-valued function is implemented.

CE301: Database Management Systems 58


DBMS

Execute the function by the following query:

3. Multi-Statement Table-Valued Functions


The multi-statement table-valued function is slightly more complicated than the other
two types of functions because it uses multiple statements to build the table that is
returned to the calling statement.
Unlike the inline table-valued function, a table variable must be explicitly declared
and defined. The following example shows how to implement a multi-statement
tablevalued function that populates and returns a table variable.
The following query illustrates this:

To test this function, all you need to do is run a SELECT statement against the
function with the employee number that you want to insert into the temporary table.
The following SELECT statement does just that for Emp_No =100.

Dropping / Deleting a User Define Function

A UDF can be deleted from the SSMS IDE or using the following command.

SYNTAX

DROP udf_name

CE301: Database Management Systems 59


DBMS

Drop the UDFs you have created by using this command.

drop function
AddEmp

LAB # 11

OBJECTIVE
Apply sub queries and correlated subqueries in SQL. Also study Triggers and Types
of Triggers.

THEORY

What is a subquery in SQL Server?


In SQL Server, a subquery is a query within a query. You can create subqueries within
your SQL statements. These subqueries can reside in the WHERE clause, the FROM
clause, or the SELECT clause.

Note

CE301: Database Management Systems 60


DBMS

• In SQL Server (Transact-SQL), a subquery is also called an INNER


QUERY or INNER SELECT.
• In SQL Server (Transact-SQL), the main query that contains the subquery
is also called the OUTER QUERY or OUTER SELECT.

Subqueries are generally used to fi ll one of a few needs:


• To break a query into a series of logical steps

• To provide a listing to be the target of a WHERE clause together with


[IN|EXISTS|ANY|ALL]
• To provide a lookup driven by each individual record in a parent query

WHERE clause
Most often, the subquery will be found in the WHERE clause. These subqueries are
also called nested subqueries.

For example:

SELECT p.product_id, p.product_name


FROM products p
WHERE p.product_id IN

The subquery portion of the SELECT statement above is:

(SELECT inv.product_id
FROM inventory inv
WHERE inv.quantity > 10);

This subquery allows you to find all product_id values from the inventory table that
have a quantity greater than 10. The subquery is then used to filter the results from the
main query using the IN condition.
This subquery could have alternatively been written as an INNER join as follows:

SELECT p.product_id, p.product_name


FROM products p
INNER JOIN inventory inv
ON p.product_id = inv.product_id
WHERE inv.quantity > 10;

This INNER JOIN would run more efficiently than the original subquery. It is
important to note, though, that not all subqueries can be rewritten using joins.

CE301: Database Management Systems 61


DBMS

FROM clause
A subquery can also be found in the FROM clause. These are called inline views.
For example:

SELECT suppliers.supplier_name, subquery1.total_amt


FROM suppliers,
(SELECT supplier_id, SUM(orders.amount) AS total_amt
FROM orders
GROUP BY supplier_id) subquery1
WHERE subquery1.supplier_id = suppliers.supplier_id;

In this example, we've created a subquery in the FROM clause as follows:

(SELECT supplier_id, SUM(orders.amount) AS total_amt


FROM orders
GROUP BY supplier_id) subquery1
This subquery has been aliased with the name subquery1. This will be the name used
to reference this subquery or any of its fields.

SELECT clause
A subquery can also be found in the SELECT clause. These are generally used when
you wish to retrieve a calculation using an aggregate function such as theSUM,
COUNT, MIN, or MAX function, but you do not want the aggregate function to apply
to the main query.
For example:

SELECT e1.last_name, e1.first_name,


(SELECT MAX(salary)
FROM employees e2
WHERE e1.employee_id = e2.employee_id) subquery2
FROM employees e1;

In this example, we've created a subquery in the SELECT clause as follows:

(SELECT MAX(salary)
FROM employees e2
WHERE e1.employee_id = e2.employee_id) subquery2

The subquery has been aliased with the name subquery2. This will be the name used
to reference this subquery or any of its fields.

CE301: Database Management Systems 62


DBMS

Building a Nested Subquery


A nested subquery is one that goes in only one direction — returning either a single
value for use in the outer query, or perhaps a full list of values to be used with the IN
operator. In the event you want to use an explicit = operator, you‟ll use a query that
returns a single value — that means one column from one row. If you are expecting a
list back, you‟ll need to use the IN operator with your outer query.

In the loosest sense, your query syntax will look something like one of these two
syntax templates:

SELECT <SELECT list>


FROM <SomeTable>
WHERE <SomeColumn> = (
SELECT <single column>
FROM <SomeTable>
WHERE <condition that results in only one row returned>)

Or:

SELECT <SELECT list>


FROM <SomeTable>
WHERE <SomeColumn> IN (
SELECT <single column>
FROM <SomeTable>
[WHERE <condition>)]

Nested Queries Using Single-Value SELECT Statements

Let‟s get down to the nitty-gritty with an explicit example. Let‟s say, for example,
that you want to know the ProductIDs of every item sold on the first day any product
was purchased from the system.

If you already know the first day that an order was placed in the system, it‟s no
problem. The query would look something like this:

SELECT DISTINCT sod.ProductID


FROM Sales.SalesOrderHeader soh
JOIN Sales.SalesOrderDetail sod
ON soh.SalesOrderID = sod.SalesOrderID
WHERE OrderDate = „07/01/2005‟; --This is first OrderDate in the system

But let‟s say, just for instance, that you are regularly purging data from the system,
and you still want to ask this same question as part of an automated report.
Because it‟s going to be automated, you can‟t run a query to find out what the first
date in the system is and manually plug that into your query — or can you? Actually,
the answer is: “Yes, you can,” by putting it all into just one statement:

CE301: Database Management Systems 63


DBMS

SELECT DISTINCT soh.OrderDate, sod.ProductID


FROM Sales.SalesOrderHeader soh
JOIN Sales.SalesOrderDetail sod
ON soh.SalesOrderID = sod.SalesOrderID
WHERE OrderDate = (SELECT MIN(OrderDate) FROM
Sales.SalesOrderHeader);

Nested Queries Using Subqueries That Return Multiple Values

Perhaps the most common of all subqueries implemented in the world are those that
retrieve some form of domain list and use it as criteria for a query. You might write
something like this:

SELECT ProductID, Name


FROM Production.Product
WHERE ProductID IN (
SELECT ProductID FROM Sales.SpecialOfferProduct);
While this works just fi ne, queries of this type almost always can be done using an
inner join rather than a nested SELECT. For example, you could get the same results
as the preceding subquery by running this simple join:

SELECT DISTINCT pp.ProductID, Name


FROM Production.Product pp
JOIN Sales.SpecialOfferProduct ssop
ON pp.ProductID = ssop.ProductID;

BUILDING CORRELATED SUBQUERIES

How Correlated Subqueries Work

What makes correlated subqueries different from the nested subqueries you‟ve been
looking at is that the information travels in two directions rather than one. In a nested
subquery, the inner query is processed only once, and that information is passed out
for the outer query, which will also execute just once — essentially providing the
same value or list that you would have provided if you had typed it in yourself.

With correlated subqueries, however, the inner query runs on information provided by
the outer query, and vice versa. That may seem a bit confusing (that chicken or the
egg thing again), but it works in a three-step process:

1. The outer query obtains a record and passes it into the inner query.
2. The inner query executes based on the passed-in value(s).
3. The inner query then passes the values from its results back to the outer query,
which uses them to fi nish its processing.

Example:

CE301: Database Management Systems 64


DBMS

----Example of Correlated Subqueries


USE AdventureWorks;
GO

SELECT e.EmployeeID
FROM HumanResources.Employee e
WHERE e.ContactID IN
(
SELECT c.ContactID
FROM Person.Contact c
WHERE MONTH(c.ModifiedDate) = MONTH(e.ModifiedDate)
)
GO

Triggers
Triggers are database operations which are automatically performed when an action
such as Insert, Update or Delete is performed on a Table or a View in database.
Triggers are associated with the Table or View directly i.e. each table has its own
Triggers.

Types of Triggers
There are two types of Triggers. After and Instead of Triggers.
1. After Triggers
These triggers are executed after an action such as Insert, Update or Delete is
performed.

2. Instead of Triggers
These triggers are executed instead of any of the Insert, Update or Delete operations.
For example, let’s say you write an Instead of Trigger for Delete operation, then
whenever a Delete is performed the Trigger will be executed first and if the Trigger
deletes record then only the record will be deleted.

After Triggers
Now I will explain you with examples the After Triggers for Insert, Update and Delete
operations.
1. Insert Trigger
Below is an example of an After Insert Trigger. Whenever a row is inserted in the
Customers Table, the following trigger will be executed. The newly inserted record is
available in the INSERTED table.
The following Trigger is fetching the CustomerId of the inserted record and the
fetched value is inserted in the CustomerLogs table.

CE301: Database Management Systems 65


DBMS

CREATE TRIGGER [dbo].[Customer_INSERT ]


ON [dbo].[Customers ]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CustomerId INT

SELECT @CustomerId = INSERTED.CustomerId


FROM INSERTED

INSERT INTO CustomerLogs


VALUES(@CustomerId, 'Inserted')
END

2. Update Trigger
Below is an example of an After Update Trigger. Whenever a row is updated in the
Customers Table, the following trigger will be executed. The updated record is
available in the INSERTED table.
The following Trigger is fetching the CustomerId of the updated record. In order to
find which column is updated, you will need to use UPDATE function and pass the
Column name of the Table to it.
The UPDATE function will return TRUE for a Column if its value was updated else it
will return false.
Finally based on which column of the record has been updated a record (containing
the CustomerId and the appropriate action) is inserted in the CustomerLogs table.

CREATE TRIGGER [dbo].[Customer_UPDATE]


ON [dbo].[Customers]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CustomerId INT


DECLARE @Action VARCHAR(50)

SELECT @CustomerId = INSERTED.CustomerId


FROM INSERTED

IF UPDATE(Name)
BEGIN
SET @Action = 'Updated Name'
END

IF UPDATE(Country)

CE301: Database Management Systems 66


DBMS

BEGIN
SET @Action = 'Updated Country'
END

INSERT INTO CustomerLogs


VALUES(@CustomerId, @Actio n)
END

3. Delete Trigger
Below is an example of an After Delete Trigger. Whenever a row is delete in the
Customers Table, the following trigger will be executed. The deleted record is
available in the DELETED table.
The following Trigger is fetching the CustomerId of the deleted record and the fetched
value is inserted in the CustomerLogs table.

CREATE TRIGGER [ dbo].[Customer_DELETE ]


ON [ dbo].[Customers ]
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CustomerId INT

SELECT @C ustomerId = DELETED.CustomerId


FROM DELETED

INSERT INTO CustomerLogs


VALUES(@CustomerId, 'Deleted')
END

Instead Of Triggers
Below is an example of an Instead Of Delete Trigger. Whenever anyone tries to delete
a row from the Customers table the following trigger is executed.
Inside the Trigger, I have added a condition that if record has CustomerId value 2 then
such a record must not be deleted and an error must be raised. Also a record is
inserted in the CustomerLogs table.
If the CustomerId value is not 2 then a delete query is executed which deletes the
record permanently and a record is inserted in the CustomerLogs table.

CREATE TRIGGER [dbo].[Customer_InsteadOfDELETE]


ON [dbo].[Customers]
INSTEAD OF DELETE
AS
BEGIN
SET NOCOUNT ON;

CE301: Database Management Systems 67


DBMS

DECLARE @CustomerId INT

SELECT @CustomerId = DELETED.CustomerId


FROM DELETED

IF @CustomerId = 2
BEGIN
RAISERROR('Mudassar Khan''s record cannot be deleted',16 ,1)
ROLLBACK
INSERT INTO CustomerLogs
VALUES(@CustomerId, 'Record cannot be deleted.')
END
ELSE
BEGIN
DELETE FROM Customers
WHERE CustomerId = @CustomerId

INSERT INTO CustomerLogs


VALUES(@CustomerId, 'Instead Of Delete')
END
END

The following error message shown when record with CustomerId 2 is deleted.

LAB # 12

CE301: Database Management Systems 68


DBMS

INTRODUCTION TO REACT JS AND NODE JS

OBJECTIVE:
To get familiar with the basic concepts of react js, node js and express js and MySQL.
What is React js?
React js is a free and open-source front end JavaScript library for building user
interfaces. It is maintained by Facebook and a community of individual developers
and companies. It can be used as a base language for building single-page, mobile
applications, or server-rendered applications with the help of frameworks like Next.js.
The following is a basic example of usage of react with JSX (Syntax extension of
javascript) and javascript. JSX is basically a HTML like language which make react js
easy to understand.

import React from "react";

const Greeting = () => {

return (
<div className="hello_world">
<h1> Hello, world! </h1>
</div>
);
};

export default Greeting;

What is Node js and Express js?


Node.js is an open-source, cross-platform, back-end JavaScript runtime
environment that runs on the V8 engine and executes JavaScript code outside a web
browser. Before the launch of node js, javascript was used just for front end
functionalities but node js has enabled javascript to run on server side as well. Node js
has an event driven architecture capable of asynchronous I/O.
On the other hand, Express js or simply Express is a backend web application
framework for node js, released under the MIT license. It is specifically designed for
building web applications and APIs. In January 2016, IBM announced that it would
place Express js under the supervision of Node js foundation incubator.
The following program will respond to HTTP Get request with the text ‘Hi, your
request has been received’, and listen to the port the program is running on port 2000.

// Import the Express library.


const express = require('express');

// Initializing the app.


const app = express();

// Getting the path request and sending the response with text
app.get('/', (req,res) => {
res.send('Hi, your request has been received');

CE301: Database Management Systems 69


DBMS

});

// Listen on port 2000


app.listen(2000, () => {
console.log('listening at http://localhost:2000');
});

What is MySQL?
Its almost similar to SQL which we are studying in our DBMS course. Although, its
RDBMS (Relational Database management system). A relational database organizes
data into one or more tables in which data may be related to each other, these relations
help structure the data. SQL stands for Structured Query language, it is a language
programmers used to create, modify, and extract data from the relational database as
well as control user access to the database.

TASK:
Using React, Node, Express and MySQL frameworks. Create CRUD application
which should have create, read, update, and delete functionalities.
REACT JS:
import './App.css';
import {useState} from 'react'
//axios is a library used to send request to an API
import Axios from 'axios'

function App() {

  const [Name,SetName] = useState("");


  const [Email,SetEmail] = useState("");
  const [Position,SetPosition] = useState("");
  const [Contact,SetContact] = useState();

  const [EmployeeList,setEmployeeList] = useState([]);

  const addEmployee = () => {


    Axios.post('http://localhost:3001/create' , {
      Name: Name,
      Email: Email,
      Position: Position,
      Contact: Contact
    }).then(() => {
      setEmployeeList([...EmployeeList, {
        Name: Name,
        Email: Email,
        Position: Position,
        Contact: Contact
      }])
    })

CE301: Database Management Systems 70


DBMS

  }
Here, we have declared some variables namely Name, Email, Position and contact
which are also in our database table and we have used states to store the value of these
attributes.
const getEmployees = () => {
    Axios.get('http://localhost:3001/Employees').then((response) => {
      setEmployeeList(response.data)
    })
  }
Here getEmployees callback function means we are displaying the records of the
database in a particular manner.
return (
    <div className="App">
      <div className="details">
      <h1>SIMPLE CRUD APPLICATION</h1>
      <label>Name: </label>
      <input type="text" onChange={(event) => {
        {SetName(event.target.value)};
      }}></input>
      <label>Email: </label>
      <input type="text" onChange={(event) => {
        {SetEmail(event.target.value)};
      }}></input>
      <label>Position: </label>
      <input type="text" onChange={(event) => {
        {SetPosition(event.target.value)};
      }}></input>
      <label>Contact: </label>
      <input type="number" onChange={(event) => {
        {SetContact(event.target.value)};
      }}></input>
      <button onClick={addEmployee}>Add Employees</button><br/>
      </div>
      <div className='details'>
      <button onClick={getEmployees}>Show Employees</button><br/>
      {EmployeeList.map((value,key) => {
        return(
          <div className='employees'>
            <h3>Email: {value.Email}</h3>
            <h3>Position: {value.Position}</h3>
            <h3>Contact: {value.Contact}</h3>
          </div>
        )
      })}
      </div>

    </div>
  );

CE301: Database Management Systems 71


DBMS

}
export default App;

This is the coding of structure of our form which is appearing on the browser.
NODE JS AND EXPRESS JS:
To run the project on client side, we write npm start on our terminal/cmd.
To run our server, we write nodemon index.js on our terminal
const express = require('express')
const app = express()
const mysql = require('mysql')
const cors = require('cors')

app.use(cors())
app.use(express.json())

const db = mysql.createConnection({
    user: 'root',
    host: '127.0.0.1',
    password: 'Password@123',
    database: 'crudapplication'
})

In this piece of code, main dependencies are called. Express js is used to create and
call the API which we have created.
Mysql is the name of our database with which we will be communicating with.
Cors is basically a medium to send API request from our front end to back end.
Remember that cors is just used to deal with the APIS that the users create on their
own.
Json() is a middleware function in express. This method returns the middleware that
only parses JSON and only looks at the requests where content-type header matches
the type option.
Beneath it is our database connection, root is the name of our user, 127.0.0.1 is our
host IP, password is given and after that, it’s the name of our database given.
app.post('/create', (req,res) => {
    console.log(req.body)
    const Name = req.body.Name
    const Email = req.body.Email
    const Position = req.body.Position
    const Contact = req.body.Contact
   
    db.query('INSERT INTO empdata (EmpName,Email,Position,Contact)
VALUES(?,?,?,?)' ,
    [Name,Email,Position,Contact],
    (err,results) => {
        if(err)
        {
            console.log(err)
        }

CE301: Database Management Systems 72


DBMS

        else{
            res.send('Successfully inserted...')
        }

    } )
})
app.get('/Employees', (req,res) => {
    db.query('SELECT * FROM empdata' , (err,results) => {
        if(err){
            console.log(err)
        }
        else{
            res.send(results)
        }
    })
})
app.listen(3001, () => {
    console.log('Server is running at port 3001')
})

Here in our post request, we are inserting all our values of our form to our database
table. Almost, there is nothing new after going through the above examples. Yes,
there are 2 arguments given i.e. (req,res). Basically, they are short form of request and
response. Request means that we are sending some data/information from our front
end to our backend. This data/information always goes in the form of requests
whether they are get or post request. It’s up to you.
Similarly, below is our get request. With this request, we are showing the data present
in our database table. We are extracting the data from our respective table using select
query.
Below that, app.listen function is used to bind and listen the connections on the
specified host and port.

MySQL:

OUTPUT:

CE301: Database Management Systems 73


DBMS

This is a form from where we are inserting new users to our database. Add Employees
button has a functionality that whenever we will fill the form and click the button, it
will generate a post request and send it to the server and those values will be stored in
the database (if valid). If the data is not valid, then the server will return an error
response.

LAB # 13

UNDERSTANDING NO-SQL DBMS


Objective: To get hands on implementation of Flutter project by using Firebase
Database.
Theory:

CE301: Database Management Systems 74


DBMS

Firebase is originally developed by Firebase inc and later acquired by Google. It


provides different kinds of services that help you to develop high-quality mobile and
web applications to grow your business. It is compatible with Web, iOS, Android, and
OS X clients. With Firebase, developers don’t need to worry about the backend
programming, Authentication, API development, database (real-time cloud-hosted
NoSQL database and cloud firestore), File storage, etc. Firebase provides all the
services with very efficient and fast performance.

Firebase is a full package that can help in developing your mobile or web applications
faster with fewer resources and more efficiency. Now, let’s look at some of the
services and use of it.

There are many services which Firebase provides, Most useful of them are:

 Cloud Firestore
 Cloud Functions
 Authentication
 Hosting
 Cloud Storage
 Google Analytics
 Predictions
 Cloud Messaging
 Dynamic Links
 Remote Config

Firebase is a full package that can help in developing your mobile or web applications
faster with fewer resources and more efficiency.

To get started with firebase we need to go to website https://firebase.google.com/

Then go to console:

CE301: Database Management Systems 75


DBMS

Flutter: Flutter is a free and open-source mobile UI framework created by Google


and released in May 2017. In a few words, it allows you to create a native mobile
application with only one codebase. This means that you can use one programming
language and one codebase to create two different apps (for iOS and Android).

Flutter consists of two important parts:

 An SDK (Software Development Kit): A collection of tools that are going to


help you develop your applications. This includes tools to compile your code
into native machine code (code for iOS and Android).

 A Framework (UI Library based on widgets): A collection of reusable UI


elements (buttons, text inputs, sliders, and so on) that you can personalize for
your own needs.
To develop with Flutter, you will use a programming language called Dart. The
language was created by Google in October 2011, but it has improved a lot over these
past years.

Dart focuses on front-end development, and you can use it to create mobile and web
applications.

If you know a bit of programming, Dart is a typed object programming language. You
can compare Dart's syntax to JavaScript.

Let’s get started!


We have a project on Flutter named “DevFolio” this is a portfolio project purely built
in flutter we have to host this web app to Firebase.

Web apps are supported on the stable channel in Flutter 2.0. In this lab, we’ll take a

look at deploying a web app to Firebase static hosting and front it with a custom

domain.

Step 1: Create a new project on firebase:


The first step is to create a project in firebase. Visit firebase.google.com and sign-
up if you haven’t already and go to console. Here, we will create a new project
and give it any name of our choice.

CE301: Database Management Systems 76


DBMS

Step 2: Creating flutter web app


In this step, we will create the web application of the flutter project we have already
prepared. I have made an interactive portfolio web app that changes the pages based
on the user’s input on navigation bar. To create the web application of the flutter
project we will use the following command ‘flutter build web‘. This will create a
light and smooth flutter web application n the build folder inside the web directory.
You can even check if there is any problem with the build or not by using this
command
 flutter run -d chrome –release

Step 3: Registering App


In this step, we will create a web instance in the firebase project that we have created
and register our web app and generate a name (URL) for the flutter web app.
Go to firebase > add app > select web icon >register app

CE301: Database Management Systems 77


DBMS

Selecting Web
App

Step 4: Adding Firebase SKD


Now we will add the firebase system development kit in our flutter app. It helps
firebase identify the web app, track its version, keep track of its usage. It is done by
adding two or three scripts in the body of the index.html page.

CE301: Database Management Systems 78


DBMS

After that add this generated script to flutter project file named index.html page.

Add The Following Generated Script In This File.


Step 5: Installing Firebase CLI
In this step, we will install a firebase command-line interface that lets us interact with
firebase and use its functionalities. It is done by running the below command in the
terminal:
 npm install -g firebase-tools

CE301: Database Management Systems 79


DBMS

Step 6: Deploying the app

This is the final step we will deploy our flutter web app to the firebase hosting. First,
we need to run the command ‘firebase login‘ to confirm we are connected with the
firebase. Then we will initialize the process by running the command ‘firebase inti‘.
And now we need to select a few options that you can see in the video below. And
after all the initializing steps are done then we will the command ‘firebase deploy‘ or
the one was given on the firebase website. This command will push all the files to the
hosting server and it will return us a URL to the web app we have successfully hosted.
And in this case, it was https://gfg-flutter-story.web.app/, you can check this out if
you want.

Firebase setup

Once the firebase CLI is installed, login using the command below.
$ firebase login

This would open up the browser to let you sign in to your google account. Once the

login is successful, you should see a message on the terminal:

✔ Success! Logged in as [email protected]

Next, initialize firebase hosting by running the following command in the root

directory of the flutter project.


$ firebase init hosting

You’ll be prompted to create a new project or pick an existing project if you want to

use an existing project.

Next, you’ll be prompted to pick the public directory of your web application that you

want to deploy. The default for a flutter web app build is build/web .

CE301: Database Management Systems 80


DBMS

This is what the interaction would look like:


? Please select an option: Use an existing project
? Select a default Firebase project for this directory: shiped-7b848 (shipantherproject)
i Using project shiped-7b848 (shipantherproject)? What do you want to use as your public
directory? build/web
? Configure as a single-page app (rewrite all urls to /index.html)? Yes

If you are running this in a git repository that points to Github remote, firebase CLI

would also prompt you to configure the Github actions for automatic deployment. You

can skip this, if you prefer.

Deploying the web application

You are now ready to build and deploy the web application.
$ flutter build web
Compiling lib/main.dart for the Web... 24.9s

Once the build is done, let’s publish the application to firebase hosting.
$ firebase deploy --only hosting=== Deploying to 'shiped-7b848'...i deploying hosting
i hosting[shiped-7b848]: beginning deploy...
i hosting[shiped-7b848]: found 30 files in build/web
✔ hosting[shiped-7b848]: file upload complete
i hosting[shiped-7b848]: finalizing version...
✔ hosting[shiped-7b848]: version finalized
i hosting[shiped-7b848]: releasing new version...
✔ hosting[shiped-7b848]: release complete✔ Deploy complete!Project Console:
https://console.firebase.google.com/project/shiped-hash/overview
Hosting URL: https://shiped-7b848.web.app

You can now navigate to the Hosting URLin your browser

CE301: Database Management Systems 81


DBMS

Flutter web app deployed to firebase hosting

Adding a custom domain to the application

Now that we have the application deployed to firebase, we’ll continue to setup a

custom domain for the web app. You can skip this if it does not apply to your case.

Binding a custom domain involves telling firebase about the domain, proving

ownership of the domain and then wait for SSL certificates to be issued.

CE301: Database Management Systems 82


DBMS

Let’s begin by telling firebase about the domain you’d like to host the web application

on. Navigate to the Hosting side panel on the Firebase console of your project. Select

“Add custom domain”

Click Add custom domain on the Hosting panel in Firebase Console

Add the domain name that you’d like to point to web application

Add the domain name

Click Continue and follow the instructions to setup the DNS for the domain. In this

step, add the two A records to the DNS. Usually, the DNS is managed differently for

different Domain registrars(eg: Go daddy, Google Domains, AWS Route 53, etc.).

You’ll need to follow instructions specific to your Domain registrar.

CE301: Database Management Systems 83


DBMS

Add the DNS records mentioned here to the DNS settings of your domain

Once the records are added, you can verify them via running a dig command
$ dig shipanther-test.bigpanther.ca A; <<>> DiG 9.10.6 <<>>
shipanther-test.bigpanther.ca A
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 54464
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0,
ADDITIONAL: 1;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;shipanther-test.bigpanther.ca. IN A;; ANSWER SECTION:
shipanther-test.bigpanther.ca. 3600 IN A
151.101.65.195
shipanther-test.bigpanther.ca. 3600 IN A
151.101.1.195;; Query time: 59 msec
;; SERVER: 192.168.67.67#53(192.168.67.67)
;; WHEN: Mon Mar 15 19:23:54 PDT 2021
;; MSG SIZE rcvd: 90

CE301: Database Management Systems 84


DBMS

At this point firebase would be able to verify the ownership of your


domain and you can navigate to https://shipanther-test.bigpanther.ca(this
should be your custom domain) to see the results. Please note that it can
take up to 24 hours for the DNS changes to propagate and for Firebase to
issue a valid SSL certificate for the domain.

Check that the domain validation has succeeded. Until it is done, SSL certificate
would not be issued and the browser would show an error like
NET::ERR_CERT_COMMON_NAME_INVALID. Check back in some time to
allow DNS propagation to finish.

Exercise:
Create your own portfolio and host it on firebase the flutter code is provided. You
have to make changes in the provided code so that you will able to make this code
your own attractive portfolio.

SAMPLE PORTFOLIO OF OUR STUDENT

CE301: Database Management Systems 85


DBMS

CE301: Database Management Systems 86


DBMS

These are the values that are inserted in the database and here we have
extracted these values using get request. Below Add Employees, there is a
button ‘Show Employees’ on which we have applied functionality to show the
data from database whenever clicked. Whenever we will insert the data using
the above form, data will be shown here automatically.

CE301: Database Management Systems 87

You might also like