0% found this document useful (0 votes)
42 views

Chapter-1-: 1.1. What Is SQL?

The document summarizes basic SQL concepts for querying and manipulating data in a relational database. It describes SQL as a non-procedural language used to access and modify data in database tables. The SELECT statement is used to query data by retrieving records that match certain criteria. Optional clauses like WHERE, ORDER BY, GROUP BY, HAVING allow filtering, sorting, grouping and aggregating records. INSERT, UPDATE, DELETE statements are used to modify data.

Uploaded by

Ayele Mitku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Chapter-1-: 1.1. What Is SQL?

The document summarizes basic SQL concepts for querying and manipulating data in a relational database. It describes SQL as a non-procedural language used to access and modify data in database tables. The SELECT statement is used to query data by retrieving records that match certain criteria. Optional clauses like WHERE, ORDER BY, GROUP BY, HAVING allow filtering, sorting, grouping and aggregating records. INSERT, UPDATE, DELETE statements are used to modify data.

Uploaded by

Ayele Mitku
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Database II

Chapter-1- Reading and Writing Data with SQL

1.1. What is SQL?


SQL is a non-procedural language used for accessing field and record values in
relational database tables.

A non-procedural language essentially submits a single command, with a


questioning or querying type nature. SQL is a non-procedural language consisting of
single commands, where the database itself does a lot of the work in deciding how
to get that information. On the other hand, a procedural language contains blocks of
commands. Those blocks of commands are sequences of distinct steps, typically
where each successive step is dependent on the result of the previous command in
the sequence.

In most relational databases, SQL does have the capability to function in a limited
procedural fashion, allowing the programmer to determine partially how a database
is accessed. Traditionally, SQL procedural code is used to write what are called
stored procedures, triggers, database events, or database procedures. There are
other names for these code blocks, depending on the database in use. Procedural
SQL code is generally simplistic and can sometimes allow the inclusion of basic
programming constructs such as IF statements, CASE statements, and so on.

So, SQL is a simple non-procedural programming language allowing single line


commands. These single line commands are used to access data stored in database
table structures.

1.2. The Basics of Queries

The basics of SQL consist of a number of parts. What a simple SQL statement can do
is categorized and explained below.

Query Statements:
Querying a database is performed with a single command called the SELECT
command. The SELECT command creates queries, and has various optional clauses
that include performing functions such as filtering and sorting. Queries are used to
retrieve data from tables in a database. There are various ways in which data can be
retrieved from tables and each of these is illustrated below.

Page 1 of 22
Database II

 Basic query—the most simple of queries retrieves all records from a single
table.
 Filtered query—A filtered query uses a WHERE clause to include or exclude
specific records.
 Sorted query—sorting uses the ORDER BY clause to retrieve records in a
specific sorted order.
 Aggregated query—The GROUP BY clause allows summarizing, grouping, or
aggregating of records into summarized record sets. Typically, aggregated
queries contain fewer records than the query would produce, if the GROUP
BY clause were not used. A HAVING clause can be used to filter in, or filter
out, records in the resulting summarized aggregated record set. In other
words, the HAVING clause filters the results of the GROUP BY clause, and not
the records retrieved before aggregation.
 Join query—a join query joins tables together, returning records from
multiple tables. Joins can be performed in various ways, including inner joins
and outer joins.
 Nested queries—a nested query is also known as a sub-query, which is a
query contained within another query (a parent or calling query). Nesting
implies that sub-queries can be nested in multiple layers and thus a sub-
query itself can also be a calling query of another sub-query.
 Composite queries—a composite query is a query that merges multiple
query results together, most often using the UNION keyword.

Data Change Statements


 INSERT—The INSERT command is used to add new records to a table.
 UPDATE—The UPDATE command allows changes to one or more records in
a table, at once.
 DELETE—The DELETE command allows deletion of one or more records
from a table, at once.

Page 2 of 22
Database II

Database Structure Change Commands


These commands allow alterations to metadata (the data about the data). Metadata
in a simple relational database comprises tables and indexes. Table metadata
change commands allow creation of new tables, changes to existing tables, and
destruction of existing tables. Table metadata commands are CREATE TABLE,
ALTER TABLE, and DROP TABLE commands.

1.3. Querying a Database Using the SELECT Statement


1.3.1. Basic Query:
Syntax:
S ELEC T attri b ute_li s t FR OM tab le_li s t ;
Examples:

Statement: What it does


SELECT id, fname, lname Returns list of id numbers, first name and last name
FROM student ; of all students in the student table
Returns list of all fields/attributes of all students in
SELECT * FROM student ;
the student table
SELECT s.fname, s.lname , d .title It uses aliases s and d for the tables student and
FROM student s JOIN department department, respectively. Then it extracts student
d ON s .department =d .dep_code ; first name, last names and their department titles.

SELECT student.fname, It extracts same information above (first name, last


student.lname , department .title name and department title), but it doesn’t implement
FROM student JOIN department aliases for tables.
ON student .department
=department .dep_code ;
SELECT s.fname, s.lname ,c.title, It uses the aliases s, e, and c for the tables student,
c.cr_hr, e.grade enrollment, and course respectively. It then extracts
FROM student s JOIN enrollment e student first name, last name, course titles, credit
ON s .id =e .st_id JOIN course c on hour, and grade of all students that are enrolled for
c.code=e.course ; courses.

Page 3 of 22
Database II

Note: Using shorter alias names can help to keep SQL code more easily readable,
particularly for programmers in the future having to make changes. Maintainable
code is less prone to error and much easier to tune properly.
1.3.2. Filtering Data with the WHERE Clause
Statement: What it does
ASELECT
filteredcr_hr,
query title
uses the WHERE
FROM clause to include, orExtracts
course
exclude, specific
course credit records.
hour and
title of all courses that have a
WHERE cr_hr
Following are=some
3; demonstrative examples: credit hour of 3.
Extracts course credit hour and
SELECT cr_hr, title FROM course
title of all courses that have a
WHERE cr_hr != 3; credit hour different from 3.
SELECT s.fname, s.lname , d .title FROM It extracts student first name, last
student s JOIN department d ON s .department =d names and their department titles
.dep_code WHERE d.faculty =’technology’ ; under technology faculty.

SELECT s.fname, s.lname , c .title, c.cr_hr,


c.category Extracts student fname, lname,
FROM student s JOIN enrollment e ON course title, course credit hour, and
category for which the students are
s.id=e.st_id JOIN course c ON e.course = c.code
registered for main courses.
WHERE c.category ='main';
SELECT cr_hr, title FROM course Extracts course credit hour and
WHERE cr_hr BETWEEN 3 and 5; title from courses that have a
credit hour of between 3 and 5.

SELECT cr_hr, title FROM course Extracts course credit hour and
WHERE cr_hr IN (2,3,4); title from courses that have a
credit hour of 2, 3, or 4.

1.3.3. Precedence Rule of AND, OR, and NOT operations


Without using the parenthesis or bracket operator, i.e. ( ), the order of precedence
from high to low precedence is NOT, AND, OR. This means if a logical expression
contains the three operators, then the NOT will execute first, then the AND finally
the OR will execute.

Page 4 of 22
Database II

If a parenthesis is used, the one contained in the parenthesis is executed first.


Following are some examples:

Statement: What it does


Extracts credit hour and title of all courses
SELECT cr_hr, title FROM course
whose title begins with “Introduction” and with
WHERE cr_hr = 3 AND title LIKE
a credit hour of 3. It also extracts all MAIN
‘Introduction%’ OR category = ‘Main’;
courses!

Extracts course credit hour and title of all MAIN


SELECT cr_hr, title FROM course
courses that have a credit hour of 3 and also
WHERE cr_hr = 3 AND (title LIKE
courses whose title begins with ‘Introduction’
‘Introduction%’ OR category = ‘MAIN’);
having a credit hour of 3.

SELECT cr_hr, title FROM course WHERE NOT Extracts credit hour and title of INTRODICTION
cr_hr =3 AND title LIKE ‘Introduction%'; courses having a credit hour of other than 3.

Extracts credit hour and title of courses having a


SELECT cr_hr, title FROM course WHERE NOT
credit hour of other than 3 or courses whose
(cr_hr =3 AND title LIKE ‘Introduction%');
title doesn’t begin with ‘Introduction’.

SELECT title FROM course WHERE NOT cr_hr Extracts titles of all MAIN courses having a
=3 AND category =’MAIN’ OR title credit hour of other than 3 OR it extracts course
LIKE‘Introduction%'; whose title begins with ‘Introduction’.

Page 5 of 22
Database II

1.3.4. Sorting Data with the ORDER BY Clause


Sorting records in a query requires use of the ORDER BY clause, as demonstrated by
the following examples. The sorting criteria can be one or more conditions.

Statement: What it does

Extracts credit hour and course titles of all courses


SELECT cr_hr, title FROM course
and sort them by increasing order of their credit
ORDER BY cr_hr ;
hours.

SELECT cr_hr, title FROM course


Same as above; it sorts in ASCENDING by credit hour.
ORDER BY cr_hr ASC ;

SELECT cr_hr, title FROM course Same as above; but it sorts in DESCENDING by credit
ORDER BY cr_hr DESC ; hour.

Extracts credit hour and course titles of all courses


SELECT cr_hr, title FROM course ORDER BY and sort them by increasing order of their credit
cr_hr, title ; hours; and if two courses have the same credit hour,
then they are sorted by their title.

1.3.5. Aggregating with the GROUP BY Clause


An aggregated query uses the GROUP BY clause to summarize repeating groups of
records into aggregations of those groups.

If there is a ‘WHERE’ clause, the GROUP BY clause comes after it. And if there is an
‘ORDER BY’ clause, the GROUP BY clause then comes before it.

Following are some examples:

Page 6 of 22
Database II

Statement: What it does

SELECT d.title , COUNT (c.code ) FROM department


Extracts name of departments along with the
d JOIN course c ON d .dep_code =c
.offering_dep GROUP BY d.title ;
number of courses under each department.

SELECT d.title, COUNT (s.department) FROM


Extracts name of departments along with the
department d JOIN student s on d.dep_code
=s.department GROUP BY d.title ; number of students under each department.

SELECT d.title, COUNT (s.department) FROM


department d JOIN student s ON d.dep_code Extracts name of departments which have a
=s.department GROUP BY d.title HAVING COUNT total of more than 5 students.
(s .department ) >5;

SELECT s.program, COUNT (*) FROM student s Extract the number of students in each
GROUP BY s.program; program (Masters, Degree, and TVET)

SELECT fname,COUNT (course ), SUM (cr_hr ) Extracts first name of all students along with
FROM student JOIN enrollment ON id=st_id the total number of courses each student took
JOIN course ON enrollment.course = and also the sum of credit hours of those
course.code GROUP BY fname; courses

Note: Above the ‘HAVING’ clause is used to filter data like the ‘WHERE’ clause.

A common programming error is to get the purpose of the WHERE and HAVING
clause filters mixed up. The WHERE clause filters records as they are read (as I/O
activity takes place) from the database. The HAVING clause filters aggregated
groups, after all database I/O activity has completed. Don’t use the HAVING clause
when the WHERE clause should be used, and vice versa.

Page 7 of 22
Database II

1.3.6. Join Queries


A join query is a query retrieving records from more than one table. Records from
different tables are usually joined on related key field values. The most efficient and
effective forms of join are those between directly related primary and foreign key
fields. There are a number of different types of joins:

Inner Join
An intersection between two tables using matching field values, returning records
common to both tables only.

Cross join
This is also known mathematically as a Cartesian product. A cross join merges all
records in one table with all records in another table, regardless of any matching
values.

Outer join
It returns records from two tables as with an inner join, including both the
intersection between the two tables, plus records in one table that are not in the
other table. Any missing values are typically replaced with NULL values. Outer joins
can be of the following three forms:

 Left outer join—all records from the left side table plus the intersection of
the two tables. Values missing from the right side table are replaced with
NULL values.

 Right outer join—all records from the right side table plus the intersection
of the two tables. Values missing from the left side table are replaced with
NULL values.

 Full outer join—the intersection plus all records from the right side table not
in the left side table, in addition to all records from the left side table not in
the right side table.

Self join
A self join simply joins a table to itself, and is commonly used with a table containing
a hierarchy of records. A self join does not require any explicit syntax other than
including the same table in the FROM clause twice.

Page 8 of 22
Database II

1.3.7. Nested Queries


A nested query is a query containing other sub queries or queries contained within
other queries. SQL server uses the IN set operator to nest one query within another,
where one value is checked for membership in a list of values.

Statement: What it does

SELECT * FROM course WHERE course.code IN Extracts course information for which
(SELECT e.course FROM enrollment e) ; students are registered.

SELECT * FROM course WHERE course.code NOT IN Extracts course information for which NO
(SELECT e.course FROM enrollment e) ; student is registered.

SELECT DISTINCT s.fname,s.lname FROM student s


WHERE s.id IN Extracts student first name and last name
(select e.st_id from enrollment e); which are registered for a course

1.3.8. Composite Queries


The UNION operator is used to combine two separate queries into a merged
composite query. Both queries must have the same data types for each field, all in
the same sequence.

Following are some examples:

Page 9 of 22
Database II

Statement: What it does


SELECT fname,lname,division,gender FROM student
WHERE division ='regular' AND gender='F' Extracts name, division and gender of
UNION REGULAR FEMALE students OR
SELECT fname,lname,division,gender FROM student EXTENSION MALE students.
WHERE gender='M' and division = 'Extension';
SELECT code,title,cr_hr FROM course
WHERE cr_hr>3 AND offering_dep IN
Extracts course code, title, and credit
(SELECT code FROM department WHERE hour of all courses which belong to
faculty=’Technology’) one of the following:
UNION  Courses in technology faculty
and having a credit hour of
SELECT code,title,cr_hr FROM course greater than 3 OR
WHERE category=’common’ AND offering_dep IN  Common courses in health
(SELECT code FROM department WHERE faculty
faculty=’Health’);

1.4. Changing Data in a Database


Changes to the data stored in a database can be performed using the INSERT,
UPDATE, and DELETE commands.

The INSERT INTO Command

The syntax for the insert command is:

I N S E R T I N T O t a b le [ ( fi e ld1, fi e ld2, . .. , fi e ldN ) ] V A L U E S ( va lue 1, va lue 2, …, va lue N);

In the above syntax, ‘table’ is the name of the table that you are going to insert data.
F i le d1, fi e ld2, …., fi e ldN are list of fields in the table and va lue 1, va lue 2, …., va lue N
refers to the values that you are going to insert in the corresponding fields.

Note: In the above syntax, the list of fields is optional.

Following is a demonstration for the INSERT INTO command:

Page 10 of 22
Database II

Statement: What it does

INSERT INTO student (id, fname, lname) VALUES Inserts id, first name, and last name of
(‘scr/0558/90’, ‘Adem’, ‘Kedir’) ; one student.

INSERT INTO student VALUES (‘scr/0558/90’, Same as above but the field list is not
‘Adem’, ‘Kedir’) ; listed.

The UPDATE Command


Used to change or modify data in tables. The syntax is:

U P D A T E tbl _Na me SE T f iel d 1=val u e1 [, ..., f iel d N=val u eN] [ W H E R E … ] ;

And following are examples on the UPDATE statement:

Statement: What it does


Sets the credit hour to 2 and category to
UPDATE course SET cr_hr=2, category=’Main’
WHERE cr_hr=1; ‘Main’ of all courses that have a credit hour
of 1.

Sets the grade submission date of all courses


UPDATE enrollment SET
submit_date =DATEADD (MONTH,5,enroll_date ); in the enrollment table to 5 months
beginning from the enrollment date.

Page 11 of 22
Database II

The DELETE Command

This command is used to delete records in a table, which you can set criteria for
deletion. The syntax is:

D E L E T E F R O M tb l_Na me [ W H E RE … ] ;

Statement: What it does


DELETE FROM course WHERE cr_hr=1; Deletes all courses that have 1 credit hour.

DELETE FROM course; Deletes all courses.

1.5. Transactions
A transaction allows us to make change to the data in a relational database. To save
this change, the COMMIT command is used. And if you want to remove those changes
the transaction made to the data in the database, i.e. not to save the changes, the
ROLLBACK command is used.

A transaction specifies a sequence of Transact-SQL statements that is used by database


programmers to package together read and write operations, so that the database
system can guarantee the consistency of data. There are two forms of transactions:

 Implicit: Specifies any single INSERT, UPDATE, or DELETE statement as a


transaction unit.

 Explicit: Generally a group of Transact-SQL statements, where the beginning


and the end of the group are marked using statements such as BEGIN
TRANSACTION, COMMIT, and ROLLBACK.

When you use the explicit form of transactions, you use the global Transact-SQL
variable @@error to detect if there is an error during the execution of the transaction.

Following are examples:

Page 12 of 22
Database II

Example 1:
USE mystud;
UPDATE student SET division=’extension’ WHERE division=’weekend’
IF (@@error <> 0) ROLLBACK;

Example 2:
USE mystud;
BEGIN TRANSACTION;
DELETE FROM student WHERE department=’dep10’ AND division=’weekend’;
COMMIT TRANSACTION;

Hands on Exercises on Transactions:


Build a Transact SQL statement for each of the following activities.

i. Sets the grade of all extension computer science


students that scored ‘B’ to ‘A’.
ii. Sets the student group of all extension computer
science students to 2.
iii. Update the credit hour of all supportive courses to 2
and that of elective courses to 3.
iv. Change the name of the faculty of all ‘Business’
departments to ‘Business Management’ and also all
‘Accounting’ department to ‘Finance and Accounting’.

Chapter-2- Views and Database Security

Page 13 of 22
Database II

2.1. What is view?


A base table stores data on a disk. But, in case of views, their contents do not
exist/stored on a disk. A view creates a logical overlay without copying data from
tables. They are called virtual tables. Views might hurt performance. Query a view
and you query the underlying tables directly. Materialized views are physical copies
of data. Query a materialized view and you query the materialized view, and not the
underlying tables.

Views are usually used by administrators to implement security, down to the record
and field levels. In other words, a view can be used to restrict specific users to access
only specific records in a table. This is because a view contains a query. That query
can have a WHERE clause filter, restricting the records returned from underlying
tables.

2.2. How to Create a View


Views are created with the CREATE VIEW statement. And this statement must be
the only statement in a batch of statements. To do this, the GO statement is used.

Views are used to increase the security of the data in the database by increasing its
confidentiality.

With views, you can create a logical grouping of the rows in a table and expose each
logical group to the user that has permission to access it.

Following are some examples:

Page 14 of 22
Database II

Examples:

Statement: What it does


GO It creates a view of id
CREATE VIEW comp_stud AS (SELECT ID, fname, lname number, first name and
last name of students
FROM student whose department code is
WHERE department ='dep01'); ‘dep01’.
GO
CREATE VIEW tech_ext_stud AS
(SELECT ID, fname, lname, department,division Creates a view of
FROM student technology faculty
WHERE division='extension' and department IN extension students.
(SELECT dep_code FROM department
WHERE faculty='Technology'));
GO
CREATE VIEW tech_ext_stud AS
(SELECT ID, fname, lname, department,division Same as above but it uses
the JOIN SQL statement
FROM student s JOIN department d ON
instead of nesting
s.department=d.dep_code AND queries.
s.division='extension' AND
d.faculty='Technology'));

Hands on Exercises on Views:


Build a view using Transact SQL statements for each of the following:

i. A view that contains id, first name, last name, and


division of computer science students
ii. ***Only id number and grade of computer science regular
students that are registered for the course ‘COMP100’ by
the year 2017 first semester
iii. Id number and department title of students that have scored
an ‘F’ or an ‘NG’ in at least one MAJOR course.
iv. Course code, title, credit hour and course category of all
courses that are in technology faculty.

2.3. Database Security System in SQL Server 2008

Page 15 of 22
Database II

General Overview
Database engine security system is composed of two different security subsystems:

 Windows security: specifies security at the operating system level—that is,


the method by which users connect to Windows (the computer) using their
Windows user accounts. This method of authentication is also called Windows
authentication.

 SQL Server security: specifies the additional security necessary at the


system level— that is, how users who have already logged on to the operating
system can subsequently connect to the database server. SQL Server security
defines a SQL Server login (or simply a “login”) that is created within the
system and is associated with a password. Some SQL Server logins are
identical to the existing Windows user accounts, i.e. they can be mapped from
existing windows user accounts. Authentication using this subsystem is called
SQL Server authentication. This technique of authentication method is older
fashion, which is used in previous versions of SQL server, so for current and
coming versions, use the Windows authentication method.

In addition to Windows user accounts and logins, there are also Windows groups
and SQL Server roles. A Windows group is a collection of Windows user accounts.
Assigning a user account membership to a group gives the user all the permissions
granted to the group. Similarly, a role is a collection of logins.

Generally, the database security system revolves around the following basic
concepts:

 Authentication
Authentication is the process of validating user credentials to prevent unauthorized
users from using the system. Authentication can be checked by requesting the user
to provide information such as username and password.

To configure the authentication mode (to make it either Windows or SQL server
mode), do the following:

I) Right click on the name of the server in the


Management studio

Page 16 of 22
Database II

II) Click the “Properties” option


III) From the “Server Properties” dialog box, choose
the “Security” option from the left pane.
IV) Now you can choose the authentication mode you
want
V) Click the “Ok” button

 Data Encryption
Data encryption is the process of scrambling information so that it is not
understandable until it is decrypted by the intended recipient. This is made with a
help of encryption/decryption software.

 Authorization
Authorization is the process that is applied after the identity of a user is verified
through authentication. During this process, the system determines what resources
the particular user can use. In other words, structural and system catalog
information about a particular entity (table, row etc) is now available only to a
principal. A principal is a user or a subject that has permission to access an entity.

There are three Transact-SQL statements related to authorization:

 GRANT: grants permissions to resources


 DENY: denies permissions to resources
 REVOKE: removes one or more previously granted or denied permissions

 Change Tracking
This means that every action of unauthorized user is tracked, i.e. followed up, and
documented on the system.

2.4. SQL Server Logins

Page 17 of 22
Database II

Logins can be created using the create DDL statement or using the management
studio.

The following syntax is used to create a login using the CREATE DDL command:

CREATE LOGIN login_name FROM WINDOWS;

Example: CREATE LOGIN [my_pc\user1] FROM WINDOWS;

The above statement creates a login with the name my_pc\user1. When you
create a login from an existing windows user account, the name should be composed
of the computer name and the user account name. Above, ‘my_pc’ is the name of the
computer and user1 is the name of the user account.

NOTE: To create a login, the current account you used to log in to the system must
have been granted for the action!

To create a login using the management studio, follow the steps below:

I) Go to the ‘Security’ server object listed in the


object explorer window
II) Expand it by clicking on the ‘+’ sign
III) Right click on the ‘logins’ option and select the
‘New Login…’ option
IV) Click on the ‘Search’ command button to search for
the windows user account to which the login is
mapped.
V) If you want, select a default database which is the
database automatically connected and opened when
you log in using your login.
VI) Finally, click OK.

Page 18 of 22
Database II

2.5. Database User Accounts


Database user accounts are user accounts that let a login, or a windows user
account, to access a specific database, or database object. These database user
accounts can be mapped from a windows user account (or windows group) or a SQL
server login (or a role which is a group of logins).

Therefore, system users, which are authenticated to connect to the database server
instance, must have a database user account for each database they want to use.

You can use the CREATE USER statement or the management studio to work with
database users.

Using the CREATE USER statement:

CREATE USER techno_dean FROM LOGIN [mypc\user1];

The above statement creates a database user named techno_dean from the
existing Windows user account named user1 on the computer named mypc.

Using the management studio:

I) Go to the object explorer window and click the ‘+’ sign


in front of your database name
II) Go to the security database object (+Security) and
click the ‘+’ sign
III)Right click on the ‘Users’ option and click the ‘New
User’ menu item
IV) Type the name of the database user and select the
login to which the database user is mapped
V) Finally, click OK.

Each database has its own specific users. Therefore, the CREATE USER statement
must be executed once for each database where a user account should exist. Also, a
SQL Server login can have only a single corresponding database user for a given
database.

Page 19 of 22
Database II

2.6. Schema
A schema is a collection of database objects (such as tables) that is owned by a user,
and having a name.

You can work with schemas using DDL or the management studio.

Using DDL, you can create a schema and assign a view to it as follows:

CREATE SCHEMA cs_manager AUTHORIZATION techno_dean;


GO
CREATE VIEW techno_faculty AS (SELECT id,fname,lname, department
FROM student s JOIN department d ON s.department =d.dep_code
WHERE faculty ='technology' ;
GO

GRANT SELECT TO cs_department;

DENY UPDATE TO cs_department;

DENY DELETE TO cs_department;

The above DDL creates a schema named cs_manager and makes the database user
techno_dean the owner of the schema. Next it creates and assigns a view named
techno_faculty to the schema. Finally, it gives a SELECT authorization to another
database user named cs_department and denies an UPDATE and DELETE activity or
permission on the view.

Using the management studio, you can create a schema as follows:

I) Go to the object explorer window and click the ‘+’ sign


in front of your database name
II) Go to the security database object (+Security) and
click the ‘+’ sign
III)Right click on the ‘Schemas’ option and click the
‘New Schema’ menu item
IV) Type a name for the new schema and search the schema
owner and select it
V) Finally, click OK.

Page 20 of 22
Database II

2.7. Roles
When several users need to perform similar activities in a particular database, you
can add a database role, which specifies a group of database users that can access
the same objects of the database. These database users can be Windows user
accounts or SQL Server logins.

Note that roles are of two types: server roles and database roles. Server roles are
assigned activities related to the server and database roles specify activities related
to databases.

Following are examples of server roles:

 sysadmin: members of this role can perform any activity in the databases
under the current database server instance
 dbcreator: can create and modify databases under the database server
 securityadmin: can manage LOGINS and can also manage CREATE DATABASE
permissions

And the following are examples of database roles:

 db_owner: users of this role can perform almost activities in the current
database.
 db_accessadmin: members of this role can add/remove other database users
 db_backupoperator: users who can backup the database

On top of server roles and database roles, you can create a new database role using
the management studio as follows:

I) Go to the object explorer window and click the ‘+’ sign


in front of your database name
II) Go to the security database object (+Security) and
click the ‘+’ sign
III)Right click on the ‘Database Roles’ option and click
the ‘New Database Role’ menu item

Page 21 of 22
Database II

IV) Type a name for the new database role and assign an
owner for this role
V) Then, find database users which you want to have this
role from the bottom section of the dialogue box
VI) Finally, click OK

Page 22 of 22

You might also like