Dms Lab Manual Updated
Dms Lab Manual Updated
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.
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 :
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:
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.
Step 4. Save your new table by selecting File > Save Table_1, as shown in Figure 1-4.
Your new table will appear under the Tables section, as depicted in Figure 1-6.
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:
You can now start entering the data directly into your table.
LAB TASK
1. Create below tables
LAB # 2
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.
SYNTAX
SELECT * FROM table_name Examples:
select * from bonus select
* from employee select *
Join column Emp_Name and Emp_Job column of Employee table having the
same data type by this query:
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
SELECT ENo, EName, Job, Sal AS 'Previous Salary', Sal * 0.25 AS increment,
Sal + Sal * 0.25 AS 'Current Salary' FROM Employee
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
Following point must be kept in mind when using the WHERE clause:
Using the WHERE clause, following query will retrieve details of all those employees
whose Emp_head number is 125:
Using DISTINCT keyword with our query, repeating records can be eliminated.
Head column from the Employee table will be retrieved and as used here without
DISTINCT keyword, all records will be displayed.
9. Using TOP-Clause
The TOP-Clause limits the rows retrieved from the query result.
SYNTAX:
Asterisk (*) sign again provides all the columns of the table, and column names
can be provided to restrict the number of columns retrieved as:
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
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.
You should try the following query and observe the result:
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‟.
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.
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
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.
select ename, job, sal from employee where ename not like 'j%'
Type the following query. It will show a department information such that
department name is sales and located in Lahore.
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.
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
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”.
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’.
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:
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:
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:
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
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.
This result could also have been achieved by using this query if the column order
is default:
Implicit Method: Omit the Column Name From the Column List
Explicit Method: Specify the NULL keyword or empty string (‘ ‘) in the values
list.
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:
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:
Syntax
INSERT INTO table(column_list)
Subquery
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.
Syntax
UPDATE <table name>
SET <column> = <value>
[WHERE condition
a. Consider the following query: Specific row(s) can be updated while using the
WHERE clause.
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.
Temp table has the same data as of the Employee table. You will be provided this
in the lab.
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.
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.
b. Consider the following query: All rows in the table will be deleted, if we
omit the WHERE clause.
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.
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.
Test different columns for ORDER BY clause by writing more queries yourself.
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.
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.
<query 1>
<set operator>
<query 2>
[ORDER BY <order_by_list>]
• 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.
• 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.
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).
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.
As an example for using EXCEPT, the following query returns locations that are
employee locations but not customer locations.
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.
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.
LAB TASKS:
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.
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
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:
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:
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:
• 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.
• 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.
• 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.
• 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.
Nonequi jo ins
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.
Cartesian Products
LAB TASK:
EmployeeDetail Table - EmployeeID,
FirstName,LastName,Salary,JoiningDate,Department,Gender
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.
LAB # 07
TASKS:
Consider a company database with the following data and execute the mentioned
statements using SQL queries.
TABLE 01
Employee
location
TABLE 03
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.
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
.
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.
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.
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
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.
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)
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":
We can also add a condition to the query. Now we want to see the total sale only for
the category "Beverages":
FROM table_name
WHERE condition
Now we want to add the "Category" column to the "Current Product List" view. We
will update the view with the following SQL:
Syntax
CREATE PROC procedure_name AS T-SQL statement(s)
Create a Stored Procedure
1. Consider the following query (stored procedure):
A stored procedure will be created that will show the details of all the employees
from the employee table whose department number is 20.
Syntax
EXECUTE procedure_name
Consider the following query which executes the EMP_20 stored procedure
(output is shown in figure):
EXECUTE EMP_20
Syntax
CREATE PROCEDURE procedure_name
@parameter_name <data type>
AS
T-SQL Statement(s)
Lab Task:
The following SELECT statement returns a list of products from products
table in the abc sample database:the p
SELECT
product_name,
list_price
FROM
production.products
ORDER BY
product_name;
LAB # 10
OBJECTIVE
Apply SQL Functions and User defined Functions in SQL.
THEORY
Syntax
SELECT UPPER(column_name) FROM table_name;
Syntax
SELECT LOWER(column_name) FROM table_name;
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;
Example
The MAX() function returns the largest value of the selected column.
Syntax
SELECT MAX(column_name) FROM table_name;
Example
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;
Example
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.
Syntax
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:
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:
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.
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.
3. DATEPART()
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.
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:
7. MONTH()
8. YEAR()
String Functions
1. ASCII()
Returns the ASCII code value of the leftmost character of a character expression.
Syntax
ASCII ( character_expression )
Example
SELECT ASCII('AB')
SELECT ASCII('BC')
2. LEFT()
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()
Syntax
RIGHT(string, length)
Example
SELECT RIGHT('Md. Marufuzzaman',5)
4. LTRIM()
Example
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.
String Specifies the substring with which to replace the located substring.
Example
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.
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
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 following SELECT statement calls the function. Note that the two-part name
(owner.object_name) is required when calling this function.
When the SELECT is executed, the input parameters 1 and 98 are added together and
the sum 99 is returned.
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.
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:
• 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.
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.
A UDF can be deleted from the SSMS IDE or using the following command.
SYNTAX
DROP udf_name
drop function
AddEmp
LAB # 11
OBJECTIVE
Apply sub queries and correlated subqueries in SQL. Also study Triggers and Types
of Triggers.
THEORY
Note
WHERE clause
Most often, the subquery will be found in the WHERE clause. These subqueries are
also called nested subqueries.
For example:
(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:
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.
FROM clause
A subquery can also be found in the FROM clause. These are called inline views.
For example:
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 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.
In the loosest sense, your query syntax will look something like one of these two
syntax templates:
Or:
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:
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:
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:
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:
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.
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.
IF UPDATE(Name)
BEGIN
SET @Action = 'Updated Name'
END
IF UPDATE(Country)
BEGIN
SET @Action = 'Updated Country'
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.
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.
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
The following error message shown when record with CustomerId 2 is deleted.
LAB # 12
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.
return (
<div className="hello_world">
<h1> Hello, world! </h1>
</div>
);
};
// Getting the path request and sending the response with text
app.get('/', (req,res) => {
res.send('Hi, your request has been received');
});
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() {
}
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>
);
}
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)
}
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:
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
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.
Then go to console:
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.
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.
Selecting Web
App
After that add this generated script to flutter project file named index.html page.
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
Next, initialize firebase hosting by running the following command in the root
You’ll be prompted to create a new project or pick an existing project if you want to
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 .
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
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
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.
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 the domain name that you’d like to point to web application
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.).
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
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.
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.