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

Unit 3 updated2

This document provides an overview of relational database management systems, including the structure of databases with tables, fields, and records. It explains the use of SQL for database manipulation, detailing the categories of SQL commands: Data Definition Language (DDL), Data Manipulation Language (DML), and Data Query Language (DQL). Additionally, it covers practical SQL commands for creating, altering, and managing database tables and relationships.

Uploaded by

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

Unit 3 updated2

This document provides an overview of relational database management systems, including the structure of databases with tables, fields, and records. It explains the use of SQL for database manipulation, detailing the categories of SQL commands: Data Definition Language (DDL), Data Manipulation Language (DML), and Data Query Language (DQL). Additionally, it covers practical SQL commands for creating, altering, and managing database tables and relationships.

Uploaded by

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

At the end of this unit,

you will be able to:


• Describe relational database management
system.
• Explain fields and records.
• Apply SQL data definition language(DDL) to
create tables in a database.
• Differentiate between SQL data definition
language(DDL), data
• manipulation lanaguage (DML), and data query
language(DQL).
• Apply SQL DML to manipulate records in tables.
• „ Apply SQL DQL to query records of tables.
3.1. Overview of Relational Database
Management System
• It refers to various types of software systems
developed in order to manage databases.
• It is used to create, maintain, and provide
controlled access to a relational database.
• Data are stored in a two-dimensional table,
which contains columns or fields and rows or
records.
• Each column of a table represents an
attribute or data value, and each row in a
table represents a tuple or record.
3.1. Overview of Relational Database
Management System
• A database contains one or more tables that
maintain records.
• Attributes are the set of properties to
describe the instances of the entity.
– For example, a student can be an entity. The
attributes of a student can be described in terms
of student id, name, age, grade level and sex.
• A record is a row or a tuple in the table
contains a single data value in each column.
3.1. Overview of Relational Database
Management System

one record/
tuple
3.1. Overview of Relational Database
Management System
• Each field in a table has to be given a name
and data type.
• Data type is the type of data value you want
to store in the field.
• best describes the fields in the table
3.1. Overview of Relational Database
Management System

• Sample fields with appropriate data types and data values


Class Review
1. A db which has only one table is
called ____
2. An entity of a database is referred
to as a table. T/F
3. A record of a given database table
is known as ______
4. Attributes of a table refers to ____
5. Relational database may contain
two or more related tables. T/F
6. ______ describes the type of
data that can be recorded under
each attributes in the database
table.
7. Each attributes of a table has its
own corresponding data type.
T/F
8 Each attributes of a table has its
own corresponding data value.
T/F
3.1. Overview of Relational Database
Management System
• Relational databases are the most popular
databases
– Examples: Microsoft Access, Oracle,
Microsoft SQL Server, MySQL, SQLite, IBM
DB2, and PostgreSQL.
Figure 3. 3 Example of Relational
Database model with sample data.
3.2. Database Manipulation Using
SQL
• A standard language for accessing and
manipulating a database.
• SQL is a special-purpose query language
meant for interacting with relational
databases such as Microsoft Access.
• SQL can help To create better queries and
make it easier to understand how to fix a
query that is returning unwanted results.
3.2. Database Manipulation Using
SQL
• Based on their purposes, three categories of
SQL commands are presented below.
• Data Definition Language (DDL): DDL contains
commands that allow you to create or modify
tables and establish relationship between
tables in your database structure.
• Data Manipulation Language (DML): DML
contains commands that are used to manage
the database by performing operations such
as inserting, updating, deleting, and
navigating through data.
3.2. Database Manipulation Using
SQL
• Data Query Language (DQL): is used for
querying or selecting all or subsets of data
from a database
Activity 3.3
1. What SQL command can be used to:
• create a table?
• modify a table?
• delete a table?
• add a record to a table?
• modify a record in a table?
• remove a record in a table?
2. Categorize commands in question 1 under DDL,
DML and DQL.
To create a database
• Identify tables/entities
• Identify attributes/fields of each table
• Identify the data types of each
attributes of a table
• Assign data size of CHAR data types
• Identify the primary and foreign keys
of database tables
PRIMARY KEY
• serve as unique identifiers for each row in a
database table.
• FOREIGN KEY
Foreign keys link data in one table to the data in
another table.
A foreign key column in a table points to a
column with unique values in another table
(often the primary key column) to create a
way of cross-referencing the two tables
Create a database with a name HSS &
create student, Teacher and grade
tables
Create table Teacher(
Tr_id char(10) PRIMARY KEY,
Name char(20),
Sex char(1),
Age int,
Specialization char(15))
Create table Student(
St_id char(10) PRIMARY KEY,
Name char(20),
LName char(20),
Sex char(1),
Age int,
G_level int,
DOB DATETIME)
Create table Grade(
Stu_Id char(10) REFERENCES
Student(st_id),
Teach_Id char(10) REFERENCES
Teacher(Tr_Id),
C_Code char(20),
mark int)
Create the Patient AND Doctor Table using
the following info. Use SQL command
Patient ID char(5) Doctor id …..char(5)
Name char(20) Doctor name … char(20)
Doctor Address … Cha(15)
Sex char(1)
Age Integer
Address char(15)
Set Doctor ID as
App_Date datetime
primary key
SET Patient ID as
primary key & Doctor
ID as a foreign key
Doctor id …..char(5) CREATE TABLE Doctor (
Doctor name … Dr_ID CHAR(5) PRIMARY KEY,
char(20) Name CHAR(20),
Doctor Address … Dr_Address CHAR(15))
Char(15)

Set Doctor ID as
primary key
Patient ID char(5) CREATE TABLE Patient(
Name char(20) Pt_ID CHAR(20) PRIMARY KEY,
Sex char(1) Name CHAR(20),
Sex CHAR(1),
Age Integer
Age INT,
Address char(15)
Address CHAR(15),
App Date datetime APP_Date DATETIME,
SET Patient ID as primary
Doc_ID char(5) REFERENCES
key & Doctor ID as a
foreign key
Doctor(Dr_ID))
Here is the r/ship
Create the Department & Employee Table
using the following info. Use SQL command

Employee ID CHAR(10)
Depart ID char(10)
Emp Name CHAR(20)
Dept Name char(30)
Position CHAR(20)
Dept Location char(20) Salary CURRENCY
Block Number Integer
• SET Employee ID as
* SET Depart ID as primary key &
primary key Depart ID Foreign key
CREATE TABLE Department(
Dept_ID CHAR(10) PRIMARY KEY,
Dept_Name CHAR (30),
Dept_Location CHAR(20),
Bl_No INT)
Employee ID CHAR(10) CREATE TABLE Employee(
Emp Name CHAR(20) Emp_ID CHAR(10) PRIMARY KEY,
Position CHAR(20) Name CHAR(20),
Salary CURRENCY Position CHAR(20),
Salary CURRENCY,
SET Employee ID as Depart_ID char(10) REFERENCES
primary key & Department(Dept_ID))
Depart ID Foreign key
Q1. Create the following tables using
SQL commands Access:
• Teacher table with attribute – teacher id
(CHAR(10)), name (CHAR(20)),
sex(CHAR(1)), age(INTEGER),
specialization (CHAR(15)). Set the
Teacher id as primary key.
CREATE TABLE Teacher(trid char(10)
PRIMARY KEY, name char(20), sex
char(1), Age INT, Specialization char(15))
Q1. Create the following tables using
SQL commands Access:
Student table with attribute – student id
(CHAR(10)), name (CHAR(20)),
sex(CHAR(1)), age(INTEGER), grade level
(INTEGER). Set the Student id as primary
key.
CREATE TABLE Student(StudentID
char(10) PRIMARY KEY, NAME
CHAR(20), SEX CHAR(1), Age INT,
Gradelevel INT)
Q1. Create the following tables using SQL
commands Access:
• Grade table with attribute – student id
(CHAR(10)), teacher id(CHAR(10), course
code(CHAR(20)), mark(INTEGER). Use st_id as a
FOREIGN KEY to create a relationship with the
Student table.
create table grade(Stu_Id Char(10)
REFERENCES Student(st_Id),
teach_ID char(10) REFERENCES
Teacher(tr_Id), C_Code char(20),
mark INT)
Q. The following CREATE statement has a
problem (i.e. has syntax error). Trace the
problem and rewrite the statement to fix
the error
CREATE TABLE Patient (pid INTEGER, P_Name TEXT
P_Age INT

CREATE Physician (id CHAR, name TEXT, DoB


DATETIME, PRIMARY KEY(id))

CREATE TABLE Treatment (ptid INTEGER


REFERENCES Patient pid, drId CHAR REFERENCE
id)
CREATE TABLE Patient(pid INT PRIMARY KEY,
P_Name TEXT, P_Age INT)

CREATE table Physician(id CHAR PRIMARY


KEY, name TEXT, DoB DATE)

CREATE TABLE Treatment(ptid INT


REFERENCES Patient(pid), drId CHAR
REFERENCE Physician(id))
ALTER TABLE command(DDL)
• Once a table is created, it can be modified
using the ALTER TABLE command.
• Using the ALTER command, you can add
column(s), drop column(s), and change
column definitions.
• It is also used to establish relationship
between tables.
Note: A table can be altered before
records are inserted.
Examples
• the data type for name in Physician table on
the above slide is CHAR(25) , to modify the
field name in the Physician table with
CHAR(30).
ALTER TABLE Physician ALTER COLUMN name
CHAR(30)
• Or drop the column name like this:
ALTER TABLE Physician DROP COLUMN name;
Then, add column (example Sex) again like this:
• ALTER TABLE Physician Add COLUMN Ph_Name
char(20), Sex char(1), Age int
ALTER Command
• If you have missed setting a primary key while
creating a table, the ALTER command can be
used to modify the column as primary key.
• Assume you have not set a primary key for the
Physician table. Modify the emp_ID and set it
as primary key as follows:

ALTER TABLE Physician ADD PRIMARY KEY(emp_ID)


ALTER command to create
relationship
• The following ALTER command modifies
the COURSE table to create a relationship
with STUDENT table through SID which is
the primary key in STUDENT table.

ALTER TABLE Student ADD FOREIGN KEY


(C_Description) REFERENCES
STUDENT(SID);
Create table COURSE(
C_Code int Primary Key,
Contact_Hr int,
C_Name char(25),
C_Description char(30))
Create table COURSE(
C_Code int Primary Key,
Contact_Hr int,
C_Name char(25),
C_Description char(30))

Assume You have created Student and


course tables under HurutaSS database
without Setting up a foreign key in the
course table to create a relation ship
with student table. To setup R/Ship use
the following slide:
Create a database with a name
HurutaSS & create student and course
tables
create table student(
SID Char(5),
SName char(20),
LName char(20),
Sex Char(2),
Age int,
Grade int)
Activity 3.6
1. Modify the Student table based on the
following descriptions using ALTER
command:
a/ Modify ‘SID’ COLUMN datatype to CHAR of
size 8. E.g. ‘Stu/1001’.
LATER TABLE student ALTER COLUMN SID(8)
b/ Modify (Set) ‘SID’ as PRIMARY KEY.
LATER TABLE student ADD PRIMARY KEY (SID)
c/ Add a new column (DoBirth) for student
table with DATETIME data type.
ALTER TABLE student ADD COLUMN DoBirth
DATETIME
D/ Delete column Date of Birth from student table
ALTER TABLE student DROP COLUMN DoBirth
Solution
• Modify ‘employee id’ datatype to CHAR of size 7.
E.g. ‘Py/1001’.
ALTER Table Physician ALTER COLUMN Emp_id
CHAR(7)
• Modify ‘employee id’ as PRIMARY KEY.
ALTER TABLE Physician ADD PRIMARY KEY(Emp_Id)
• Add a new column for date of hire of the
physician with DATETIME datatype.
ALTER TABLE Physician ADD COLUMN DoHire
DATETIME;
Activity 3.6
2. Modify the STUDENT and COURSE tables in
question 1 to create the following
relationship using the ALTER command:
• Add SID for the Student table as foreign key
of table COURSE,
ALTER TABLE course ADD FOREIGN KEY (St_ID)
REFERENCES STUDENT(SID)
DROP TABLE command
• Use the DROP TABLE command to
delete the table already created.
• For example, if you want to delete COURSE
table, use the following SQL command.
DROP TABLE COURSE

• Caution - Remember that if you delete a


table with record, you cannot get it back.
Summary of DDL
• CREATE TABLE
• ALTER TABLE
– ALTER COLUMN – changing col. definition
– ADD COLUMN
– ADD PRIMARY KEY
– ADD FOREIGN KEY
– DROP COLUMN – deleting col
• DROP TABLE
Q. The difference b/n DROP COLUMN &
DROP TABLE
Activity 3.7
1. Create a PATIENT table with PID,
P_Name, Address & with data type
Char(10), Char(25), Char(15)
respectively.

a/ Add Sex and Age columns with char(1)


& INT data types (Use ALTER)
b/ Delete column Address from patient
table
c/ Modify the data type size of column
P_Name to Char(20)
d/ Set PID as a primary key
e/ Delete PATIENT table
Summary Questions
1. A table can be altered after a record is
inserted. T/F
2. You can get it back Dropped table from
the Database. T/f
3. What SQL command you use to update
column definition. ______
4. Assume you have forgotten setting
Primary key in the student table. Write
SQL command to set it back
5. Assume you don’t want course table in
school database. Write SQL command to
delete it.
3.2.3 Data Manipulation Language
• Data Manipulation Language (DML) consists
of commands that allow you to manage the
database by performing operations such as
inserting, updating, deleting, and navigating
through data.
• The DML commands include INSERT, UPDATE
and DELETE.
INSERT command
Notes: Did you know that while using the
INSERT INTO command, the column value
should match the column data type of the
table (e.g., you cannot insert a text value into
a numerical field).
• All string values to be inserted in a table
should be quoted with single or double
quotation marks (e.g. ‘Chemistry’ or
“Chemistry”).
• But if the field is defined as numeric, like Age
INT, the value to be inserted does not need
quotation marks(e.g. 20).
INSERT command
• INSERT command helps to insert new records
to a table.
• The INSERT command can be used in one of
the two options shown in the table below.
– Option 1 is used when the values of all
fields are to be replaced by new values,
INSERT INTO table_name VALUES (value1,
value2, value3 ...)
– Option 2 is used when only selected fields
are to be replaced.
INSERT INTO table_name (column1,
column2…) VALUES (value1, value2 …)
INSERT command
• Example 1: Insert into a COURSE table
INSERT INTO COURSE VALUES (3, “Chemistry”,
“Organic chemistry”, “105”, “NS1421”);

• Example 2: Insert into a DEPARTMENT table


INSERT INTO DEPARTMENT (D_Number,
D_Name, D_Location) VALUES (“D101”,
“Biology”, “NBR First Floor”)
INSERT command
INSERT INTO COURSE (Contact_Hr, C_Name,
C_Department, C_Code) VALUES (4,
“Biology”, “102”, “NS2323”);
• In the above INSERT statement, the value of
C_DESCRIPTION is not mentioned on the query.
• As a result of this, while you run the query, the
value of the course description for Biology is left
blank in the table (See Figure 3.13)
Create table PATIENT(PID char(10),
P_Name char(10), Sex Char(1), Age INT)

INSERT INTO PATIENT VALUES(‘102’,


‘Habtom’, ‘M’, 34);
Create a database with a name HSS &
create student and course tables
create table student(
SID Char(5) Primary key,
SName char(20),
LName char(20),
Sex Char(2),
Age int,
Grade int)
3.2.1 Using SQL in Microsoft Access
Create XYCollege Database and Create
tables DEPARTMENT and COURSE
create table Course(
C_Code char(10) Primary key,
Contact_Hr int,
C_Name char(20),
C_Description text,
C_Department char(10) REFERENCES
Department(D_Number))
Activity 3.9
1. Insert the following records in the Student, Teacher and
Grade tables you have created in Activity 3.5

Page 80
Solution
INSERT INTO Grade (student_Id,
Teacher_ID, Subject, Mark)
VALUES( “1001/2013”, “1001/2010”,
“Physics”,80)
Activity 3.9
Activity 3.9

INSERT INTO Teacher VALUES( “2001/2010”,


“Roman Nesibu”, “F”, 31, “Physics”)
INSERT INTO Teacher VALUES( “2002/2010”,
“Helen Alemu”, “F”, 30, “ICT”)
Activity 3.9
2. What is the problem with the following INSERT
statement? Rewrite the INSERT statement to fix
the error.
INSERT IN TO GRADE VALUES(‘1012/13’,
‘2023/2010’, English)
INSERT INTO TEACHER (teacher_id, Sex, Age)
VAL-UES(“001”,”M”)
INSERT INTO STUDENT (Student_id, Name, Sex)
VALUES(‘1015/13’, ‘M’)
3. Write INSERT statements to insert the
following records.
• Student id, name and age for three students
(1001/2014, Meymuna, 20), (1002/2014,
Alehegne, 20), and (1003/2013, Kello, 19).
UPDATE command
• The UPDATE command does not add new
records to a table, nor does it remove records. It
simply updates existing records in the table.
• The UPDATE command is used to change a value
of one or more fields in an existing table row or
number of rows.
• The general syntax of an UPDATE command is
given below.
UPDATE table_name SET column1 = value1,
column2 = value2...
WHERE condition;
Examples
UPDATE Teacher SET T_Salary = 15000 WHERE
T_Salary<10000;
The UPDATE command can also be used
to update multiple rows at the same time.
This is done by selecting many rows
using the WHERE clause.
It is the WHERE clause that determines
how many records are updated.
UPDATE Teacher SET T_Salary = 20000
WHERE T_sex=’female’;
• If you ignore the WHERE clause in the above
statement, the query changes the salary of all
teachers to $15,000
UPDATE Teacher SET Teacher.T_Salary = 15000;
Activity 3.10
1. UPDATE the following records in the Student and
Teacher tables (See Activity 3.9)
• Modify student name, Halima Mohammed
where student_id is 1001/2013.
• Modify specialization, Economics where
teacher_id is 2010/2010
EmpID Name Sex Age Dept Salary
001 Gosa Belachew M 32 Mgt 8000
002 Gosaye Teshome M 28 Sales 9500
003 Haimanot Getu F 21 Acct 14000
004 Helen Kelela F 24 Mkt 16000
005 Hiwot Birhanu F 27 Sales 20000
006 Jibril Jemal F 15 Acct 10100
007 Jamal Mohamed M 20 Mgt 7800
Assume you have Employee table with
EmpID, Name , Sex, Age, Dept & Salary
Columns and also the table has some
records
1. Update the salary of mgt department
employees in to 30,000
2. Update the salary of Female
employees into 50,000
3. Update salary of employees whose
age >30 in to 60,000
4. Modify the name “Helen Kelela” her
EmpID 001 into “Hiwot Ketema”
5. Update the salary of all employees
into 35000
6. Update the Sex, Age and Salary of an
employee whose EmpID is 006 into
“M”, 35, 25000 respectively
5. Update the Sex of an employee whose
ID 005 in to “M”
6. Update the Dept of employees whose
department name Mgt in to Admin
Product table
PrID Desc Unit Qty Price
001 LED TV pcs 15 32000
002 Laptops pcs 12 21500
003 Keyboard pcs 10 2500
004 Desktop pcs 8 1400
005 Scanner pcs 7 20000
006 Hp Printer pcs 30 35000
007 CC camara pcs 16 20000

DELETE FROM product


WHERE PrID=“007”;
Qui1
1. Update the Qty of the product its PID
004 into 25
2. Update the price of product desktop
in to 45000
3. Update the price and the qty of
product its PID 005 into 2000 and 21
respectively.
4. Change the name and Price of the
product its PID 007 into “Digital
Camera” and “25000” respectively
5. Change the quantity of all products
into 10.
Quiz2
1. Column of a table refers to _____
2. Drop table command only deletes all
records with in a table. True/False
3. Which SQL command is used to add
forgotten primary key in the table.
A/ Add B/ Alter C/ Drop D/ Insert
4. Which SQL command is used to modify
record(s) in the table
A/Delete B/ Set C/ Insert into D/None
5. Re-write the following SQL code by fixing its
syntax error.
DELETE FROM student
WHERE Sex = F
DELETE command
• The DELETE command is used to delete
a record or multiple records from the
database.
• DELETE command does not remove the
table structure, rather it only deletes
the data that is currently being held by
the table structure.
DELETE FROM table_name
WHERE condition;
3.2.4 Data Query Language – SELECT
Command
• It provides a SELECT command for querying all or
subset of records from one or more tables of a
database.
Basic SQL Clauses: SELECT, FROM, and WHERE
• This part deals with queries that run on a single
table. You can run a SELECT operation on multiple
tables in a single statement, too
• The syntax to retrieve all records from a table is:
SELECT * FROM table_name;
• “Select all records from a table”.
• When the keyword SELECT is followed by the
asterisk symbol (*), it means all columns/ fields in
the table.
3.2.4 DQL… cont’d
Example:
• The following SELECT query retrieves full name of
male students with their sexes from the STUDENT
table.
SELECT S_Fname, S_MName, S_LName, S_sex
FROM STUDENT
WHERE s_sex = ‘male’ AND YEAR =‘2023’;
Employee table
EmpID Name Sex Age Dept Salary
001 Gosa Belachew M 32 Mgt 8000
002 Gosaye Teshome M 28 Sales 9500
003 Haimanot Getu F 21 Acct 14000
004 Helen Kelela F 24 Mkt 16000
005 Hiwot Birhanu F 27 Sales 20000
006 Jibril Jemal F 15 Acct 10100
007 Jamal Mohamed M 20 Mgt 7800
Exercises
1. Select Name, Dept & Salary of an employees
their salary is BETWEEN 30000 AND 10000
2. Select the Name and Sex of employees their
Dept is Acct.
3. Select the Name and Salary of employees
their Sex is Male and ORDER BY their Name
Descending
4. Delete all employees’ record who are in Mgt
department.
5. Delete all employees record
6. Select all employees record
7. Delete an employee record whose EmpID is
004
3.2.4 DQL… cont’d
Filter records on multiple criteria:
• you see how to combine multiple criteria using AND
and OR.
• Example:
SELECT CustomerId, SalesDate, Amount
FROM SALES
WHERE SalesDate>=’01-05-2020’ AND Amount >
12000;
3.2.4 DQL… cont’d
Filter records on multiple criteria:
• Example2:
SELECT CustomerId, SalesDate, Amount
FROM SALES
ORDER BY Amount;
3.2.4 DQL… cont’d
Filter records on multiple criteria:
• Example2:
SELECT CustomerId, SalesDate, Amount
FROM SALES
WHERE Amount <1000 OR Amount > 15000;
3.2.4 DQL… cont’d
SELECT Command ORDER BY Clause
• Syntax:
SELECT column1, [column2], …
FROM table_name
ORDER BY [column] [ASC][DESC]
3.2.4 DQL… cont’d
SELECT Command ORDER BY Clause
• Example:
SELECT T_First_Name, T_Middle_Name,
T_Sex, T_Salary
FROM Teacher
ORDER BY T_Salary
3.2.4 DQL… cont’d
SELECT Command ORDER BY Clause
• Example:
SELECT T_First_Name, T_Middle_Name, T_Sex,
T_Salary
FROM Teacher
WHERE Sex =“Male”
ORDER BY T-First_Name DESC
3.2.4 DQL… cont’d
• Selecting records from Two Tables
• Syntax:
SELECT table1.column1, table1.column2],
table2.column1, [table2.column2]
FROM table1, table2
WHERE table1.column1 = table2.column2

SELECT student.sid, student.fname,


couse.Ccode, course.grade
From student, course
WHERE student.SID = course.StID
•Do activity 3.15 on page
92
tables
3.2.4 DQL… cont’d
• Selecting records from Two Tables
• Example:
SELECT COURSE.Course_id,
COURSE.Course_name, COURSE.Grade,
CourseOffering.Semester
FROM COURSE, CourseOffering
WHERE COURSE.Course_id =
CourseOffering.Course_code;
3.2.4 DQL… cont’d
• Selecting records from Two Tables
• Example:
SELECT COURSE.Course_id,
COURSE.Course_name, COURSE.Grade,
CourseOffering.Semester
FROM COURSE, CourseOffering
WHERE COURSE.Course_id =
CourseOffering.Course_code AND
Semester=’I’;
1. Select all teachers who are
specialized in Mathematics and
order them by their names.
2. Select all records in teacher
table and order them by Sex

You might also like