Data Base Administration Level IV: Shashemene Poly Technique College

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Database administration level IV

SHASHEMENE POLY TECHNIQUE COLLEGE

Data base Administration


Level IV

Unit of Competence: Use Advanced Structured Query Language

Module Title: Using Advanced Structured Query Language

TTLM Code: ICT DBA4 06 0710

Learning outcomes:
LO1: Write advanced SQL statement to retrieve and sort data

LO2: Write ADVANCED SQL statements that use functions


LO3: Write ADVANCED SQL statements that use aggregation and
filtering

Page 1
Database administration level IV

Definition of a Database
A database can be defined as a shared collection of interrelated data designed to meet the varied information
needs of an organisation.
Database Systems
The database approach emphasizes sharing of information across the whole rganization. This approach focuses
on the things or entities that an organization must manage. That is staff, customers, sales, products and
relationship between them(customers buy products). Applications are then developed that use such structures
according to sets of rules, called business rules.
Metadata: is the information about the way an organization views entities and associations between them.
Metadata includes record type definitions and field definitions as well as the associations between record types
and any other information relevant to the data model. Metadata is stored and maintained in the data dictionary.
Functions of the DBMS
One advantage of the database approach is that the Database Management System incorporates a number of
functions that make it easier to manage and manipulate the data.
1. Data dictionary management: All definitions of data, relationships between data, information on keys and
indexes are all stored in the data Dictionary.
2. Data storage management: Provides storage for data, related data entry screens, report definitions, validation
rules and application code
3. Data transformation and presentation: DBMS transforms the data entered by users into the physical
structures that are required for storage.
4. Security management: Security rules protect the data from unauthorized use. Users are given access only to
specified portions of the data. Manipulation of the data by users is also controlled.
5. Multiuser Access control: DBMS provides complex structures that allow multiple users to access the database
concurrently. This must be done without affecting the integrity or the consistency of the data.
6. Backup and recovery: DBMS provides special facilities that allow for periodic backups of the database and
run routines that restore the database to a usable state after a failure.
7. Data integrity management: DBMS stores and enforces integrity rules. These may be rules specified by
relationships between data.
8. Database access Languages: DBMS provides access via a query language
9. Database communication interfaces: DBMS may provide special communications facilities that allow the
user access across the organizations network.
Types of Database
There are two types of generic database architectures
1. Centralized Databases
 Have all data located at a single site.
 Allow remote sites to access the database by using communications equipment
 Provide a great deal of control over accessing and updating data.
 Depend on the availability of data at the central site.
2. Distributed Databases: Are single logical databases that are spread physically across computers in multiple
locations.
 May be of a number of types.
 Have the advantage of increased independence of data
 Allow increased flexibility in that different computers may run the same or different
 Application programs and hold different data. Therefore they can be tailored to an organization's needs.
 Optimally need similar operating systems and compatible DBMS.
 Are more difficult to administer.
 Are complex to design and more expensive to implement than centralized systems.
Page 2
Database administration level IV

 Provide a greater security risk than centralized systems.


Introduction to Database Models
Database Design
When developing information systems, a number of standard steps or phases, known collectively as the Systems
Development Life Cycle (SDLC) are followed. Phases and terminology may differ slightly from one design
methodology to another, but because an organization's database is part of its information system, database
design is typically a fundamental component within the SDLC.
Database Models: Database models are grouped into two categories:
1. Conceptual Models: What is represented in the database?
Conceptual model illustrates what data will be stored in the database, the structure of the data, as well as the
associations or relationships between the data. Conceptual models are independent of any specific database
management system and are therefore not concerned with implementation issues.

Conceptual models include:


 Entity Relationship Model
 Semantic Object Model
2. Implementation Model: How the data structures are implemented?
Once the conceptual model has been designed, it is then converted to the underlying database model of the
database management system to be used. For example, if the selected database management system was
Oracle, then the conceptual model would be adapted to fit the structures of a relational model.
This phase of database design is also referred to as logical database design.
Implementation models include:
 Hierarchical Model
 Network Model
 Relational Model
Normalization: is the process of analyzing the design of a Relational Database to identify and correct any
problems, referred to as anomalies, within the design. The process works through a set of formal steps, called
Normal Forms, to assign attributes to tables. Normalization should reduce data redundancy and eliminate
anomalies in the resulting tables. The process of Normalization is based on analyzing the dependencies that
exist between the attributes and determining the keys and key combinations for that set of attributes.
Normalization can be considered a "Bottom up" process and can be applied independently of Entity-Relation
analysis. In other words we can start with the attributes from a form or report and achieve a set of normalized
tables without drawing an E-R diagram first.
Structuring Tables:
 Insertion Anomaly
 Deletion Anomaly
 Update Anomaly
The aim in the process of developing a database is to achieve a set of well-structured tables (relations). A well-
structured table can be defined as one that has minimum redundancy. Furthermore any modification of the table
(insert, delete, update) results in a minimum number of errors or inconsistencies. These inconsistencies are
called anomalies.

First Normal Form: A relation is said to be in First Normal Form (1NF) if and only if it contains no repeating
groups.

Page 3
Database administration level IV

Second Normal Form: normal form and all non key attributes are dependant on the whole key. That is all
partial dependencies are removed. An analysis of the dependencies of the Student table used previously shows
the following
 Student Number è name, address, phone, course
 Module Code èteacher, teacher contact, fee
 Student Number, Module è Day
Third Normal Form: normal form and there are no transitive dependencies existing. Transitive dependencies
are dependencies between two non key attributes.
Teacher è teacher contact
BCNF(Boyce Codd Normal Form: Usually tables that are in Third Normal Form are already in Boyce Codd
Normal Form. A table is in BCNF if every determinant is a candidate key
Fourth Normal Form: normalization occurs under specific conditions where a data instance has two or more
sets of data values associated with it. A table is in Fourth Normal Form if it is already in Third Normal Form
and it contains no multivalued dependencies.
Fifth Normal Form: Fifth Normal Form deals with with Join Dependencies. Most of the textbooks regard Fifth
Normal Form as dealing with fairly obscure anomalies and the definition quite complex. For this reason 5NF is
not dealt with in any detail.

LO1: Write advanced SQL statement to retrieve and sort data

Sorting (Ordering the Result Set)


Data in a SQL table takes the form of an unsorted list. In other word, If no order by clause exists, SQL Server
will return the rows in the order in which they are fetched. If a table has a clustered index, the rows will likely
be returned according to the clustered index. Other logical operations within the query may sort the data to
support the logical operation. SQL can sort data (query result) by multiple techniques:
Specifying the Order by Using Column Names
The simplest way to sort the result set is to completely spell out the order by columns which Used to display the
query based on order either ascending or descending like as:
SELECT * from table_name ORDER BY column_name asc /desc
Specifying the Order by Using Expressions
In the case of sorting by an expression, the entire expression can be repeated in the order by clause. This does
not causes a performance hit because the SQL Server Query Optimizer is smart enough to avoid recomputing
the expression:
SELECT column 1 + ‘, ‘ + Column 2 FROM table_name ORDER BY Column 1+ ‘, ‘ + Column 2
Specifying the Order by Using Column Aliases
Alternatively, a column alias may be used to specify the columns used in the order by clause. This is the
preferred method for sorting by an expression, because it makes the code easier to read. Note that this example
sorts in descending order rather than the default ascending order:
SELECT column 1 + ‘, ‘ + Column 2 as column 3 FROM table_name ORDER BY column 3 asc
An alias is allowed in the order by clause, but not the where clause, because the where clause is logically
executed near the beginning of the query execution, whereas the order by clause is the last logical operation and
follows the assembling of the columns and aliases.
Specifying the Order by Using Column Ordinal Position

Page 4
Database administration level IV

The ordinal number of the column (column position number) can be used to indicate the order by columns. But
If the columns are changed at the beginning of the select statement, the order by will function differently. Use
the ordinal number to specify the sort for complex union queries.
SELECT column 1 + ‘, ‘ + Column 2 as column 3 FROM table_name ORDER BY 1 asc

Order by and Collation


SQL Server’s collation order is vital to sorting data. Besides determining the alphabet, the collation order also
determines whether accents, case, and other alphabet properties are considered in the sort order. For example, if
the collation is case sensitive, the uppercase letters are sorted before the lowercase letters. The following
function reports the installed collation options and the current collation server property:
SELECT * FROM ::fn_helpcollations()
Ranking
Top
SQL Server will return all the rows from the select statement by default. The optional top predicate tells SQL
Server to return only a few rows (either a fixed number or a percentage), based upon the options specified, Top
works hand-in-hand with order by. It’s the order by clause that determines which rows are first. If the select
statement does not have an order by clause, the top predicate still works by returning an unordered sampling of
the result set.
SELECT TOP 3 PERCENT * from table_name (return 3% of total data in an unordered list)
SELECT TOP 3 PERCENT * from table_name ORDER BY column2 DESC(return 3% of total data ordered
column2 desc)
SELECT TOP 3 * from table_name (return 3 row from total data in an unordered list)
The query looks clean and the result looks good, but unfortunately it return wrong result if data sorted by
column has the same values. In other word, if the selection cannot include all the data with the same value and
only select one or two of them even if they have the same value. The “with ties” option solves this problem.
With Ties Option
It allows the last place to include multiple rows if those rows have equal values in the columns used in the order
by clause. The following version of the preceding query includes the with ties option and correctly results in
number of rows from a top 3 predicate:
SELECT TOP 3 WITH TIES * from table_name order by column_name asc/desc (for example the query
return 5 row if the 3rd row and the remaining 2 row have the same values for selected column)
”Select with Criteria(Where clause)
Sometimes we want to retrieve data based on certain conditions. To do this, we use the WHERE keyword. The
where conditions restrict the rows that will be returned in the result set. The conditions can refer to the data
within the tables, expressions, built-in SQL Server scalar functions, or user-defined functions. The “where”
conditions can also make use of several possible comparison operators and wildcards either in simple condition
or in compound condition.
The syntax is: SELECT "column_name" FROM "table_name" WHERE "condition";
Compound conditions are made up of multiple simple conditions connected by AND or OR. The syntax for a
compound condition is:
SELECT "column_name" FROM "table_name" WHERE "simple condition" { [AND|OR] "simple ondition"}+;
The { }+ means that the expression inside the bracket will occur one or more times. [AND|OR] means that
either AND or OR can be used. In addition, we may use the parenthesis sign ( ) to indicate the Project of the
condition.
Operators
Arithmetic Operator

Page 5
Database administration level IV

Description Operator
Modulo %
Addition +
Substraction -
Product *
Division /
Comparison Operator
The where conditions filter the output of the from clause and restrict the rows that will be returned in the result
set. The where conditions can also make use of several possible comparison operators and wildcards. addition,
we can also specify multiple where conditions with Boolean and, or, and not operators.
Standard Comparison Operators
Description Operator Example
Equals = Quantity = 12
Greater than > Quantity > 12
Greater than or equal to >= Quantity >= 12
Less than < Quantity < 12
Less than or equal to <= Quantity<= 12
Not equal to <> , != Quantity <> 12 , Quantity != 12
Not less than !< Quantity !< 12
Not greater than !> Quantity !> 12
In addition to the standard comparison operators, SQL provides four special comparison operators: between, in,
like, and is.
Boolean Operator
Boolean And
A Boolean “and” (represented by the ampersand character, &) returns a value of true only if both inputs are
true. If either or both are false, the “and” will return a value of false.
Boolean Or
The Boolean “or” operator, the vertical pipe character (|), returns true if either input is true.
Boolean Exclusive Or
The “exclusive or” bitwise operator, the carat (^), returns a value of true if either input is true, but not if both are
true. Using it is the same as “or”ing two “and”s, each with a “not” on one input. While that’s simple to build in
digital electronics, in code the operator is much easier to use.
Bitwise Not
The last bitwise operator, denoted by the tilde (~), is a bitwise “not” function. Traditionally, the “not” operates
on a single bit and is used to alter the input of an “or” or “and” digital gate. This bitwise “not” is a little
different. The “not” performs a logical bit reversal for every bit in the expression. The result depends on the
data length of the expression.
The bitwise “not” is not suitable for use with Boolean expressions such as if conditions.
Between Search Condition
The between search condition tests for values within a range. The range can be deceiving, however, because it
is inclusive. For example, between 1 and 10 would be true for 1 and 10. When using the between search
condition, the first condition must be less than the latter value because in actuality, the between search condition
is shorthand for “greater than or equal to the first value, and less than or equal to the second value.” . If we wish
to exclude 'value1' and 'value2' but include everything in between, we need to change the query to the
following:

Page 6
Database administration level IV

SELECT "column_name" FROM "table_name" WHERE ("column_name" > 'value1') AND ("column_name" <
'value2');
The between search condition is commonly used with dates.
SELECT * from table_name WHERE column BETWEEN ‘firstdate’ AND ‘nextdate’;
In Search Condition
The in search condition is similar to the equals comparison operator, but it searches for an exact match from a
list. If the value is in the list, the comparison is true. For example:
SELECT Column1,column2 FROM table_name WHERE column1 IN (‘value1’, ‘value2’);
The in search condition is the equivalent of multiple equals comparisons with “or” operator together:
SELECT Column1,column2 FROM table_name WHERE column1= ‘value1’ or column1=‘value2’
Like Search Condition
The like search condition uses wildcards to search for patterns within a string. The wildcards, however, are very
different from the MS/DOS wildcards.
Description SQL wildcar Example
Multiple Character % Like ‘A%’
Single Character - Like ‘a_’
Match in Range of Characters [] Like ‘[a-f]’ or like ‘[abcdef]’
Match not in Range of Characters [^] Like ‘[^g-m]’ or like ‘[^ghijklm]’
The following query finds any column values beginning with a letter between a and d, inclusive:
SELECT column_name FROM table_name WHERE column LIKE ‘[a-d]%’;
Multiple Where Conditions
You can combine multiple where conditions within the where clause using the Boolean logical operators: and,
or, and not. As with the mathematical operators of multiplication and division, an order of precedence exists
with the Boolean logical operators: and comes first, then or, and then not:
SELECT column1, column2 FROM table1 WHERE Column2 LIKE ‘A%’ OR Column1 BETWEEN ‘value1’
AND ‘value2’ AND Column2 LIKE ‘%G%’;
SELECT column1, column2 FROM table1 WHERE (Column2 LIKE ‘A%’ OR Column1 BETWEEN ‘value1’
AND ‘value2’) AND Column2 LIKE ‘%G%’;
While the two preceding queries are very similar, in the first query the natural order of precedence for Boolean
operators caused the “and” to be evaluated before the “or”. The second query used parentheses to explicitly
dictate the order of the Boolean operators.
Boolean Case:The Boolean form of case is more flexible than the simple form in that each individual case has
its own Boolean expression. Example:
SELECT CASE
WHEN condition THEN ‘expression ’
The Boolean case expression can handle complex conditions, including Boolean and and or operators.
Working with Nulls
The relational database model represents missing data using null. Technically, null means “value unknown.” In
practice, null can indicate that the data has not yet been entered into the database, or the column does not apply
to the particular row. Since, null is unknown; the result of any expression that includes null will also be
unknown.
Since it devastating/ disturb the effect on expressions, some developers detest the use of nulls. so that nulls are
never permitted and column defaults supply surrogate nulls (blanks, 0s, or “n/a”) instead. But Nulls are valuable
in a database because they provide important information about the status of the data, so it’s worth your while to
write code that checks for nulls and handles them appropriately.
Testing for Null

Page 7
Database administration level IV

Because null is unknown, null is not even equal to null. For example, if the value of xx is unknown and the
value of yy is also unknown, then it’s logically impossible to prove that they have equal value. Because the =
operator can’t check for nulls. SQL includes a special operator, “is”, to test for null values. The “is” null SQL
search condition is used to test for a null value. The “is” search condition may be used in the select statement’s
where clause to locate rows with null values. The following query retrieves data from table1 where column3
consist null value.
SELECT * from table1 WHERE column3 IS NULL ORDER BY column2
The “is” operator may be combined with not to test for the presence of a value by restricting the result set to
those rows where column3 is not null:
SELECT * from table1 WHERE column3 IS not NULL ORDER BY column2
Handling Nulls
Nulls require special handling when used within expressions, and SQL includes a few functions designed
specifically to handle nulls. Isnull() and coalesce() convert nulls to usable values, and nullif() will create a null
if the specified condition is met.
IsNull() Function
The most common null-handling function is isnull(), which is different from the is null search condition. This
function accepts a single column or expression, and a substitution value. If the source is a valid value (not null),
the isnull() function passes the value on. However, if the source is a null, the second parameter is substituted for
the null, as follows:
Select source_expression, isnull(source_expression, replacement_value) from table_name
Functionally, isnull() is the same as the following case expression:
Select source_expression, CASE
WHEN source_expression IS NULL THEN ‘replacement_value’
ELSE source_expression
END AS ISNULL from table_name
For example the following code will substitute the string (‘none’) for a null in column3:
SELECT column3, isnull(column3,’none’) from table1
If the row has a value in the column3, that value is passed though the isnull() function untouched. However, if
the column3 is null for a row, then the null is handled by the isnull() function & converted to the value ‘none’.
The isnull() and nullif() functions are T-SQL specific and are not ANSI standard SQL.
Coalesce()
Coalesce() is derived from the Latin words co + alescre, which mean to unite toward a common end, to grow
together, or to bring opposing sides together for a common good. Coalesce() is excellent for merging messy
data. For example, when a table has partial data in several columns, the coalesce() function can help pull the
data together. It accepts a list of expressions or columns and returns the first non-null value, as follows:
Coalesce(expression, expression, ...)
SELECT column3, coalesce(column3, column4 ) from table1.
Functionally, coalesce () is the same as the following case expression:
Select expression (column), CASE
WHEN expression1 IS NOT NULL THEN expression1
WHEN expression2 IS NOT NULL THEN expression2
WHEN expression3 IS NOT NULL THEN expression3
END AS COALESCE from table_name
Nullif()
Sometimes a null should be created in place of surrogate null values. If a database is polluted with n/a, blank, or
– values where it should contain nulls, you can use the nullif() function to replace the inconsistent values with

Page 8
Database administration level IV

nulls and clean the database. The nullif() function accepts two parameters. If they are equal, it returns a null;
otherwise, it returns the first parameter.
select column_name, nullif(column_name,'')nullcolumn from table_name
Functionally, nullif() is the same as the following case
The following case code will convert any blanks with the following blank value in column_name into nulls.
select column_name, CASE
WHEN column_name = ' ' THEN 'Null'
WHEN column_name = 'blank' THEN 'Null'
WHEN column_name ='n/a' THEN 'Null'
end as nullif from table_name
Join
In relational algebra, a join is the multiplication of two data sets followed by a restriction of the result so that
only the intersection of the two data sets is returned. The whole purpose of the join is to horizontally merge two
data sets (usually tables, but it could be a subquery, view, common table expression, or user-defined function)
and produce a new result set from the combination by matching rows in one data source to rows in the other
data source. Sometimes we have to select data from two or more tables to make our result complete. In these
cases, we have to perform a join. In the Structured Query Language (SQL), there are three common types of
joins: inner, outer, and cross.
Join Types
Inner Join
The inner join was originally called a natural join by E. F. Codd. The inner join returns only those rows that
represent a match between the two data sets. It extracts only data from the inner portion of the intersection of
the two overlapping data sets (finds the intersection between the two tables). This is the most common type of
join used, and is considered as the default join type. The join example below takes all the records from table A
(in our case, employees) and finds the matching record(s) from table B (Projects). If no match is found, the
record from A is not included in the results. If multiple results are found in B that match the predicate then one
row will be returned for each (the values from B will be repeated).

Employee: Project
EID FName
01 PID
Hansen EID Pname
02 221
Svendson 01 Software
331 02 Networking
03 Svendson
04 441
Pettersen 03 Internet

E.g.1 Who works on a software development?


SELECT Employee.FName FROM Employee, Pname WHERE Employee.EID=Project.EID AND
Project.Pname='software'
In addition to using dot to join tables by inner join, we can also use the JOIN keyword, like this:
Syntax:
SELECT field1, field2, field3 FROM first_table INNER JOIN second_table ON first_table.keyfield =
second_table.foreign_keyfield
The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that
do not have matches in Projects, those rows will not be returned.
Outer Join

Page 9
Database administration level IV

An outer join extends the inner join by adding the nonmatching data from the left or right data set. Outer joins
solve a significant problem for many queries by including all the data regardless of a match. If we are interested
in selecting elements in a table regardless of whether they are present in the second table we need to use the
SQL OUTER JOIN command. Outer joins are subdivided further into left outer joins, right outer joins, and full
outer joins.
Right outer join
In an right outer join, all rows will be selected from the second table, regardless of matching row on the first
table mentioned in the SQL query. It returns all the rows from the second table (Projects), even if there are no
matches in the first table (Employees). It returns all the values from right table + only matched values from left
table.
Syntax:
SELECT fields FROM first_table Right outer JOIN second_table ON first_table.keyfield =
second_table.foreign_keyfield.
Left outer join
In left outer join, all rows will be selected from the first table, regardless of matching row on the second table
mentioned in the SQL query. In other word, it returns all the rows from the first table (Employees), even if there
are no matches in the second table (Projects). It returns all the values from First (left) table + only matched
values from Second (right) table.
Syntax:
SELECT fields FROM first_table LEFT outer JOIN second_table ON first_table.keyfield =
second_table.foreign_keyfield.
Full outer joins
In an full outer join, all rows will be selected from both tables regardless of matching rows on both tables
mentioned in the SQL query.
SELECT fields FROM first_table full outer JOIN second_table ON first_table.keyfield =
second_table.foreign_keyfield.
Note: NULL is returned when there is no match value between tables.
Self-Joins
A self-join is a join that refers back to the same table. This type of unary relationship is often used to extract
data from a reflexive (also called a recursive) relationship, such as manufacturing databases with bill of
materials data (build-from-material to material) and human resource databases (employee to boss). Think of a
self-join as a table being joined with a temporary copy of itself. The key to constructing a self-join is to include
a second reference to the table using a named range or table alias. Once the table is available twice to the select
statement, the self-join functions much like any other join.
SELECT * FROM table1 where table1.pk=table1.fk (column that references Pk of the same table)
Cross Join
It is also called an unrestricted join. It is a pure relational algebra multiplication of the two source tables. A
cross join (also called a Cartesian join) is a join of tables without specifying the join condition. The query would
return all possible combination of the tables in the SQL query.
Each row in data set one is matched with every row in data set two. for example, if the first data source has five
rows and second data source has four rows, a cross join between them would result in 20 rows. This type of
result set is referred to as a Cartesian product.
SELECT column_name, column_name1 FROM table1 CROSS JOIN table2
Union
The union operation is different from a join. In relational algebra terms, a union is addition, whereas a join is
multiplication. Instead of extending a row horizontally as a join would, the union stacks multiple result sets into
a single long table.
Page 10
Database administration level IV

Syntax:
SELECT column1 FROM table1 union SELECT column1 FROM table2
These few rules must be followed when constructing a union query:
✦ The column names, or aliases, must be determined by the first select.
✦ Every select must have the same number of columns, and each lineup of columns must share the same data-
type family.
✦ Expressions may be added to the select statements to identify the source of the row so long as the column is
added to every select.
Relational algebra consists of eight relational operators:
Restrict: Returns the rows that meet a certain criterion
Project: Returns selected columns, or calculated data, from a data set
Product: Relational multiplication that returns all possible combinations of data between two data sets
Union: Relational addition and subtraction that merges two tables vertically by stacking one table above
another table and lining up the columns
Intersection: Returns the rows common to two data sets
Difference: Returns the rows unique to one data set
Join: Returns the horizontal merger of two tables, matching up rows based on common data
Divide: The inverse of relational multiplication, returns rows in one data set that match every row in a
corresponding data set
Union All
The purpose of the SQL UNION ALL command is also to combine the results of two queries together. The
difference between UNION ALL and UNION is that, while UNION only selects distinct values, UNION ALL
selects all values. The syntax for UNION ALL is as follows:
[SQL Statement 1] UNION ALL [SQL Statement 2];or
SELECT column1 FROM table1 union all SELECT column1 FROM table2
Intersect: An intersection union finds the rows common to both data sets. An intersection union query is
similar to an inner join, with every column participating in the on condition. However, an intersection union
query will see nulls as common and include the rows in the intersect, whereas an inner join will treat nulls as
different and not join two rows with null values.
Similar to the UNION command, INTERSECT also operates on two SQL statements. The difference is that,
while UNION essentially acts as an OR operator (value is selected if it appears in either the first or the second
statement), the INTERSECT command acts as an AND operator (value is selected only if it appears in both
statements). The syntax is as follows:
[SQL Statement 1] INTERSECT [SQL Statement 2]; or
SELECT column1 FROM table1 intersect SELECT column1 FROM table2
Lo2: Write ADVANCED SQL statements that use functions
Arithmetic Function
Modulo (%): returns only the remainder of the division.
Syntax: SELECT firstnumber % second number
Addition: sum two or more than two numbers. plus(+) is used for both mathematical addition and string
concatenation.
Syntax: SELECT firstnumber (string)+ second number(string)
Substraction: enable us to substract one number from the other. Hyphen is used for subtraction.
Syntax: SELECT firstnumber - second number
Multiplication: used to return the product of two or more numbers. The Star (*) is used for multiplication.
Syntax: SELECT firstnumber * second number

Page 11
Database administration level IV

Division: enable us to divide numbers. The backward Slash (/) operator is used for division.
Syntax: SELECT firstnumber / second number
String Function
Like most modern programming languages, T-SQL includes many string-manipulation functions:
Upper(str)
Returns the string str with all characters changed to uppercase according to the current character set mapping.
Select upper (column_name) from table_name
Lower(str)
Returns the string str with all characters changed to lowercase according to the current character set mapping.
Select lower (column_name) from table_name
Reverse(str)
Returns the string with the order of the characters reversed.
Select reverse (column_name) from table_name
Length(str)
Returns the length of the string measured in bytes.
Select len(column_name) from table_name
SubString(string, starting position, length): Returns a portion of a string. The first parameter is the string, the
second parameter is the beginning position of the substring to be extracted, and the third parameter is the length
of the string extracted:
SELECT SUBSTRING(‘abcdefg’, 3, 2)
Stuff(string, insertion position, delete count, string inserted): The inverse of substring(), the stuff() function
inserts one string into another string. The inserted string may delete a specified number of characters as it is
being inserted:
SELECT STUFF(‘abcdefg’, 3, 2, ‘123’)
SELECT STUFF(STUFF(‘123456789’, 3, 0, ‘-’), 7, 0, ‘-’)
CharIndex(search string, string, starting position): Returns the character position of a string within a string:
SELECT CHARINDEX(‘c’, ‘abcdefg’, 1)
Wild-car
To match values on a string pattern we will need to employ the concept of wildcard. In SQL, there are two
wildcards:
 % (percent sign) represents zero, one, or more characters.
 _ (underscore) represents exactly one character.
Wildcards are used with the LIKE keyword in SQL. LIKE is a keyword that is used in the WHERE clause.
Basically, LIKE allows you to do a search based on a pattern rather than specifying exactly what is desired (as
in IN) or spell out a range (as in BETWEEN).
Syntax: SELECT "column_name" FROM "table_name" WHERE "column_name" LIKE {PATTERN};
Examples:
 'A_Z': All string that starts with 'A', another character, and end with 'Z'. For example, 'ABZ' and 'A2Z'
would both satisfy the condition, while 'AKKZ' would not (because there are two characters between A and
Z instead of one).
SELECT * FROM table_name WHERE column_name LIKE 'A_Z';
 'ABC%': All strings that start with 'ABC'. For example, 'ABCD' and 'ABCABC' would both satisfy the
condition.
SELECT * FROM table_name WHERE column_name LIKE 'ABC%’;
Concatenation

Page 12
Database administration level IV

Sometimes it is necessary to combine together (concatenate) the results from several different fields. In such
case we concatenate the fields or columns together by using plus (+) sign.
Syntax: SELECT columns , column1 + ' ' + column2 FROM table_name condition(optional) or
SELECT columns , column1 + column2 FROM table_name condition(optional)
Mathematical function
Numeric Function
SQL numeric functions are used primarily for numeric manipulation and/or mathematical calculations.
SQRT :SQL SQRT function is used to find out the square root of any number. You can Use SELECT statement
to find out square-root of any number as follows:
Syntax: select sqrt (number) or select sqrt(column_name) from table_name
Cosine: Returns the cosine of passed numeric expression. The numeric expression should be expressed in
radians. Syntax: select cos (number)
ABS: Returns the absolute value of numeric expression. Syntax: select abs (number)
Tangent: Returns the tangent of numeric expression expressed in radians. Syntax: select tan (number)
LOG() :Returns the natural logarithm of the passed numeric expression. Syntax: select log (number)
Sine: Returns the sine of numeric expression given in radians. Syntax: select sin (number)
Power: Returns the value of one expression raised to the power of another expression.
Syntax: select power(base number, power number)
Data-Time Functions
Databases must often work with date-time data, and SQL Server includes several useful datetime functions.
SQL Server stores both the data and the time in a single data type. T-SQL includes two functions to return the
current datetime:
GetDate(): Returns the current server date and time to the nearest three milliseconds.
GetUTCDate(): Returns the current server date converted to Greenwich Mean Time to the nearest three
milliseconds. This is extremely useful for companies that cross time boundaries.
The following four SQL Server date-time functions handle extracting or working with a specific portion of the
date or time stored within a datetime column:
DateName(date portion, date): Returns the proper name for the selected portion of the datetime value (the
portions for datename() and datepart()):
SELECT DATENAME(Year, GetDate()) as Year (return the cuttent year as year)
Datetime Portions Used by Date Functions
Portion Abbreviation
Year yy, yyyy
Quarter qq, q
Month mm, m
DayofYear dy, d
Day dd, d
Week wk, ww
Weekday dw
Hour hh
Minute mi, n
Second ss, s
Millisecond ms
NB: SQL Server does not include a date only data type, but many applications require only the date. To avoid
query confusion, strip off the time data and store only the date using a trigger

Page 13
Database administration level IV

Getdate Function
The GETDATE function is used to retrieve the current database system time in SQL Server. GETDATE
function is most useful when we need to record the time a particular transaction happens. Its syntax is
GETDATE( ). GETDATE does not require any argument.
Example:
SELECT GETDATE( ); it return the current date and time on the computer (sql server).
Aggregate Functions : The basic gist of an aggregate query is that instead of returning all the selected rows,
SQL Server returns a single row of computed values that summarizes the original data set.
The types of calculations range from totaling the data to performing basic statistical operations. The aggregate
functions occur following the from clause and the where filters. This means that the data can be asse mbled and
filtered prior to being summarized without having to use a subquery. Since, we deals with numbers, we have to
do math on those numbers, such as summing, subtracting, divition, average, etc. in other word SQL has several
arithematic functions, and they are:
The syntax is: SELECT "function type" ("column_name") FROM "table_name";
Average
It displays the average of the selected column if its data type is numeric.
SELECT AVG("column_name") FROM "table_name";
Count
This allows us to COUNT up the number of row in the table.
SELECT COUNT("column_name") FROM "table_name";
COUNT and DISTINCT can be used together in a statement to retrieve the number of distinct entries in a table.
SELECT COUNT (DISTINCT column_name) FROM table_name
MAX Function
Used to find the maximum value in a column.
SELECT MAX ("column_name") FROM "table_name";
MIN Function
Used to find the minimum value in a column.
SELECT MIN ("column_name") FROM "table_name";
Sum Function
It is used to calculate the total for a column.
SELECT SUM("column_name") FROM "table_name";

Page 14
Database administration level IV

LO3: Write ADVANCED SQL statements that use aggregation and filtering
Group by
Aggregate functions are complemented by the group by function, which automatically partitions the data set
into subsets based upon the values in certain columns. Once the data set is divided into subgroups, the aggregate
functions are performed on each subgroup.
The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at least
one arithmetic operator appears in the SELECT statement. When that happens, we need to GROUP BY all the
other selected columns, i.e., all columns except the one(s) operated on by the arithmetic operator.
SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1";

Sort aggregated data


Having Clause
Used to limit the output based on the corresponding sum (or any other aggregate functions). Instead of using the
WHERE clause in the SQL statement, though, we need to use the HAVING clause, which is reserved for
aggregate functions. The HAVING clause is typically placed near the end of the SQL statement, and a SQL
statement with the HAVING clause may or may not include the GROUP BY clause.

Page 15
Database administration level IV

SELECT ["column_name1"], Function("column_name2") FROM "table_name" [GROUP BY


"column_name1"] HAVING (arithmetic function condition);
Note: We may select zero, one, or more columns in addition to the aggregate function. If we select zero column,
there is no need for the GROUP BY clause.
Self Check

Table Employee
Column Name

EID

Name

Salary

Use the above table (Employee) to answer the following questions.


1. Which SQL statement would you use to select all Employees whose Name starts with 'A'?
A. Select eid, name from employee where name like 'a';
B. Select eid, name from employee where name in 'a';
C. Select eid, name from employee where name like 'a%';
D. Select eid, name from employee where name like '%a';
2. Which SQL statement allows you to sort all Employees by Salary, from the highest Salary to lowest Salary?
A. Select eid, name, salary from employee Project by salary desc;
B. Select eid, name, salary from employee Project by salary asc;
C. Select eid, name, salary from employee sort by salary asc;
D. Select eid, name, salary from employee sort by salary desc;
3. Which SQL statement allows you to find the highest Salary from the table EMPLOYEE?
A. Select eid, name, max(salary) from employee; C. Select max(salary) from employee;
B. Select maximum(salary) from employee; D. Select salary from employee Project by salary desc;
4. Which SQL statement allows you to find all employees Salary between 4000 and 7000?
A. Select eid, name, salary from employee having salary between 4000 and 7000;
B. Select eid, name, salary from employee having salary is between 4000 and7000;
C. Select eid, name, salary from employee where salary between 4000 and 7000;
D. Select eid, name, salary from employee where salary is between 4000 and 7000;
Stored Procedures
The primary purpose of client/server development is to move the processing as close to the data as possible.
Moving data processing from a client application to the server reduces network traffic and improves both
performance and data integrity. One of the most popular methods of moving the processing closer to the data is
developing stored procedures.
An application can communicate with SQL server in two ways
I. you can code the application to send the T-SQL statement from the client to SQL server
II. Creating a stored procedure which are stored and run at the server
If the T-SQL statement sent from the client application to the server, the statement will be sent across the
network and recompiled by the SQL server each time they are run.
Page 16
Database administration level IV

In the other way if you used stored procedure, you can execute the stored procedure by calling it from the
application with one statement. Therefore, when several T- SQL statements are needed to perform a task or
when a statement is processed frequently, using stored procedure can reduce network traffic by reducing the
sending of each statement from the client to the server through network.
A stored procedure is a set of SQL commands that can be compiled and stored in the sql server. It is
collection of T-SQL statement that the SQL server compiles in to single execution plan. The plan is stored in
the procedure cache area of the memory when the stored procedure is 1 st executed so that the plan can be used
repeatedly without the need to recompile it again when the procedure is called. Once this has been done, clients
don't need to keep reissuing the entire query but can refer to the stored procedure. This provides better
performance because the query has to be parsed only once, and less information needs to be sent between the
server and the client.
It differs from ordinary SQL statements and from batches of SQL statements in that they are precompiled. The
first time you run a procedure, SQL Server's query processor analyze it and prepare an execution plan that is
ultimately stored in a system table. The subsequent execution of the procedure is according to the stored plan.
Stored procedures are extremely similar to the constructs seen in other programming languages.
Types of Procedure
There are three kinds of stored procedure
I. System stored procedures
All stored procedures that SQL Server provides start with "sp_" and "xp_" (extended stored procedures). If you
try to call a stored procedure that starts with "sp_" SQL Server will first search the MASTER database before
searching the current database. You use the system procedure sp_helptext to list the definition of a procedure,
and sp_help to display control information about a procedure. The system procedures sp_helptext and sp_help
are used to list information about other database objects, such as tables, rules, and defaults, as well as stored
procedures.
 Supplied by the SQL server
 Use to manage SQL server and display info. About the DB and client
 Is a kind of procedure having the prefix SP_ in the master database and can be executed from any
database.
Syntax sp_helptext procedure_name (object name)
sp_help procedure_name (object name)
e.g.1. sp_helptext student
2. sp_help student
Eg. sp_rename 'students', 'trainees' (rename students table to trainees)

II. Extended stored procedures


 Are dynamic link libraries (DLLS) the SQL server can dynamically load and execute
 can reference functionality external to SQL Server, such as calling routines and functions in remote
libraries and processes compiled
 run directly in the address space of SQL Server
 They are executed in the same manner as the other two types of stored procedures.
 Have prefix XP_
Eg. xp_readerrorlog (display log information)
III. Simple user defined
 Created by the user and customized to perform whatever task the user wants.
Page 17
Database administration level IV

The syntax to define a new procedure is:


Create Procedure [pocedure_name]
As
Code (expression)
E.g.1
Create Procedure courselist
As select * from course
A stored procedure can be executed by typing its name or using the EXECUTE statement. The syntax to
execute our stored procedure is:
Execute [procedure name][parameters].
e.g execute courselist
Creating a Stored Procedure with Input Parameters
E.g.2
Create procedure proc1 (@p1int, @p2 char (20), @p3 char (5))
AS
Insert into course Values (@p1, @p2, @p3)
Execute proc1 ‘01’,’vb’,3 (insert the values into predefined procedure parameter)
E.g.3 Let us assume that we have a table named student and this information is updated in real-time and branch
managers are constantly checking the students’ profile. So instead of typing the code like: SELECT * from
FROM student WHERE branch = 'addis' which is inefficient performance at the SQL Server; each time a
branch manager executed the query, the database server was forced to recompile the query and execute it from
scratch. It also required the branch manager to have knowledge of SQL and appropriate permissions to access
the table information. We can simplify this process through the use of a stored procedure. Let's create a
procedure called stu that retrieves the students profile for a given branch.
CREATE PROCEDURE stu
@location varchar (10)
AS SELECT * FROM student WHERE branch = @location
The Addis branch manager can then access students profile by issuing the command: Stu 'Addis'; the diredewa
branch manager can access students profile by issuing the command: Stu 'diredewa'
Stored procedures cannot be modified in place, so you're forced to first drop the procedure, and then create it
again. Although SQL Server can produce the code that was used to create the stored procedure, you should
always maintain a backup copy.
We use the drop procedure statement to drop a stored procedure that is created. Multiple procedures can be
dropped with a single drop procedure statement by listing multiple procedures separated by commas after the
keywords drop procedure like:
Drop procedure procedure_name_1,..., procedure_name_n
Triggers
Trigger is a special type of stored procedure that is invoked when a particular event occurs. Instead of being
executed by the user, triggers are executed by the database server when certain operations are performed on the
object. Triggers could be defined on the table, view, schema, or database with which the event is associated.
Triggers are written to be executed in response to any of the following events:
 A database manipulation (DML) statement (delete, insert, or update).
 A database definition (DDL) statement (create, alter, or drop).
 A database operation (servererror, logon, logoff, startup, or shutdown).
DML Trigger

Page 18
Database administration level IV

DML triggers takes effect when a data manipulation language (DML) event takes place that affects the table or view defined in the trigger. DML
events include INSERT, UPDATE, or DELETE statements. DML triggers can be used to enforce business rules and data integrity, query other tables,
and include complex Transact-SQL statements.
DML triggers are similar to constraints in that they can enforce entity integrity or domain integrity. In addition, DML triggers are most useful when
the features supported by constraints cannot meet the functional needs of the application.
- DML triggers can cascade changes through related or separate tables in the database while referential integrity (foreign key) can cascade only
related (joined) tables.

- They can guard against malicious or incorrect INSERT, UPDATE, and DELETE operations and enforce other restrictions that are more
complex than those defined with CHECK constraints.

- Unlike CHECK constraints, DML triggers can reference columns in other tables. For example, a trigger can use a SELECT from another table
to compare to the inserted or updated data and to perform additional actions, such as modify the data or display a user-defined error message.

- They can evaluate the state of a table before and after a data modification and take actions based on that difference.

- Multiple DML triggers of the same type (INSERT, UPDATE, or DELETE) on a table allow multiple, different actions to take place in response
to the same modification statement.

- Constraints can communicate about errors only through standardized system error messages. If your application requires, or can benefit from,
customized messages and more complex error handling, you must use a trigger.

- DML triggers can disallow or roll back changes that violate referential integrity, thereby canceling the attempted data modification.

- If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution but prior to the AFTER trigger execution. If
the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed.
Insert Triggers
1. Insert triggers: the define SQL statement will take place while the data will be inserted into defined table.
Create trigger trigger_name on Table_name or view_name
For insert as
(sql Statement or expression)
For example the following insert trigger would count number of students and group them using their gender
when new students’ records are added to the table.
create trigger count_trigger on student
for insert
as
select sex, count(*) "Total number of student" from student group by sex
So when you insert data into student the data will automatically stored in student table and the result will be
displayed.
2. Delete triggers -this trigger can protect any delete action on the table.
Create trigger trigger_name on Table_name or view_name
For delete as
(sql Statement or expression)
e.g the following code protect the deletion of record in student table if the student lives in Addis
Create trigger Addi on student
For Delete
As
If (select city from deleted) = 'Addis'
Begin
Page 19
Database administration level IV

Print 'cannot remove student From Addis'


Print 'Transaction has been cancelled'
RollBack
End
Delete From student Where city = 'Addis'
3. Update Triggers:
Create Trigger Update_student on srudent
For Update
As
If Update (fname)
Begin
Print 'can Not Update fname from student’
Print' Transaction Has Been Cancelled'
Rollback
End
Update student set fname=’aaaa’ where sid=’s001’ (to update)
When you excute or try to update students’ fname the trigger will display the following error message:
Can not update fname from student
Transaction Has Been Cancelled
But the other column will be updated if you want to update.
Note: The if update Statement can be used in insert triggers as well as in update triggers.
AFTER trigger
AFTER triggers are executed after the action of the INSERT, UPDATE or DELETE statement is performed. AFTER triggers are never executed if a
constraint violation occurs; therefore, these triggers cannot be used for any processing that might prevent constraint violations. For every INSERT,
UPDATE, or DELETE action specified in a statement, the corresponding trigger is fired for each DML operation.
For example if you have a table named employee and you want synchronously take a backup of the table to
employee_backup; First of all take the copy of employee table into employee_backup like this;
Select * into employee_backup from employee
And then create the following trigger.
create trigger back on employee
after insert
as
begin
insert into employee_backup select * from inserted
end
So when you insert data into employee table the data will automatically stored in employee_backup table from
inserted table after the data will be stored in base (employee) table.
INSTEAD OF trigger
Instead of triggers execute “instead of” (as a substitute for) the submitted transaction, so that the submitted
transaction does not occur. INSTEAD OF triggers override the standard actions of the triggering statement.
Therefore, they can be used to perform error or value checking on one or more columns and perform additional
actions before insert, updating or deleting the row or rows. For example, when the value being updated in credit
column in a course table exceeds a specified value, a trigger can be defined to either produce an error message
and roll back the transaction, or insert a new record into an audit trail before inserting the record into the course
table.

Page 20
Database administration level IV

Instead of triggers are useful when it’s known that the DML statement firing the trigger will always be rolled
back and some other logic executed instead of the DML statement. For example:
 When the DML statement attempts to update a non-updateable view, the instead of trigger updates the
underlying tables instead.
The following code creates a test instead of trigger and then attempts to insert a row:
Create trigger Instead_of on student
Instead of Insert
As
Print ‘ To add new record !!!!!!!!!!!!!!!’
This code display a message “To add new record!!!!!!!!!!!!!!!!” while you try to insert data into the table and no record or data can be inserted into
the table.
DDL Triggers
Like standard triggers, DDL trigger execute stored procedures in response to an event. But unlike standard triggers, they do not execute in response
to UPDATE, INSERT, or DELETE statements on a table or view. They primarily execute in response to data definition language (DDL) statements.
DDL triggers do not fire in response to events that affect local or global temporary tables and stored procedures. Unlike DML triggers, DDL triggers
are not scoped to schemas. Therefore, functions such as object_id, object_name, object-property cannot be used for querying metadata about DDL
triggers.
DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily
correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures
that perform DDL-like operations.
DDL trigger can be created in either the database or the server. In other word if you want to control the creation,
alter and deletion of objects in the database; you should have to create DDL trigger on the DB . for example the
following trigger prohibit the creation, alter and deletion of table in the database and print the message instead
of performing the function.
create trigger protection on database
for create_table,drop_table, alter_table as print 'It is only permited for admin' rollback
But if you want to create trigger in order to prevent the creation and database drop you should have to create the
DDL trigger on the server like as follows:
create trigger safety on all server
for create_database as print 'It is not permited to create or drop database’
rollback
Logon Triggers
Logon triggers fire in response to the LOGON event that is raised when a user sessions is being established this event is raised when a user session is
established with an instance of SQL Server. Logon triggers fire after the authentication phase of logging in finishes, but before the user session is
actually established. Therefore, all messages originating inside the trigger that would typically reach the user, such as error messages and messages
from the PRINT statement, are diverted to the SQL Server error log. Logon triggers do not fire if authentication fails. Triggers can be created directly
from Transact-SQL statements or from methods of assemblies that are created in the Microsoft.NET Framework common language runtime (CLR)
and uploaded to an instance of SQL Server.
A logon trigger can effectively prevent successful connections to the Database Engine for all users, including members of the sysadmin fixed server
role. When a logon trigger is preventing connections, members of the sysadmin fixed server role can connect by using the dedicated administrator
connection, or by starting the Database Engine in minimal configuration mode (-f).
Disabling and enabling Trigger
Triggers are enabled by default when they are created. Disabling a trigger does not drop it. The trigger still exists as an object in the current database.
However, the trigger does not fire when any Transact-SQL statements on which it was programmed are executed.

Page 21
Database administration level IV

To disable a DML trigger, at a minimum, a user must have ALTER permission on the table or view on which the trigger was created.To disable a
DDL trigger with server scope (ON ALL SERVER) or a logon trigger, a user must have CONTROL SERVER permission on the server. To disable a
DDL trigger with database scope (ON DATABASE), at a minimum, a user must have ALTER ANY DATABASE DDL TRIGGER permission in the
current database.
So if you want to put out of action the trigger temporarily for some period of time instead of dropping it is possible to disable the trigger. Use the
following syntax to disable the trigger:
DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }
ON { object_name | DATABASE | ALL SERVER } or
disable TRIGGER trigger_name ON (server or database or object)
example:
- disable TRIGGER safety ON all server (to disable trigger on the instance or server)
- disable TRIGGER protection ON database (to disable trigger on the database)
- disable TRIGGER sort ON student (to disable trigger on student table)
- alter table student disable trigger sort
To disable all triggers that were defined with the same scope use the following syntax:
- The following example disables all DDL triggers that were created at the server scope
- DISABLE Trigger ALL ON ALL SERVER;
Triggers can be re-enabled by using enable trigger. DML triggers defined on tables can be also be disabled or enabled by using alter table. to enable
the formerly disabled triggers use the following syntax:
Enable trigger trigger_name on schema(server, database, object)
Eg. enable trigger sort on student
alter table student enable trigger sort
Drop Trigger
You can delete or drop the triggers if they are no necessarily required moreover. So you can drop it by using the following syntax.
drop trigger_name on server or database or table.
The inserted and deleted Tables
DML trigger statements use two special tables: the deleted table and the inserted tables. SQL Server automatically creates and manages these tables.
You can use these temporary, memory-resident tables to test the effects of certain data modifications and to set conditions for DML trigger actions.
You cannot directly modify the data in the tables or perform data definition language (DDL) operations on the tables, such as create index.
In DML triggers, the inserted and deleted tables are primarily used to perform the following:
 Extend referential integrity between tables.
 Insert or update data in base tables underlying a view.
 Test for errors and take action based on the error.
 Find the difference between the state of a table before and after a data modification and take actions based on that difference.
The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE
statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows
in common.
The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are
added to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.
An update transaction is similar to a delete operation followed by an insert operation; the old rows are copied to the deleted table first, and then the
new rows are copied to the trigger table and to the inserted table. When you set trigger conditions, use the inserted and deleted tables appropriately
for the action that fired the trigger. Although referencing the deleted table when testing an insert or the inserted table when testing a delete does not
cause any errors, these trigger test tables do not contain any rows in these cases.
Each column in the inserted and deleted tables maps directly to a column in the base table.

Page 22
Database administration level IV

Benefits of Triggers
Triggers can be written for the following purposes:
 Generating some derived column values automatically
 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
Trigger Limitations
 Create trigger must be the first statement in the batch and can apply to only one table.
 A trigger is created only in the current database; however, a trigger can reference objects outside the
current database.
 The same trigger action can be defined for more than one user actions (for example, insert and update)
in the same create trigger statement.
 Instead of delete/update triggers cannot be defined on a table that has a foreign key with a cascade on
delete/update action defined
Temporary Tables
Temporary tables are tables that exist temporarily within a database and are automatically dropped when the
user logs out or their database connection ends. Transact-SQL creates these temporary tables in the tempdb
database. Tempdb database is created when you install SQL Server.
Temporary tables lets us to store and process intermediate results by using the same selection, update, and join
capabilities that we can use with typical SQL Server tables and temporary tables could be very useful in some
cases to keep temporary data. Temporary tables will be deleted when the current client session terminates. In
other word temporary tables will only last as long as the session is alive. A temporary table is available only to
its creator. Two types of syntax are used to create a temporary table.
Syntax 1;
Create table #table_name (
field1 datatype,
.fieldn datatype)
The pound sign (#) before the table's name is the identifier that SQL Server uses to flag a temporary table. The
table could also be dropped automatically when the user who created it logs out of the SQL Server or you may
use the following syntax to drop the tables;
Drop table #table_name
Syntax 2;
Creating a temporary table using the format of syntax 2 still results in a table being created in the tempdb
database. The difference is that this table is not dropped when the user's connection to the database ends.
Instead, the user must actually issue a DROP TABLE command to remove this table from the tempdb database.
Create table tempdb..table_name (
field1 datatype,
.
fieldn datatype)
Sub Queries
A sub query is a query whose results are passed as the argument for another query. Subqueries enable us to
bind several queries together. A Sub query or Inner query or Nested query is a query within another SQL query
and embedded within the WHERE clause. It is used to return data that will be used in the main query as a

Page 23
Database administration level IV

condition to further restrict the data to be retrieved. Sub queries can be used with the SELECT, INSERT,
UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
 Sub queries must be enclosed within parentheses.
 A sub query can have only one column in the SELECT clause, unless multiple columns are in the main
query for the sub query to compare its selected columns.
 An ORDER BY cannot be used in a sub query, although the main query can use an ORDER BY. The
GROUP BY can be used to perform the same function as the ORDER BY in a sub query.
 Sub queries that return more than one row can only be used with multiple value operators, such as the
IN operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or
NCLOB.
 A sub query cannot be immediately enclosed in a set function.
 Sub queries are most frequently used with the SELECT statement.
The basic syntax of sub query:
SELECT [*/ column_name] FROM table1 WHERE column_name1 OPERATOR (SELECT column_name1
FROM table2 [WHERE])
Subqueries with the INSERT Statement
Subqueries can also be used with INSERT statements. The INSERT statement uses the data returned from the
subquery to insert into another table. The selected data in the subquery can be modified with any of the
character, date or number functions.
The syntax is:
INSERT INTO table_name [columns] SELECT [ *|columns] FROM table_name [ where value operator ]
Subqueries with the UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a
table can be updated when using a subquery with the UPDATE statement.
The syntax is:
UPDATE table SET column_name = new_value WHERE column_name OPERATOR (SELECT
COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
Example: Assume that, we have customers_bkp table available which is backup of customers table. So the
following example update salary by 0.25 times in customers table for all the customers whose age is greater
than or equal to 27:
Update customers Set salary = salary * 0.25 Where age in (select age from customers_bkp Where age >= 27);
Subqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned
above.
The syntax is:
Delete from table_name where column_name operator (select column_name From table_name) [ where) ]
Example: delete from customers Where age in (select age from customers_bkp Where age > 27 )
Nested Subqueries
Nesting is the act of embedding a subquery within another subquery. like
Select * from something where ( subquery(subquery(subquery))) or
Select * from table_name where column_name in (select column_name from table_name where column_name
operator ‘value’ and column_2 in (select column_2 from table_name where column_2 operator ‘value’ and
column3 in (…n)))
Example:

Page 24
Database administration level IV

select * from student where age in (select age from student where age >32 and sex in (select sex from student
where sex='female') and city in (select city from student where city = 'DD'))
Cursor
Database cursors enable us to select a group of data, scroll through the group of records (often called a record
set), and examine each individual line of data as the cursor points to it. One other common use of cursors is to
save a query's results for later use. A cursor's result set is created from the result set of a SELECT query. If our
application or procedure requires the repeated use of a set of records, it is faster to create a cursor once and
reuse it several times than to repeatedly query the database.
Create the cursor
Declare cursor defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the
query used to build the result set on which the cursor operates. By executing the DECLARE cursor_name
CURSOR statement, we have defined the cursor result set that will be used for all our cursor operations. A
cursor has two important parts: the cursor result set and the cursor position. Syntax:
Declare cursor_name cursor For select [ * or column] from table_name
Opening a Cursor
The OPEN statement populates the result set. So, we have to open it after we have declared the cursor. The
simple command to open a cursor for use is: open cursor_name
Scrolling a Cursor
The FETCH command returns a row from the result set. Each time the FETCH command is executed, the cursor
pointer advances through the result set one row at a time. If desired, data from each row can be fetched into the
fetch_target_list variables To scroll through the cursor's result set, we use the FETCH command.
Syntax: fetch next from cursor_name
Close the cursor
The CLOSE statement releases the current result set associated with the cursor. We close the cursor when we
are finished with it. Syntax: close cursor_name
Deallocate the cursor
The DEALLOCATE statement releases the resources used by the cursor. Deallocate the cursor to completely
discard it. Syntax: deallocate cursor_name

Page 25

You might also like