Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

MODULE TITLE: Monitor and Administer Database

MODULE CONTENTS:
LO1. Start up a database
1.1 Monitoring databasestart-up and operation for irregularities
Configuring system for database start-up
Concepts Of Database Handling And Requirement
In the information age we are living in, we can see how much data the world is exchanging. We are basically
creating, storing, and retrieving data, extensively! There should be a way to handle all that. The DBMS is a
software system that enables you to create, store, modify, retrieve, and otherwise handle data from a database.
Such systems also vary in size, ranging from small systems that simply run on your personal computer to
larger ones running on mainframes.

Requirements for Creating Databases

You must have certain permissions to create databases, and you must calculate the storage needed for
database and related data.

Permissions Required for Creating Databases

To create databases, you need Create Databases permission on the database group that will contain the
database and Use Template permission on at least one database configuration template.

It is useful to have the following permissions on the database group and on the database.

■ Create snapshots.
■ Create external backups.
■ Delete snapshots and manage their retention time.
■ Clone the database.
■ Recover the database from a backup or snapshot.

The organization administrator can create a role with these permissions and assign users in the organization to
the role.

Calculating Database Storage Allocation

~1~
During the database creation process, you specify database storage allocation, point-in-time recovery storage
allocation, and the database group for the database. The database group provides the CPU, memory, storage,
and network resources required to run the database. The storage and point-in-time recovery allocations specify
how much of the database group's resources to use for this database.

When you calculate the amount of storage to allocate to the database, proceed as follows.

■ Estimate how much data will be stored in the database.


■ Consider the number of users and average expected number of transactions in a particular time
period and include room for growth.
■ If you plan to enable point-in-time recovery, calculate additional storage to accommodate the point-
in-time recovery write-ahead logs (WALs). The size of the allocation depends on the expected
volume of transactions on the database.

Database storage allocation is for the database data only. It does not include overhead for the operating
system, database software, swap space, or snapshots. You must have enough resources available to cover both
the database allocation and to cover any overhead. Even if the database group has enough free space for
creating a database, database creation does not complete if you do not have enough resources for the
overhead.

Database Creator Permissions

After database creation finishes, the following permissions on the new database are granted to the database
creator.

Edit Database Enables the database creator to edit database properties such as the name, description,
Info and size of the database.

Modify Database Enables the database creator to add or modify database users for this database. Database
Users users are granted full permission on this database.

Restart Database Enables the database creator to add or modify database users for this database. The
database users are granted full permission on this database.

View Database Enables the database creator to view the database.

~2~
Advanced SQL Commands
(Creating and Altering Tables)

SQL Constraints
- SQL constraints are used to specify rules for the data in a table.
- If there is any violation between the constraint and the data action, the action is aborted by the
constraint.
- Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after
the table is created (inside the ALTER TABLE statement).

SQL CREATE TABLE + CONSTRAINT Syntax

CREATE TABLE table_name


(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);

In SQL, we have the following constraints:

NOT NULL - Indicates that a column cannot store NULL value


UNIQUE - Ensures that each row for a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combinationof two or
more columns) have a unique identity which helps to find a particular record in a table more easily and
quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another
table
CHECK
DEFAULT
SQL NOT NULL Constraint
- The NOT NULL constraint enforces a column to NOT accept NULL values.
- The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert
a new record, or update a record without adding a value to this field.
- The following SQL enforces the "Name", "Address" and “PhoneNo”columnto not accept NULL values

CREATE TABLE tblStudent


(
StudentIDnvarchar(10) NOT NULL, Name
nvarchar(50) NOT NULL, Address
nvarchar(50) NOT NULL,
PhoneNonvarchar(50) NOT NULL, Email
nvarchar(25),
Birthdate date );

SQL PRIMARY KEY Constraint


- The PRIMARY KEY constraint uniquely identifies each record in a database table.
- Primary keys must contain UNIQUE values.
- A primary key column cannot contain NULL values.
CREATE TABLE tblDepartment

~3~
(
DepartmentIDchar(5),
DepartmentNamenvarchar(50),
BldgNonvarchar(5) NOT NULL,
CONSTRAINT pk_DepartmentID PRIMARY KEY (DepartmentID) );

CREATE TABLE tblInstructor


(
InstructorIDchar(5),
FirstNamenvarchar(25) NOT NULL,
LastNamenvarchar(25) NOT NULL,
Address nvarchar(50),
PhoneNonvarchar(12), Email
nvarchar(25),
CONSTRAINT pk_InstructorID PRIMARY KEY (InstructorID) );

The ALTER TABLE Statement


- The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL PRIMARY KEY Constraint on ALTER TABLE
- To create a PRIMARY KEY constraint on the "StudentID" column when the table is already created,
use the following SQL:

ALTER TABLE tblStudent


ADD CONSTRAINT pk_StudentID PRIMARY KEY (StudentID);
*Note: Make sure that the field has a NOT NULL constraint.
To DROP a PRIMARY KEY Constraint
- To drop a PRIMARY KEY constraint, use the following SQL:
ALTER TABLE tblDepartment
DROP CONSTRAINT pk_DepartmentID
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_namedatatype;
To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


ALTER COLUMN column_namedatatype

SQL ALTER TABLE Example:


- Look at the "tblDepartment" table:
Field Name Data Type / Field Size Constraints
DepartmentID Char(5) Primary Key
DepatmentName Nvarchar(50)
BldgNo Nvarchar(5) Not Null

ALTER TABLE tblDepartment


ADD DepartmentHeadnvarchar(50)

- After executing the SQL statement, the tblDepartment will now look like this.
Field Name Data Type / Field Size Constraints

~4~
DepartmentID Char(5) Primary Key
DepatmentName Nvarchar(50)
BldgNo Nvarchar(5) Not Null
DepartmentHead Nvarchar(50)

DROP COLUMN Example


- We want to delete the column named "PhoneNo" in the "tblInstructor" table.
Field Name Data Type / Field Size
InstructorID Char(5) Primary Key
Firstname Nvarchar(25) Not Null
Lastname Nvarchar(25) Not Null
Address Nvarchar(50)
PhoneNo Nvarchar(12)
Email Nvarchar(25)

- We use the following SQL statement:

ALTER TABLE tblInstructor DROP


COLUMN PhoneNo;

- The "tblInstructor" table will now look like this:


Field Name Data Type / Field Size
InstructorID Char(5) Primary Key
Firstname Nvarchar(25) Not Null
Lastname Nvarchar(25) Not Null
Address Nvarchar(50)
Email Nvarchar(25)

RENAME/CHANGE COLUMN Example


- We want to rename the column "Address" into. “Region”
Field Name Data Type / Field Size
StudentID Nvarchar(10)
Name Nvarchar(50) Not Null
Address Nvarchar(50) Not Null
PhoneNo Nvarchar(50) Not Null
Email Nvarchar(25)
Birthdate Date

EXEC SP_RENAME 'tblStudent.Address', 'Region'


- The fieldname Address is now changed to Region
Field Name Data Type / Field Size
StudentID Nvarchar(10)
Name Nvarchar(50) Not Null
Region Nvarchar(50) Not Null
PhoneNo Nvarchar(50) Not Null
Email Nvarchar(25)
Birthdate Date

Change Data Type Example


- Now we want to change the data type of the column named "Region" into varchar(25).
- We use the following SQL statement:

~5~
ALTER TABLE tblStudent
ALTER COLUMN Region varchar(25);

- The datatype of the field Region is now changed to varchar(25)


Field Name Data Type / Field Size
StudentID Nvarchar(10)
Name Nvarchar(50) Not Null
Region varchar(25) Not Null
PhoneNo Nvarchar(50) Not Null
Email Nvarchar(25)
Birthdate Date

Function

SQL GROUP BY Statement


Aggregate functions often need an added GROUP BY statement.

The GROUP BY Statement


The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or
more columns.

SQL GROUP BY Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
SQL GROUP BY Example
We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find the total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the customers.
We use the following SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
The result-set will look like this:

~6~
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
Nice! Isn't it? :)
Let's see what happens if we omit the GROUP BY statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
The result-set will look like this:

Customer SUM(OrderPrice)
Hansen 5700
Nilsen 5700
Hansen 5700
Hansen 5700
Jensen 5700
Nilsen 5700
The result-set above is not what we wanted.

Explanation of why the above SELECT statement cannot be used: The SELECT statement above has
two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value
(that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for
each row in the "Orders" table). This will therefore not give us the correct result. However, you have
seen that the GROUP BY statement solves this problem.

GROUP BY More Than One Column


We can also use the GROUP BY statement on more than one column, like this:

SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders


GROUP BY Customer,OrderDate
SQL HAVING Clause
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.

SQL HAVING Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value

~7~
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
SQL HAVING Example
We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find if any of the customers have a total order of less than 2000.

We use the following SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Orders


GROUP BY Customer
HAVING SUM(OrderPrice)<2000
The result-set will look like this:

Customer SUM(OrderPrice)
Nilsen 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.

We add an ordinary WHERE clause to the SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Orders


WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500
The result-set will look like this:

Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000

Compiling Data Dictionary And Data Structure

~8~
A data dictionary is a collection of descriptions of the data objects or items in a data model for the benefit of
programmers and others who need to refer to them.
I.e.: Itis a set of information describing the contents, format, and structure of a database and the relationship
between its elements, used to control access to and manipulation of the database.
When developing programs that use the data model, a data dictionary can be consulted to understand where a
data item fits in the structure, what values it may contain, and basically what the data item means in real-
world terms.
* Most DBMS keep the data dictionary hidden from users to prevent them from accidentally destroying its
contents.
* A data dictionary may contains:
- The definitions of all schema objects in the database.
- How much space has been allocated for, and is currently used by the schema objects
- Default values for columns.
- Integrity constraint information (Constraints that apply to each field, if any)
- Auditing information, such as who has accessed or updated various schema objects
- Privileges and roles each user has been granted (Access Authorization)
- Description of database users, their responsibilities and their access rights.
Data dictionaries do not contain any actual value from the database, only bookkeeping information for
managing it.
What is an advantage of a Data Dictionary?
When a new user is introduced to the system or a new administrator takes over the system, identifying table
structures and types becomes simpler.
 Maintaining data integrity constraints according to business requirements
Data integrityis a constraint which used to ensure accuracy and consistency of data in a database by
validating the data before getting stored in the columns of the table.
Data integrity refers to the overall completeness, accuracy and consistency of data in according to business
requirements.
 Types of integrity constraints
› Entity integrity
› Referential integrity
› Domain integrity
› User defined integrity
• Entity integrity
This is concerned with the concept of primary keys. The rule states that every table must have its own primary
key and that each has to be unique and not null.
• Referential Integrity
This is the concept of foreign keys. The rule states that the foreign key value can be in two states. The first
state is that the foreign key value would refer to a primary key value of another table, or it can be null. Being
null could simply mean that there are no relationships, or that the relationship is unknown.
Referential integrity is a feature provided by relational DBMS that prevents users from entering inconsistent
data.

~9~
• Domain Integrity
This states that all columns in a relational database are in a defined domain.
The concept of data integrity ensures that all data in a database can be traced and connected to other data. This
ensures that everything is recoverable and searchable. Having a single, well defined and well controlled data
integrity system increases stability, performance, reusability and maintainability.
• User Defined Integrity
User-defined integrity allows you to define specific business rules that do not fall into one of the other
integrity categories. All of the integrity categories support user-defined integrity (all column- and table-level
constraints in CREATE TABLE, stored procedures, and triggers).
Business rules may dictate/state that when a specific action occurs further actions should be triggered.
For example, deletion of a record automatically writes that record to an audit table.
 Creating and designing indexes and multiple-field keys according to business requirements
 What is index?
An indexis a separate physical data structure that enables queries to access one or more data rows fast.
A database index is a separate physical data structure that improves the speed of data retrieval operations on
a database table at the cost of additional writes and the use of more storage space to maintain the extra copy of
data.
Indexes are used to quickly locate data without having to search every row in a database table every time a
database table is accessed. Indexes can be created using one or more columns of a database table, providing
the basis for both rapid random lookupsand efficient access of ordered records.
Why Use Indexes? Two primary reasons exist for creating indexes in SQL Server:
- To maintain uniqueness of the indexed column(s)
- To provide fast access to the data in tables.
 Deciding which fields to be index
The following list gives guidelines in choosing columns to index:
- You should create indexes on columns that are used frequently in WHERE clauses.
- You should create indexes on columns that are used frequently to join tables.
- You should create indexes on columns that are used frequently in ORDER BY clauses.
- You should create indexes on columns that have few of the same values or unique values in the table.
- You should not create indexes on small tables (tables that use only a few blocks) because a full table
scan may be faster than an indexed query.
- If possible, choose a primary key that orders the rows in the most appropriate order.
 Creating indexes
Indexes can be created to order the values in a column in ascending or descending sequence.
 You can use the CREATE INDEX statement to create indexes.
The general form of CREATE INDEX statement is:
CREATEINDEX index_name ON table_name(column1 [ASC | DESC] ,...)
Example:Create an index for the EmpID column of the employee table.

 Delete an index
Deleting an index means removing one or more relational indexes from the current database.

~ 10 ~
The DROP INDEX statement is used to delete an index in a table.
Syntax : DROP INDEX index_name ON table_name
Why Use theDROP INDEX Statement?
You may drop an index permanently when it is no longer useful or temporarily. If the index is harming or not
helping performance, it could be dropped.
Indexes may slow down the loading of data because they must be maintained during the data load process. For
high performance loads, an index could be dropped for the duration of a load and then recreated.
To delete an index by using Object Explorer, you can follow the steps as shown below:
 In Object Explorer, expand the database that contains the table on which you want to delete an index.
 Expand the Tables folder.
 Expand the table that contains the index you want to delete.
 Expand the Indexes folder.
 Right-click the index you want to delete and select Delete.
 In the Delete Object dialog box, verify that the correct index is in the Object to be deleted grid and
click OK.
To delete an index using Table Designer
- In Object Explorer, expand the database that contains the table on which you want to delete an index.
- Expand the Tables folder.
- Right-click the table that contains the index you want to delete and click Design.
- On the Table Designer menu, click Indexes/Keys.
- In the Indexes/Keys dialog box, select the index you want to delete.
- Click Delete.
- Click Close.
- On the File menu, select Savetable_name.
 View and edit indexes
To view all indexes in a database
- In Object Explorer, connect to an instance of the SQL Server Database Engine and then expand that
instance.
- Expand Databases, expand the database that contains the table with the specified index, and then
expand Tables.
- Expand the table in which the index belongs and then expand Indexes.
To modify an index using wizard
› In Object Explorer, connect to an instance of the SQL Server Database Engine and then expand that
instance.
› Expand Databases, expand the database in which the table belongs, and then expand Tables.
› Expand the table in which the index belongs and then expand Indexes.
› Right-click the index that you want to modify and then click Properties.
› In the Index Properties dialog box, make the desired changes. For example, you can add or remove a
column from the index key, or change the setting of an index option.

~ 11 ~
 Create multiple-field keys
Relational database designs use a set of columns as the primary key for a table. When this set includes more
than one column, it is known as a “composite” or “compound” primary key.
If the values in a single common key field are insufficiently unique to accurately join or relate two tables, you
need to use multiple common key fields in combination.
 Monitoring the lock options chosen for the database
Database locks serve to protect shared resources or objects.
These protected resources could be:
 Tables  Cached Items
 Data Rows  Connections
 Data blocks  Entire Systems
There are also many types of locks such as shared locks, transaction locks, DML locks, and backup-recovery locks.

Introduction to Database Security Issues


 In today's society, some information is extremely important as to have to be protected. For example,
disclosure or modification of military information could cause danger to national security. A good
database security management system has tohandle the possible database threats.
 Threat may be any situation or event, whether intentional or accidental, that may adversely affect a
system and consequently the organization
 Threats to databases : It may results in degradation of some/all security goals like;
 Loss of Integrity
 Only authorized users should be allowed to modify data.
 For example, students may be allowed to see their grades, but not allowed to modify
them.
 Loss ofAvailability-if DB is not available for those users/ to which they have a legal right to uses
the data
 Authorized users should not be denied access.
 For example, an instructor who wishes to change a grade should be allowed to do so.
 Loss of Confidentiality
 Information should not be disclosed to unauthorized users.
 For example, a student should not be allowed to examine other students' grades.
Authentication
• All users of the database will have different access levels and permission for different data objects,
and authentication is the process of checking whether the user is the one with the privilege for the
access level.
• Thus the system will check whether the user with a specific username and password is trying to use
the resource
Authorization/Privilege
• Authorization refers to the process that determines the mode in which a particular (previously
authenticated) client is allowed to access a specific resource controlled by a server.
• Any database access request will have the following three major components

~ 12 ~
1. Requested Operation: what kind of operation is requested by a specific query?
2. Requested Object: on which resource or data of the database is the operation sought to be applied?
3. Requesting User: who is the user requesting the operation on the specified object?
Forms of user authorization
There are different forms of user authorization on the resource of the
database. These includes :
1. Read Authorization: the user with this privilege is allowed only to read the content of the data object.
2. Insert Authorization: the user with this privilege is allowed only to insert new records or items to the data
object.
3. Update Authorization: users with this privilege are allowed to modify content of attributes but are not
authorized to delete the records.
4. Delete Authorization: users with this privilege are only allowed to delete a record and not anything else.
 Note: Different users, depending on the power of the user, can have one or the combination of
the above forms of authorization on different data objects.
Database Security and the DBA
 The database administrator (DBA) is the central authority for managing a database system.
 The DBA’s responsibilities include
 Account creation
 granting privileges to users who need to use the system
 Privilege revocation
 classifying users and data in accordance with the policy of the organization
SQL Server Authentication
SQL Server 2008 provides two methods for creating database user accounts -
Windows authentication or SQL Server authentication. In Windows authentication mode,you
assign all database permissions to Windows accounts. This has the advantage of providing a
single sign-on experience for users and simplifying security management. In SQL Server (mixed
mode) authentication, you can still assign rights to Windows users, but you may also create
accounts that exist only in the context of the database server.
SQL Server Authentication Modes
SQL Server 2008 offers two authentication mode options:
 Windows authentication mode requires users to provide a valid Windows username
andpassword to access the database server. In enterprise environments, these credentials are
normally Active Directory domain credentials. 

 Mixed authentication mode allows the use of Windows credentials but supplements themwith
local SQL Server user accounts that the administrator may create and maintain within SQL
Server. 

Selecting an Authentication Mode

~ 13 ~
Microsoft’s best practice recommendation is mode whenever possible. The main benefit is that
the use of this mode allows you to centralize account administration for your entire enterprise in a single
place: Active Directory. This dramatically reduces the chances of error or oversight.

For example, consider the scenario where a trusted database administrator leaves your
organization on unfriendly terms. If you use Windows authentication mode, revoking
that user’s access takes place automatically wh
Directory account. If you use mixed authentication mode, you not only need to disable the DBA’s
Windows utaccount,youalsoneedtobcomb through the local user listings on each database
server to ensure that no local accounts exist where the DBA may know the password. That’s a lot
of work!

Server-Level Roles

To easily manage the permissions on your server, SQL Server provides several roles, which
are security principals that group other principals. Roles are like groups in the Microsoft Windows
operating system.
Fixed server roles are provided for convenience and backward compatibility. Assign more
specific permissions whenever possible.
Server-level roles are also named fixed server roles because you cannot create new server-
level roles. Server-level roles are server-wide in their permissions scope.
You can add SQL Server logins, Windows accounts, and Windows groups into server-level
roles. Each member of a fixed server role can add other logins to that same role.

The following table shows the server-level roles and their capabilities.

Server-level role
Description
name

sysadmin Members of the sysadmin fixed server role can perform any activity in the server.

serveradmin Members of the serveradmin fixed server role can change server-wide configuration
options and shut down the server.

securityadmin Members of the securityadmin fixed server role manage logins and their properties.
They can GRANT, DENY, and REVOKE server-level permissions. They can also GRANT,
DENY, and REVOKE database-level permissions if they have access to a database.
Additionally, they can reset passwords for SQL Server logins.
Security Note
The ability to grant access to the Database Engine and to configure user permissions

allows the security admin to assign most server permissions. Thesecurityadmin role
should be treated as equivalent to the sysadmin role.

processadmin Members of the processadmin fixed server role can end processes that are running
in an instance of SQL Server.
~ 14 ~
setupadmin Members of the setupadmin fixed server role can add and remove linked servers.

bulkadmin Members of the bulkadmin fixed server role can run the BULK INSERT statement.

diskadmin The diskadmin fixed server role is used for managing disk files.

dbcreator Members of the dbcreator fixed server role can create, alter, drop, and restore any
database.

public Every SQL Server login belongs to the public server role. When a server principal has
not been granted or denied specific permissions on a securable object, the user
inherits the permissions granted to public on that object. Only assign public
permissions on any object when you want the object to be available to all users.

Creating SQL Server Authentication Login (SQL Script)


 Creating Logins
Most Windows users need SQL Server login account to connect to SQL Server.
This topic shows how to create a SQL Server login account.
To create a SQL Server login that uses Windows Authentication using wizard
. In SQL Server, open Object Explorer and expand the folder of the server instance.
. Expand security folder, Right-click on login folder, and then select New Login.
. Click on the General, and enter the name of a Windows user in the Login name box.
. Select Windows Authentication, and then Click OK.
To create a SQL Server login that uses SQL Server Authentication using wizard
* In SQL Server, open Object Explorer and expand the folder of the server instance.
* Expand security folder, Right-click on login folder, and then select New Login.
* Click on the General, and enter the name of a Windows user in the Login name box.
* Select SQL Server Authentication. However, Windows Authentication is the more secure option.
* Enter a password for the login.
* Select the password policy options that should be applied to the new login, and then Click OK.
- In general, enforcing password policy is the more secure option.
To create a SQL Server login that uses Windows Authentication using Transact-SQL code
 Open New Query Editor,
 use the following Transact-SQL syntax:
Syntax
CREATE LOGIN [LoginName] with password=N'Password', default_database=[DatabaseName],
check_expiration=off, check_policy=off

Example:

CREATE LOGIN [NewUser2] with password=N'P@$$w0rd',


default_database=[master], check_expiration=off, check_policy=off

~ 15 ~
CREATE LOGIN [computer Name\name of Windows User] FROM WINDOWS
Example: CREATE LOGIN [PC-Name\Admin] from windows
To create a SQL Server login that uses SQL Server Authentication using T-SQL code
 Open New Query Editor
 Use the following Transact-SQL syntax:
CREATE LOGIN [login_Name] WITH PASSWORD = 'password'
Example: CREATE LOGIN student WITH PASSWORD=’abc/123’
 We can drop login by using the DROP LOGIN login_name statement
1. Creating and Managing database Users
To create a database user using SQL Server
 In SQL Server, open Object Explorer and expand the Databases folder.
 Expand the database in which to create the new database user.
 Expand Security folder, right click on user folder and select User.
 Select General, and enter a name for the new user in the User name box.
 In the Login name box, enter the name of a SQL Server login to map to the database user.
 Click OK.
To create a database user using T-SQL code
 Open New Query Editor
 Use the following Transact-SQL syntax:
CREATE USER <new user name> FOR LOGIN <login name>
Example: CREATE USER Admin1 for login Student

DCL
DCL is abbreviation of Data Control Language. It is used to create roles, permissions, and referential integrity as well it is
used to control access to database by securing it.

Examples: GRANT, REVOKE statements


TCL
TCL is abbreviation of Transactional Control Language. It is used to manage different transactions
occurring within a database.
Examples: COMMIT, ROLLBACK statements
DCL commands are used to enforce database security in a multiple user database environment. Two
types of DCL commands are GRANT and REVOTE. Only Database Administrator's or owner's of the
database object can provide/remove privileges on a databse object.

SQL GRANT Command

SQL GRANT is a command used to provide access or privileges on the database objects to the users.
The Syntax for the GRANT command is:

~ 16 ~
GRANT privilege_name

ON object_name

TO {user_name |PUBLIC |role_name}

[WITH GRANT OPTION];

 privilege_name is the access right or privilege granted to the user. Some of the access rights are
ALL, EXECUTE, and SELECT.
 object_name is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.
 user_name is the name of the user to whom an access right is being granted.
 user_name is the name of the user to whom an access right is being granted.
 PUBLIC is used to grant access rights to all users.
 ROLES are a set of privileges grouped together.
 WITH GRANT OPTION - allows a user to grant access rights to other users.
For Eample: GRANT SELECT ON employee TO user1;This command grants a SELECT permission on employee
table to user1.You should use the WITH GRANT option carefully because for example if you GRANT SELECT
privilege on employee table to user1 using the WITH GRANT option, then user1 can GRANT SELECT privilege on
employee table to another user, such as user2 etc. Later, if you REVOKE the SELECT privilege on employee from
user1, still user2 will have SELECT privilege on employee table.

SQL REVOKE Command:

The REVOKE command removes user access rights or privileges to the database objects.
The Syntax for the REVOKE command is:

REVOKE privilege_name

ON object_name

FROM {user_name |PUBLIC |role_name}

For Eample: REVOKE SELECT ON employee FROM user1;This commmand will REVOKE a SELECT privilege on
employee table from user1.When you REVOKE SELECT privilege on a table from a user, the user will not be able
to SELECT data from that table anymore. However, if the user has received SELECT privileges on that table from
more than one users, he/she can SELECT from that table until everyone who granted the permission revokes it.
You cannot REVOKE privileges if they were not initially granted by you.

Privileges and Roles:

Privileges: Privileges defines the access rights provided to a user on a database object. There are two types of
privileges.

~ 17 ~
1) System privileges - This allows the user to CREATE, ALTER, or DROP database objects.
2) Object privileges - This allows the user to EXECUTE, SELECT, INSERT, UPDATE, or DELETE data from database
objects to which the privileges apply.
Few CREATE system privileges are listed below:

System Privileges Description


CREATE object allows users to create the specified object in their own
schema.
CREATE ANY object allows users to create the specified object in any
schema.

The above rules also apply for ALTER and DROP system privileges.
Few of the object privileges are listed below:

Object Privileges Description

INSERT allows users to insert rows into a table.


SELECT allows users to select data from a database object.

UPDATE allows user to update data in a table.


EXECUTE allows user to execute a stored procedure or a function.

Roles: Roles are a collection of privileges or access rights. When there are many users in a database it becomes
difficult to grant or revoke privileges to users. Therefore, if you define roles, you can grant or revoke privileges to
users, thereby automatically granting or revoking privileges. You can either create Roles or use the system roles
pre-defined by oracle.
Some of the privileges granted to the system roles are as given below:

System Role Privileges Granted to the Role


CONNECT CREATE TABLE, CREATE VIEW, CREATE SYNONYM, CREATE SEQUENCE, CREATE
SESSION etc.

RESOURCE CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE, CREATE TRIGGER etc.
The primary usage of the RESOURCE role is to restrict access to database
objects.

DBA ALL SYSTEM PRIVILEGES


Creating Roles:
The Syntax to create a role is:

CREATE ROLE role_name

[IDENTIFIED BY password];

For example: To create a role called "testing" with password as "pwd",the code will be as follows

~ 18 ~
CREATE ROLE testing

[IDENTIFIED BY pwd];

It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a privilege direclty to
every user. If a role is identified by a password, then, when you GRANT or REVOKE privileges to the role, you
definetely have to identify it with the password.
We can GRANT or REVOKE privilege to a role as below.
For example: To grant CREATE TABLE privilege to a user by creating a testing role:
First, create a testing Role

CREATE ROLE testing


Second, grant a CREATE TABLE privilege to the ROLE testing. You can add more privileges to the ROLE.

GRANT CREATE TABLE TO testing;

Third, grant the role to a user.

GRANT testing TO user1;

To revoke a CREATE TABLE privilege from testing ROLE, you can write:

REVOKE CREATE TABLE FROM testing;

The Syntax to drop a role from the database is as below:

DROP ROLE role_name;

For example: To drop a role called testing, you can write:

DROP ROLE testing;

Propagation of Privileges using the GRANT OPTION


Example1
 Suppose that the DBA creates four accounts:A1, A2, A3, A4 and wants only A1 to be able to create relations.
Then the DBA must issue the following GRANT command in SQL
GRANT CREATETAB TO A1;
Example 2
 Suppose that A1 creates the two base relations EMPLOYEE and DEPARTMENT
 A1 is then owner of these two relations and hence A1 has all the relation privileges on each of them.
 Suppose that A1 wants to grant A2 the privilege to insert and delete rows in both of these relations, but A1
does not want A2 to be able to propagate these privileges to additional accounts:
GRANT INSERT, DELETE ON EMPLOYEE, DEPARTMENT TO A2;

Example 3
 Suppose that A1 wants to allow A3 to retrieve information from either of the table (Department or
Employee) and also to be able to propagate the SELECT privilege to other accounts.
~ 19 ~
 A1 can issue the command:
GRANT SELECT ON EMPLOYEE, DEPARTMENT
TO A3 WITH GRANT OPTION;
 A3 can grant the SELECT privilege on the EMPLOYEE relation to A4 by issuing:
GRANT SELECTON EMPLOYEE TO A4;
 Notice that A4 can’t propagate the SELECT privilege because GRANT OPTION was not given to A4
Example 4
 Suppose that A1 decides to revoke the SELECT privilege on the EMPLOYEE relation from A3; A1 can
issue:
REVOKE SELECT ON EMPLOYEE FROM A3;
 The DBMS must now automatically revoke the SELECT privilege on EMPLOYEE from A4, too, because
A3 granted that privilege to A4 and A3 does not have the privilege any more.
Example 5
 Suppose that A1 wants to give back to A3 a limited capability to SELECT from the EMPLOYEE relation
and wants to allow A3 to be able to propagate the privilege.
 The limitation is to retrieve only the NAME, BDATE, and ADDRESS attributes and only for the
tuples with DNO=5.
 A1 then create the view:
CREATE VIEW A3EMPLOYEE AS
SELECT NAME, BDATE, ADDRESS FROM EMPLOYEE
WHERE DNO = 5;
After the view is created, A1 can grant SELECT on the view
 A3EMPLOYEE to A3 as follows:
GRANT SELECT ON A3EMPLOYEE TO A3 WITH GRANT OPTION

Example 6
– Finally, suppose that A1 wants to allow A4 to update only the SALARY attribute of
EMPLOYEE;
– A1 can issue:
– GRANT UPDATE ON EMPLOYEE (SALARY) TO A4;
Examples 7:
GRANT INSERT, DELETE ON Customers TO Gech WITH GRANT OPTIONS
Queries allowed to Gech:

INSERT INTO Customers(cid, name, address)


VALUES(32940, ‘Joe Blow’, ‘Seattle’)

DELETE Customers

WHERE LastPurchaseDate< 1995

Queries denied to Gech:

SELECT Customer.address
~ 20 ~
FROM CustomerWHERE name = ‘Joe Blow’
GRANT SELECT ON Customers TO Michael
Now Michael can SELECT, but not INSERT or DELETE

GRANT SELECT ON Customers


TO Michael WITH GRANT OPTIONS

Michael can say this:


GRANT SELECT ON Customers TO Gech
Now Gechcan SELECT on Customers
GRANT UPDATE (price) ON Product TO Leah
Leah can update, but only Product.price, but not Product.name

~ 21 ~
 Managing Server and database Security

1. Creating Roles
Role is a random set of privileges that is granted to users. There are three types of roles in SQL
server:
 Fixed server roles
 Fixed database roles
 User defined database roles
We cannot create or change server level roles, but it is possible database level role.
After you create a database level role, configure the database-level permissions of the role by
using GRANT, DENY, and REVOKE.
Users can be added to a fixed server level role using sp_addsrvrolemember stored procedure.
Syntax: sp_addsrvrolemember ‘role, ‘user_nane’
Example: sp_addsrvrolemember ‘dbcreater’,’u1’
To add members to a database role, use the sp_addrolemember stored procedure.
Syntax: CREATE ROLE role_name [AUTHORIZATION owner_name ]
- Role_name is the name of the role to be created.
~ 22 ~
- AUTHORIZATION owner_name is the database user or role that is to own the new role. If no
user is specified, the role will be owned by the user that executes CREATE ROLE.
Example: CREATE ROLE student
-To add user u1 to be the member of student role, EXECUTE sp_addrolemember ‘student’,’u1’
-To add user u1 to be the member of fixed database role, EXECUTE sp_addrolemember
Example:sp_addrolemember ‘db_accessadmin’,’u1’
- We can drop roles using the Drop role role_name code
- We can remove membership from roles using sp_droprolemember stored procedure
Example; sp_droprolemember db_accessadmin, ‘u1’
2. Granting Permissions
The GRANT statement is used to give privilege to users or roles.
Note: if the permission is given via the [WITH GRANT OPTION], all users in the TO clause can
themselves pass on the privilege to other users.
Examples: GRANT SELECT ON student to u1
GRANT SELECT, INSERT, UPDATE (salary) ON employee to u1
GRANT SELECT ON student to u1 WITH GRANT OPTION
GRANT CREATE TABLE TO u1 WITH GRANT OPTION
3. Revoking Permissions
Revoke statement is used to withdraw privileges from a user without deleting that user.
Syntax: REVOKE [GRANT OPTION FOR]
[GRANT OPTION FOR]:- Indicates that the ability to grant the specified permission will be revoked.
Examples: REVOKE DELETE ON employee from u1
REVOKE DELETE, INSERT ON employee from u1
REVOKE GRANT OPTION FOR DELETE ON EMPLOYEE FROM U1 CASCAD

LO3. Manage database access


 Allocating or removing access privileges according to user status
2. Managing Server and database Security
3. Creating Schemas
InSQL Server, schema is an object that conceptually holds definitions for database objects such as
tables,views,stored procedures, etc. The main advantage of creating a schema is that you can grant permissions to
database objects by using a single CREATE SCHEMA statement.
Syntax:CREATE SCHEMA [schema_name] Authorization [user_name]
Example: create a student schema owned by Admin as follows:
Create schema student Authorization Admin
Create table stud (fnamevarchar(20), Id int, sex char(6))
We can use the DROP SCHEMA schema_name statement to remove schema from the database.
Note: Windows Authentication mode is the default and recommended authentication mode.

~ 23 ~
Configuring SQL Server Authentication Modes
To select or change the server authentication mode, follow these steps:
* In SQL Server, right-click on a desired SQL Server, select Properties and then Select Security
* Select the desired server authentication mode under Server Authentication and then click OK.
* In Object Explorer, right-click on a desired server and then click Restart.
- Using Windows authentication is a more secure choice.

 The Database Administrator's Operating System Account


To perform the administrative tasks of a Database, you need specific privileges within the database and possibly in
the operating system of the server on which the database runs.
Depending on the operating system on which Database is running, you might need an operating system account or
ID to gain access to the operating system. Your operating system account might require operating system privileges
or access rights that other database users do not require.
 Administrative User Accounts
What is the difference between Database Administrator and System Administrator?
A database administrator is a person responsible for the installation, configuration, upgrade, administration,
monitoring and maintenance of databases in an organization.
The role includes the development and design of database strategies, system monitoring and improving
database performance and capacity, and planning for future expansion requirements. They may also plan,
Co-ordinate and implement security measures to safeguard the database.
A System Administrator is generally responsible for all parts of the computer network, such asuser
accounts,computer accounts, domain trusts, email accounts, etc.
The System Administrator isprobably specialized in the network server operating systems and user administration;
where as aDatabase Administrator will be highly specialized with the specific database server and client.
A network administrator maintains network infrastructure such as switches and routers, and diagnoses problems with
these or with the behavior of network-attached computers.
Authorization, privileges, and roles
Users can successfully execute operations only if they have the authority to perform the specified function.
For example: To create a table, a user must be authorized to create tables; to alter a table.
Authorization
In computing systems, authorization is the process of determining which permissions a person or system is supposed
to have. In multi-user computer systems, a system administrator defines which users are allowed access to the
system, as well as the privileges of use for which they are eligible (e.g., access to file directories, hours of access,
amount of allocated storage space).
Privileges
A privilege is a permission to perform an action or a task. Authorized users can create objects, have access to
objects they own, and can pass on privileges on their own objects to other users by using the GRANT statement.
Privileges may be granted to individual users or roles (groups).

~ 24 ~
You can apply five different kinds of user privileges. A user may be able to view, delete, insert, or update
information in a table or view.
A user who has no privileges to a table is not able to use the table at all.
Role
A role is a group of privileges that can be granted to users as one unit. You can create roles and assign users to
certain roles. A single user may have more than one role assigned, and a single role may have more than one user
assigned. All roles are granted to users with the GRANT ROLE statement.

 Monitoring network server log-in log file for illegal log-in attempts or for security breach
Network monitoring
The term network monitoring describes the use of a system that constantly monitors a computer network for slow
or failing components and that notifies the network administrator in case of outages.
Network Server Monitoring allows a network administrator to track the health of network servers in real time.
Network Server Monitoring can identify servers that are in danger of malfunctioning before a malfunction occurs so
that the administrator can proactively repair the server. Network Server Monitoring allows a single administrator to
maintain many remote network servers.
 Backup operator
A backup operator is a user that can backup and restore the computer regardless of file system security.
By default, users are allowed to backup and restore files for which they have the appropriate file and directory
permissions without requiring membership in the Backup Operators group.
The Backup Operators group allows users to backup and restore files regardless of whether they have read or write
access to the files.
Storing Recent Back-Up And Retrieve Data

Data Backup and Storage

What is a Backup?

Backup is a term used to denote the process of creating copies of data that can later be restored in the event of data
loss. A backup can be as simple or complicated as you want to make it. Saving a copy of a file in a different location
on the same hard disk could be an example of a very simple backup, whereas more complex backups may include
servers, off-site storage, and even paid guards!

~ 25 ~
Though there are many terms to denote various types of backup, there exist three basic types of backup — full,
incremental, and differential, all of which may prove useful in different situations.

Full Backup

Every type of backup starts with a full backup. Therefore, full backups are typically part of an overall backup plan.
A full backup creates copies of all data a user has selected for backup. Unless the user chooses to use compression,
the backup file size will be equal to that of the original data. The advantage to this type of backup is that it allows
you to easily and quickly restore your data. The down side is that creating full backups tends to be a long process,
requiring the user to have a large backup window (the amount of time reserved for backup). In addition, creating a
series of full backups requires a storage device with a significant amount of disk space, which can be expensive.

Incremental Backup

An incremental backup starts with a full backup. Incremental backups are generally done periodically according to a
schedule. This type backs up only those files that have changed since the last backup of any type, be it full or
incremental. The advantage to incremental backups is that it takes very little time to back up your files after the
initial full backup, requiring a smaller backup window. Concerning the archive size, incremental backups are
optimal, as they require less disk space.

Differential Backup

A differential backup is similar to an incremental backup. They both back up only data that has been changed. The
difference is that a differential backup backs up only those files that have been changed after the last full backup.
This offers many users a happy medium between full and incremental backup. Differential backup offers the user
both a reasonably short backup and restoration time. Nevertheless, this option requires more disk space than
incremental backups, but less than full backups.

~ 26 ~
Which Files Should I Back Up?

This question arises every time a user wants to back up his or her precious files. The first step to answering this
question is thinking about how long it took to gather the data. Things like financial records, address books, digital
photographs, and Internet browser bookmarks are accumulated over long periods of time and should have high
priority. In addition to this, you should consider whether or not files are of any financial importance. This answers
the question of what you should back up. But what about those files which you should not back up?

Many companies offer users the opportunity to back up their data in their data centers via Internet. These archives
are stored offsite, protecting you from disasters in your own home or office. One of the most attractive advantages is
that as a rule, you can access your data from multiple locations.

One of the most uninviting aspects of storing backups online is the uncertainty of your data's safety. If the company's
servers go down you may not be able to access your information, which may cost you a lot of time or money in a
concurrent data loss event. Perhaps more frightening than this might be hacking. If the company were to be hacked,
your information could be stolen, possibly making you a victim of identity theft or giving away the secrets of your
company's business plan. In addition, if the data storage company goes out of business, you'll lose your backup
archive and be forced to start from zero again. Apart from this, the monthly fees for using such services can be sky
high.
Data Retrieval

In databases, data retrieval is the process of identifying and extracting data from a database, based on a query
provided by the user or application.

It enables the fetching of data from a database in order to display it on a monitor and/or use within an application.
2.6 Monitor Data Storage Space
It is important to monitor the amount of available storage space on your disk because programs might fail due to an
inability to allocate space. In addition, low disk space might make it impossible for your paging file to grow to
support virtual memory. Fragmentation also has this effect.
~ 27 ~
Use the % Free Space and Free Megabytes counters to monitor disk space. If the available space is becoming low,
you might want to run Disk Cleanup in the Disk Properties dialog box, compress the disk, or move some files to
other disks. Notice that disk compression incurs some performance loss.
Another option is Remote Storage, which enables you to create virtual disk storage out of tape or optical drives.
When you use this service, infrequently accessed files are moved to tape or to other media storage. Remote Storage
volumes are well suited for data that you need to access only at certain intervals, such as quarterly reports.

 Account operator
By default, Account Operators have permission to create, modify, and delete accounts for users, groups, and
computers in all containers and organizational units of Active Directory except the Built-in container and the
Domain Controllers.
Account Operators do not have permission to modify the Administrators and Domain Admins groups, nor do they
have permission to modify the accounts for members of those groups.
 Server operator
Server Operators is a local group that allows a user to perform general administrator tasks. These tasks include
sharing server resources, performing file backup and recovery, etc. As with other operator accounts, Server
Operators can also log on to a server locally and shut it down. Server Operators can perform most common server
administration tasks.
Members of this group can perform server management tasks such as creating, changing, and deleting shared
printers, shared directories, and files. They can also backup and restore files, lock the server console and shutdown
the system, but they cannot modify system policies or start and stop services.
 Domain administrator settings
The domain administrator creates, Edit and deletes users, manages domains settings and View domains statistics.
The domain administrator account members are allowed administrativeprivileges for the entire domain.
By default, the group has thelocal Administrator account on the Domain Controller as itsmember.
When a computer joins a domain, the Domain Administrator groupis added to the Administrators group.
When a server becomes adomain controller, the Enterprise Administrator group also is added tothe Administrators
group. The Administrators group has built-incapabilities that give its members full control over the system.The
group is the default owner of any object that is created by a member of the group.

~ 28 ~

You might also like