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

advanced database lab manual (2)

The document provides a comprehensive guide on SQL basics, including creating and managing databases and tables, performing operations like inserting, updating, and deleting records, and establishing relationships between tables. It also covers advanced SQL concepts such as joins, subqueries, and aggregate functions, along with practical examples and syntax for each operation. Additionally, it discusses query processing and optimization techniques to enhance database performance.

Uploaded by

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

advanced database lab manual (2)

The document provides a comprehensive guide on SQL basics, including creating and managing databases and tables, performing operations like inserting, updating, and deleting records, and establishing relationships between tables. It also covers advanced SQL concepts such as joins, subqueries, and aggregate functions, along with practical examples and syntax for each operation. Additionally, it discusses query processing and optimization techniques to enhance database performance.

Uploaded by

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

Part I:-Fundamental Parts:-Understanding SQL Basics and Creating Database Files

i. Operating on Database
a. Create database
Syntax:-CREATE DATABASE database_name;
Example:- CREATE DATABASE tmp;
b. Delete database
DROP DATABASE database_name;
Example: drop database tmp;
c. Use database
USE DATABASE database_name; Or USE DatabaseName;
Example:- use tmp;
ii. Table/relation Operation
a. Create table
Syntax:- CREATE TABLE tablename(fields and their types);
i.e CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns ) );
Example:- CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESSS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) );
To insert values to the table we use the syntax as
INSERT INTO table_name( column1, column2....columnN) VALUES
( value1, value2....valueN);
Example:- insert into CUSTOMERS VALUES(1,'almaz',21,'kebele03',5000);
insert into CUSTOMERS VALUES(2,'hana',21,'kebele04',6000);
c. Delete table

Syntax:-DROP TABLE table_name;


Example:- DROP TABLE CUSTOMERS;
b. Deleting query :- to delete specific row The basic syntax of DELETE query
with WHERE clause is as follows:
DELETE FROM table_name WHERE [condition];
Example:- DELETE FROM CUSTOMERS WHERE ID = 1;
g. Updating data / tuples
Syntax:- UPDATE table_name SET column1 = value1, column2 =
value2...., columnN = valueN WHERE [condition];
Example:- UPDATE CUSTOMERS SET ADDRESSS = 'kebele05',
salary=1000.00 WHERE ID = 2;
h. Alter tables and columns
1. Add fields to a table
ALTER TABLE table_name ADD (column_1 column-definition, column_2
column-definition, ... column_n column_definition);
Example :-alter table CUSTOMERS ADD BDATE DATE;
2. Drop columns
ALTER TABLE table_name DROP COLUMN column_name;
Example :- alter table CUSTOMERS drop column BDATE
i. Make relations
1. One to many relation
First create a table like CREATE TABLE Departments (
-> DepartmentID INTEGER AUTO_INCREMENT NOT NULL,
-> Department varchar(50),
-> PRIMARY KEY(DepartmentID));
Then to make one to many relation we could write as
CREATE TABLE Employees (
-> EmployeeID INTEGER PRIMARY KEY AUTO_INCREMENT NOT
NULL,
-> FirstName varchar(20),
-> LastName varchar(20),
-> HourlySalary money
-> DateHired DATE,
-> DepartmentID INTEGER REFERENCES Departments(DepartmentID));
When you create a table like this, the interpreter would know that, in the
Employees table, the DepartmentID column is a foreign key.
Part II:- Advanced Parts
Create the following two tables
create table CUSTOMERS(
ID int primary key,
NAME varchar(20),
AGE int,
ADDRESSS varchar(20)
SALARY money);
create table CUSTOMERS
(
ID INT PRIMARY KEY,
NAME VARCHAR(20),
AGE INT,
ADDRESSS VARCHAR(20),
SALARY MONEY)

create table ORDERS(


OID INT PRIMARY KEY,
DATEE DATETIME,
CUSTOMER_ID INT FOREIGN KEY REFERENCES CUSTOMERS(ID),
amaount int)
insert into CUSTOMERS VALUES(1,'almaz',21,'kebele03',5000);
insert into CUSTOMERS VALUES(2,'hana',24,'kebele04',6000);
insert into CUSTOMERS VALUES(3,'eyob',22,'kebele05',7000);
insert into CUSTOMERS VALUES(4,'nati',28,'kebele07',8000);
insert into CUSTOMERS VALUES(5,'sami',25,'kebele08',9000);
insert into CUSTOMERS VALUES(6,'kal',29,'kebele09',10000);
insert into CUSTOMERS VALUES(7,'nahom',23,'kebele10',11000);
insert into CUSTOMERS VALUES(8,'sara',26,'kebele11',12000);
insert into CUSTOMERS VALUES(9,'abriham',24,'kebele12',13000);
insert into CUSTOMERS VALUES(10,'yisak',20,'kebele13',14000);
insert into ORDERS VALUES(1,'1-15-2024',1,4);
insert into ORDERS VALUES(2,'1-15-2022',2,5);

ID NAME AGE ADDRESSS SALARY


1 Almaz 21 kebele03 5000.00
2 Hana 21 kebele05 1000.00
3 Eyob 22 kebele05 7000.00
4 Nati 28 kebele07 8000.00
5 Sami 25 kebele08 9000.00
6 Kal 29 kebele09 10000.00
7 Nahom 23 kebele10 11000.00
8 Sara 26 kebele11 12000.00
9 abriham 24 kebele12 13000.00
10 Yisak 20 kebele13 14000.00
Table1: CUSTMERS TABLE DATA

OID DATE ID AMOUNT

1 2024-01-15 00:00:00.000 1 4

2 2022-01-15 00:00:00.000 2 5
Table 2 ORDERS TABLE DATA
A. Relational Algebras
1. Selection
Syntax:-SELECT column1, column2, columnN FROM table_name;
Or
SELECT column1, column2, columnN FROM table_name WHERE
[condition]
Or
SELECT column1, column2, columnN FROM table_name WHERE
[condition1] AND [condition2]...AND [conditionN];
Or
Database System By Abebe B SELECT column1, column2, columnN
FROM table_name WHERE [condition1] OR [condition2]...OR
[conditionN]
Example:- SELECT ID, NAME, SALARY FROM CUSTOMERS;
2. Projection
Projection --> for selecting the columns of table; and
Selection ---> to select the rows of table?
To project we use select statement.
Example ;-select NAME FROM CUSTOMERS

NAME

Almaz

Hana

Eyob

Nati

Sami

Kal

Nahom

Sara
Abriham

Yisak

3. Cartesian product
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product
of the sets of records from the two or more joined tables. Thus, it equates
to an inner join where the join-condition always evaluates to True or
where the join-condition is absent from the statement.
Syntax:The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2... FROM table1, table2 [,
table3 ]
SQL>SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS,
ORDERS;
4. Join
The SQL Joins clause is used to combine records from two or more
tables in a database. A JOIN is a means for combining fields from two
tables by using values common to each. Consider the above two tables,
i. INNER JOIN
The most frequently used and important of the joins is the INNER JOIN.
They are also referred to as an EQUIJOIN. The INNER JOIN creates a
new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of
table1 with each row of table2 to find all pairs of rows which satisfy the
join-predicate. When the join-predicate is satisfied, column values for
each matched pair of rows of A and B are combined into a result row.

Syntax: SELECT table1 column1, table 1column2... FROM table1


INNER JOIN table2 ON table1.common_filed = table2.common_field;

Or

SELECT col1, col2, col3... FROM table_name1, table_name2 WHERE


table_name1.col2 = table_name2.col1;

Or
Select column-name-list from table-name1 inner join table-name2 where
column-name.table1=column-name.table2

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS


INNER JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;

ii. .OUTER JOIN


LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there
are no matches in the right table.
Syntax:-SELECT table1.column1, table2.column2... FROM table1
LEFT JOIN table2 ON table1.common_filed = table2.common_field;
Example:- SQL> SELECT ID, NAME, AMOUNT, DATE FROM
CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;
Right join
The SQL RIGHT JOIN returns all rows from the right table, even if
there are no matches in the left table.
Syntax:-
Syntax: SELECT table1.column1, table2.column2... FROM table1
RIGHT JOIN table2 ON table1.common_filed =
table2.common_field;
Example:
SQL> SELECT ID, NAME, AMOUNT, DATE FROM
CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;
FULL JOIN
The SQL FULL JOIN combines the results of both left and right
outer joins. The joined table will contain all records from both tables,
and fill in NULLs for missing matches on either side.
Syntax:
SELECT table1.column1, table2.column2... FROM table1 FULL
JOIN table2 ON table1.common_filed = table2.common_field; Here
given condition could be any given expression based on your
requirement.
Example:Let us join these two tables using FULL JOIN as follows:
SQL> SELECT ID, NAME, AMOUNT, DATE FROM
CUSTOMERS FULL JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;
5. Sql subquery
In sql it is possible to place a sql query inside another query known as sub
query for example
Select *from CUSTOMERS
Where age=(select min(age) from customers);
Select NAME FROM CUSTOMERS Where AGE=(select min(AGE) from
CUSTOMERS);
In a subquery the outer query‘s result dependent on the result set of the
inner subquery .
That is why subqueries are also called nested query.
Here the sql command
1. Excutes the subquery first ;select minimum age from the custumers table
2. Excute the outer query ;select rows whrere age is equal to the result of
sub query
Example 2
Suppose we want details of customers who have placed on order .here’s
how we can do.
select NAME from CUSTOMERS where CUSTOMER_ID IN(select CUSTOMER_ID FROM
ORDERS);
6.SQL aggregate functions
An aggregate function operates on many records and produces a summary; works with GROUP
BY.
Useful SQL Aggregate Functions

MIN returns the smallest value in a given column


MAX returns the largest value in a given column
SUM returns the sum of the numeric values in a given column
AVG returns the average value of a given column
COUNT returns the total number of values in a given column
COUNT(*) returns the number of rows in a table
SUM() Returns the sum
Aggregate functions are used to compute against a "returned column of numeric data" from your
SELECT statement. They basically summarize the results of a particular column of selected data.
 The count function Returns the number of items in expression. The data type returned is of
type int.
Syntax: COUNT ( [ALL | DISTINCT] <expression> | * )
Example: select COUNT(*), AVG(CUSTOMERS.SALARY) from
CUSTOMERS
- With the exception of the COUNT (*) function, all aggregate functions return a NULL if
no rows satisfy the WHERE clause. The COUNT (*) function returns a value of zero if
no rows satisfy the WHERE clause.
 The MAX function Returns the maximum value from expression. Max ignores any NULL
values.
Syntax: MAX ( [ALL | DISTINCT] <expression> )
Example: select MAX(CUSTOMERS.SALARY) from CUSTOMERS
 The MIN function Returns the smallest value from expression. Min ignores any NULL
values.
Syntax: MIN ( [ALL | DISTINCT] <expression> )
Example: select MIN(CUSTOMERS.SALARY) from CUSTOMERS
 The SUM function Returns the total of all values in expression. Sum ignores any NULL
values.
Syntax: SUM ( [ALL | DISTINCT] <expression> )
Example: select SUM(CUSTOMERS.SALARY) from CUSTOMERS
 The AVERAGE function Returns the average of the values in expression. The expression
must contain numeric values. Null values are ignored.
syntax: AVG ([ ALL | DISTINCT ] <expression>)
Example: select ID, avg(Employee.Salary) from CUSTOMERS

Query processing and optimization


Query processing
Activities involved in retrieving data from the database.
• Aims of QP:
– transform query written in high-level language (e.g. SQL),
into correct and efficient execution strategy expressed in low-
level language (implementing RA);
– Execute strategy to retrieve required data.

Query optimization
Activity of choosing an efficient execution strategy for processing query.
• As there are many equivalent transformations of same high-level query, aim
of QO is to choose one that minimizes resource usage.
• Generally, reduce total execution time of query.

• May also reduce response time of query.

--create database name DMUBC


create DATABASE DMUBC
use DMUBC
--create the following two tables
create table department(
Dnumber varchar(30) primary key,
Dname varchar(20)
)
create table Employee(
Eid int primary key,
Ename varchar(20),
Eage int,
Esex varchar(6),
Esalary money,
Dn varchar(30) foreign key references
department(dnumber)
)
select *from department
select *from Employee
--insert the following data into department table
Dnumbe Dname
r
1 Cs
2 IT
3 IS
4 management
5 Accounting

insert into department values('1','cs')


insert into department values('2','IT')
insert into department values('3','IS')
insert into department values('4','management ')
insert into department values('5','accounting')
--insert the following data into employee table
Eid Ename Eage Esex Esalary Dn
1 Abel 27 M 9000.00 1
2 Hiwot 28 F 10000.00 1
3 Aman 29 M 11000.00 2
4 Nati 30 M 12000.00 2
5 Samiri 31 F 13000.00 3
6 Sosi 32 F 14000.00 4
7 Dani 33 M 15000.00 5

insert into employee values(1,'abel',27,'m',9000,'1')


insert into employee values(2,'hiwot',28,'f',10000,'1')
insert into employee values(3,'aman',29,'m',11000,'2')
insert into employee values(4,'nati',30,'m',12000,'2')
insert into employee values(5,'samiri',31,'f',13000,'3')
insert into employee values(6,'sosi',32,'f',14000,'4')
insert into employee values(7,'dani',33,'m',15000,'5')
--develop query
Examples 1: retrieve average, minimum, maximum and
sum of salary for all employee.
select avg(Esalary) ,min(Esalary) ,max(Esalary)
,sum(Esalary)from Employee
or
select avg(Esalary) 'averge salary',min(Esalary) 'min
salary',max(Esalary) 'max salary',sum(Esalary)'sum
salary'from Employee
example 2:retrive all female employee who work on
computer science department
select *from department,Employee where Esex='f' and
Dname='cs'and Dnumber=Dn
example 3:retrive all female employee .
select *from department,Employee where Dnumber=Dn
and Esex='f'
Example 4: For each department, retrieve the department name, and the
number of employees in the department.
select Dname,count(*)'number of employee' from
department,Employee where Dn=Dnumber group by
Dname
Example5: Retrieve a list of employees and department name ordered
them alphabetically by their employee name
select Ename,Dname from department,employee where
Dn=Dnumber order by Ename
Privileging/Understanding Data Control Language (DCL)/
Authorizations
Transaction control language(TCL)
 Transaction: to perform some operation.
 This command is used to manage the changes made by DML
statements.
 Update, insert and delete operations are used to control the data in
table
 The transaction is implemented in the database using SQL keyword
transaction, commit, and rollback. Commit writes the changes
made by transaction into database and rollback removes temporary
changes logged in transaction log by database transaction.

Examples of TCL commands:

 COMMIT– saves all the work done


 ROLLBACK– rollbacks a transaction in case of any error occurs.

create table student


(
sid int primary key,
sname varchar(30),
lname varchar(30),
sage int
);
--TCL Command on insert operation
begin transaction
insert into student
values(2,'alemu','kebe',27);
commit transaction
--TCL command on update operation
begin transaction ;
update student set sname='ebe' where sid=2;
rollback transaction
--TCL commad on delete operation
begin transaction
delete from student where sid=2;
rollback transaction
Data control language (DCL)
 DCL is used to control user access in a database.
 This command is related to the security issues.
 Using DCL command, it allows or restricts the user from accessing
data in database schema.
Examples of DCL commands:
 GRANT-gives users’ access privileges to the database.
 REVOKE-withdraw user’s access privileges given by using the GRANT
command.

The DCL commands used to control security are:

 GRANT SELECT: Lets the user or group see the data in a


table or view..
 REVOKE SELECT: Prevents the user or group from seeing
data in a table or view..
 GRANT INSERT: Lets the user or group to add row(s) to a
table or view.
 REVOKE INSERT: Prevents users or groups from adding
row(s) to a table or view..
 GRANT UPDATE: Lets the user or group of users change
the values in the columns of a table or view.
 REVOKE UPDATE: Prevents the user or group of users
from changing the values in the columns of a table or view.
Database System By Abebe B
 GRANT DELETE: Allows a user or group of users to delete
row(s) in table or view
 REVOKE DELETE: Prevents a user or group of users from
deleting row(s) in a table or view.
 Creating Logins
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
 use the following Transact-SQL syntax:
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
 Use the following Transact-SQL syntax:
CREATE LOGIN [login_Name] WITH PASSWORD = 'password'
Example: CREATE LOGIN student WITH PASSWORD=’abc/123’
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
 Use the following Transact-SQL syntax:
CREATE USER <new user name> FOR LOGIN <login name>
Example: CREATE USER Admin1 for login Student
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.
To delete a database user using T-SQL code
 Use the following Transact-SQL syntax:
drop user user_name
For example:-drop user user22
Rename a database user

To rename a user, you use the ALTER USER ... WITH NAME statement:

Syntax:- ALTER USER user_name WITH NAME new_name;


For example :-alter user user1 with name=user3
Map the user with another login account

To map the user with another login account, you use following ALTER USER ...
WITH LOGIN statement:

Syntax:-ALTER USER user_name WITH LOGIN=new_login


For example, the following statements create a new login and map it with the
user user3.
create login login8 with password='987y'
alter user user3 with login=login8
 Managing Server and database Security
1. Creating Roles
Role is a random set of privileges that is granted to users.
After you create a database level role, configure the database-level permissions of
the role by using GRANT, DENY, and REVOKE.’
Syntax: CREATE ROLE role_name
Example: CREATE ROLE student
To add members to a database role, use the sp_addrolemember stored procedure.
-To add user u1 to be the member of student role, EXECUTE sp_addrolemember
‘student’,’u1’
Example;exec sp _ droprolemember student,u1
2. Granting Permissions
The GRANT statement is used to give privilege to users or roles.
Syntax:
GRANT<privilege list>ON <relation name or view name>TO <user/role list>;
Examples: GRANT SELECT ON student to u1
GRANT SELECT, INSERT, UPDATE (salary) ON employee to u1
3. Revoking Permissions
Revoke statement is used to withdraw privileges from a user without deleting that
user.
Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user names>;
Examples: REVOKE DELETE ON employee from u1
REVOKE DELETE, INSERT ON employee from u1
› Backup and restore database
Backup is the process by which you make a copy of your work for
safekeeping in an alternate location, in case your current work becomes lost
or corrupt.
› Create a full backup to disk
The command is BACKUP DATABASE databaseName. The "TO DISK" option
specifies that the backup should be written to disk and the location and filename to
create the backup is specified.
Example: BACKUP DATABASE DatabaseName TO DISK = 'D:\
backupFileName.BAK'
› Create a full backup with a password
This command creates a backup with a password that will need to be supplied
when restoring the database.
Example: BACKUP DATABASE databaseName TO DISK = 'D:\
backupfileName3.BAK'
WITH PASSWORD = 'Abc\123'
create database col
use col
create table student
(
sid int primary key,
sname varchar(30),
lname varchar(30),
sage int
);
--DCL
create login adm with password='12345'
create user st for login adm
create role role1
exec sp_addrolemember role1,st
grant insert on student to st
revoke insert on student from st
--backup and restore database
backup database col to disk='D:\ddf'
drop database col
restore database col from disk='D:\ddf'
Advance database lab exrecise
Exrcise1: Design a simple database for XYZ clinic
Suppose you are a database administration in XYZ clinic and assigned to create a
database that manages the DOCTOR,PATIENT and APPOINTMENT information.
Instruction: under this task you are expected to perform the following activities
based on the information .
1. Create database named XYZ clinic on sql server
2. Under XYZ clinic database create the table using the following information
Table 1: Doctor
Field Name Type Size Constraint
D id Varchar 50 Primary key
D name Int ---- Not null
D sex Varchar 6 Male or Female
Specialization Varchar 100 -----
D age Int ---- Between 18 and 60
D salary Money -- Not less than 5000

Table 2: PATIENT
Field Name Type Size Constraint
Patient record No Varchar 50 Primary key
P name Varchar 50 ----
P sex Varchar 6 Male or female
P age Int --- Not grater than 150

Table 3: APPOINTMENT

Field Name Type Size Constraint


Appointment ID Int --- Primary key, out
increment by1
Patient Record No Varchar 50 Foreign key
D id Varchar 50 Foreign key
Appointment Date Date time ----- --------

3. Change the column named “Dname” as type varchar size 50 from table
DOCTOR.
4. Add sample records in to the table as shown below
D id D name D sex Specialization D age Display
XYZ 123 Mikias Male Surgeon 40 11000
XYZ 124 Eden Female Haomatologist 45 18000
Xyz 125 Helen Female Internal 35 8000
medicine
specialists
XYZ 126 Bekalu Male Dermatologist 38 9000
XYZ 127 Surfel Male Dermatologist 55 9000
XYZ 128 Birhanu Male Surgeon 40 18000
Table 1. Lists of Doctors
Patien Record No P name P sex P age
P XyZ 111 Lemlem Female 12
PXyz 112 Hana Female 45`
PxyZ113 Belay Male 22
PXyz114 Woldu Male 91
Pxyz115 Teshome Male 55
Pxyz115 Zeru Male 1

Table 2 list of patient


Appointment ID Patien record No D id Appointment date
1 PxYz111 Xyz 123 2014-02-16
2 PXyz111 XYZ123 2014-02-26
3 PXyZ113 XYZ123 2014-02-16
4 PXYZ114 Xyz126 2014-02-04
5 PXyZ114 Xyz126 2014-02-21
6 PXYz115 XYZ123 2014-02-21
7 Pxyz115 XYZ127 2014-02-21
8 PXyz115 XYZ127 2014-02-06
Table 3. List of appointment dates
develop quires
Instruction: under this task you are expected to perform the following
activities based on the information provided.
a. Write sql statement to that can add 1500 Ethiopian birr for each Doctors
salary
b. Retrieve minimum ,maximum, average and sum of salary of doctor
c. Retrieve total number of Doctor in xyz cilinic
d. Write sql statement that can display the name of all patients who are
appointed on Date 2014-02-21
e. Write sql statement that can display the name of all female Hematologist
doctors whose age is above 40.
f. Develop sql statement that backup name back in local disk(C)
g. Write sql statement that can create backup for xyz_ Clinic database and save
the data base by writing sql command and develop sql query to recover the
database from the backup.
h. Configure the authentication method of the server to be Mixed Mode (SQL
Server and Windows)
i. Create SQL login account by name login1,login2 ,login3 and password
1234.
j. In the xyz_ Clinic database, create a user called user1 ,user2 and user3 by
the login account login1,login2 ,login3 respectively that is already created
on question #f.
k. In the xyz_ Clinic database, create a role called ICT and add the user
user1 ,user2 and user3 in this role.
l. grant SELECT ,update and delete permission for the user user1 on the
Doctor table with grant option for user2.
m. Revoke insert from user1
n. Show how to manage DML is mange by TCL commands with example
hence DML are insert, update and delete and TCL commands are
commit ,rollback etc.

create database xyz_clinic


use xyz_clinic
create table Doctor(
Did varchar(50) primary key,
Dname int not null,
Dsex varchar(6)check( Dsex in('male','female')),
Specialization varchar(100),
Dage int check (Dage between 18 and 60),
Dsalary money check(Dsalary>=5000),
);

create Table Patient(


Prno varchar(50) primary key,
pname varchar(50),
psex varchar(6) check(Psex in('male','female')),
Pagee int check(pagee <=150)
);
create table Appointment(
Aid int identity(1,1) primary key,
Prno varchar(50)foreign key references patient(Prno),
Did varchar(50) foreign key references Doctor(Did),
Adate datetime
);
--alter column
alter table Doctor alter column Dname varchar(50) not null
-- insert data for doctor table
insert into Doctor values('xyz123','mekides','male','surgon',40,'11000')
insert into Doctor values('xyz124','Eden','female','Haomatologist',45,'18000')
insert into Doctor values('xyz125','Helen','female','Internal medicine
specialists',35,'8000')
insert into Doctor values('xyz126','Bekalu','male','Dermatologist',38,'9000')
insert into Doctor values('xyz127','Surfel','male','Dermatologist',55,'9000')
insert into Doctor values('xyz128','Birhanu','male','surgon',40,'18000')
-- insert data for patient table
insert into Patient values('P XyZ 111','Lemlem','female',12)
insert into Patient values('P XyZ 112','Hana','female',45)
insert into Patient values('P XyZ 113','Belay','male',22)
insert into Patient values('P XyZ 114','Woldu','male',91)
insert into Patient values('P XyZ 115','Teshome','male',55)
insert into Patient values('P XyZ 116','Zeru ','male',1)
insert into Appointment values('P XyZ 111','xyz123','2014-02-16')
insert into Appointment values('P XyZ 111','xyz123','2014-02-26')
insert into Appointment values('P XyZ 113','xyz123','2014-02-16')
insert into Appointment values('P XyZ 114','xyz126','2014-02-04')
insert into Appointment values('P XyZ 114','xyz126','2014-02-21')
insert into Appointment values('P XyZ 115','xyz123','2014-02-21')
insert into Appointment values('P XyZ 115','xyz127','2014-02-21')
insert into Appointment values('P XyZ 115','xyz127','2014-02-06')
select*from Doctor
select *from Patient
select *from Appointment
-- a answer
update Doctor set Dsalary=Dsalary+1500;

--b answer
select min(Dsalary)as'min salary',max(Dsalary)as'max salary',sum(Dsalary)as'sum
salary',avg(Dsalary)as'avg salary' from Doctor

--c answer
select count(*)from Doctor
--d answer
select Pname from Patient,Appointment where Patient.Prno=Appointment.Prno
and Adate='2014-02-21'
--e answer
select Dname from Doctor where Specialization='Haomatologist'and Dage>40
-- f answer
backup database xyz_clinic to disk='E:/xyzclinc'
-- g answer first drop database
drop database xyz_clinic
restore database xyz_clinic from disk='E:/xyzclinc'
-- i answer
create login login1 with password='1234'
create login login2 with password='1234'
create login login3 with password='1234'
--j answer
create user user1b for login login1
create user user2 for login login2
create user user3 for login login3
-- k answer
create role ICT
exec sp_addrolemember ICT,user1b
exec sp_addrolemember ICT,user2
exec sp_addrolemember ICT,user3
--l answer
grant select,update,delete to user1b with grant option
grant insert to user1b
--m answer
revoke insert from user1b
-- n answer
create table stu
(
sid int primary key,
sname varchar(30),
lname varchar(30),
sage int
);
--TCL Command on insert operation
begin transaction
insert into stu values(2,'alemu','kebe',27);
commit transaction
--TCL command on update operation
begin transaction ;
update stu set sname='ebe' where sid=2;
rollback transaction
--TCL commad on delete operation
begin transaction
delete from stu where sid=2;
rollback transaction

exercise 2 create DMU database

create database dmu


use dmu
create table student (
sid int primary key not null,
sname varchar(20),
ssex varchar (2)check(ssex in('f','m')),
sage int check (sage >40)
);
--alter the table by adding column
alter table student add Bdate date ;
--alter the table by drop the column
alter table student drop Bdate ;
select *from student
insert into student values(1,'abebe','f',45,'12-17-2020');
insert into student values(2,'kebede','m',46,'12-18-2020');
insert into student values(3,'aster','f',47,'11-17-2020');

insert into student values(4,'almaz','f',48,'10-19-2020',2);

alter table student add tid int foreign key references teacher(tid);
create table teacher(
tid int primary key not null,
tname varchar(20),
tsex varchar check(tsex in('f','m')),
tsalary money check (tsalary between 3000 and 6000)
);
select * from teacher
-- moeny data type can be considered as character or integer
insert into teacher values (1,'hibist','f',5000);
insert into teacher values (2,'amex','m','5000');

select *from student


-- retrive the name of student that the name is contain letter a in any position
select sname from student where sname like '%a%';
--retrive the name of student the name start by letter a
select sname from student where sname like 'a%';

--retrive the nname of student the name is end by a


select sname from student where sname like '%a';
--retrive the name of teacher that teacher salary end by 00
select tname from teacher where tsalary like '%00'
--retrive the name of the teacher tha teacher salary is contain 00
select tname from teacher where tsalary like '%00%'
--update table
update teacher set tsalary=6000 where tsalary=5000
-- drop table
drop table student
-- delete table values
delete student where sid=1
delete teacher where tid=1;
-- cross join or inner join or cartisian
select sid,tname,ssex from student,teacher
select* from teacher
select *from student
--union
create table coustmer
(
cname varchar(20),
cid int primary key not null,
csalary money
);
insert into coustmer values ('abebe',30,2000);
insert into coustmer values('aster',40,3000);

create table orders(


cname varchar (20),
csalary money
);
alter table orders add cid int foreign key references coustmer (cid);
alter table orders add amount int ;

insert into orders values('abebe',5000);


insert into orders values ('alemu',800,30,8);
--union :-eliminate duplicate row
select cname from orders union select cname from coustmer
--union all not eliminate duplicate row
select cname from orders union all select cname from coustmer
--intersect:-select comn values
select cname from orders intersect select cname from coustmer

--left join
select coustmer.cname,amount from coustmer left join orders on
coustmer.cid=orders.cid;
select coustmer.cname,amount from coustmer right join orders on
coustmer.cid=orders.cid

select *from coustmer


select *from orders
--right join
select coustmer.cname,amount from coustmer right join orders on
coustmer.cid=orders.cid;

select coustmer.cname,amount from coustmer full join orders on


coustmer.cid=orders.cid;
--inner join
select coustmer.cname,amount from coustmer inner join orders on
coustmer.cid=orders.cid;
--cross join
select coustmer.cname,amount from coustmer cross join orders ;
--index
create index dd on student(ssex);
lab 2
create table student
(
sSid int primary key,
sname varchar(30),
lname varchar(30),
sage int
);
select *from student
begin transaction
insert into student values(1,'abebe','kebede',12);
rollback transaction
begin transaction
insert into student values(1,'abebe','kebede',12);
commit transaction
begin transaction
update student set sname='almaz'where sname='abebe';
rollback transaction
commit transaction

begin transaction
delete from student where sname='almaz';
rollback transaction
create login login11 with password='123abc';
create user user1 for login login11
create role student
exec sp_addrolemember student,user1
grant select,insert on student to user1
revoke insert on student from user1
create login login22 with password ='345abcc'
create user user22 for login login22
grant insert,delete on student to user1 with grant option
BACKUP DATABASE dmu to disk='E:\BBb'

DROP DATABASE dmu


restore database dmu from disk='E:BBb'

You might also like