DB - Fundamentals
DB - Fundamentals
Introduction
Limitations of file-based system:
What is a database?
It is the DBMS software together with the data itself. Sometimes, the applications are also included. (Software +
Database)
What is metadata:
Step 3: Implementation
• Install DBMS.
• Create DB schema and populate data.
• Create users and authorize access to DB.
• Maintain DB performance.
• External Schema: they are concerned with what data the user will see and how the data will be presented to
the user (Could be more than one like financial schema, HR schema, etc).
• Conceptual Schema (Logical model): they are concerned with what is represented (define the database
structures such as table sand constraints).
• Physical Schema (Physical Model): they are concerned with how the data are represented in the database,
how the data structures are implemented.
The architecture is divided into schemas to achieve data independence (a change in any schema doesn’t affect the
other schemas).
Data Models:
Mappings:
It’s the process of transforming requests and results between levels (schemas).
-بيكون مكون من 2 tiersوهنا الـ applicationبيكون موجود عىل الـ thick clientوهنا انا خفيت الـ loadبتاع الـ processingلكن ىبق عندى
هبق مضطر اعمله عىل كل ، clientوطبعا لسه عندى Single Point of Failureعند مشكلة أن لو جيت اعمل ابديت مثال للـ applicationى
الـ.database server
-مازال عندى هنا مشكلة point of failureعىل الـ application tierوممكن أحلها عن طريق ):(n-tier architecture
-الفكرة الرئيسية هنا نان بحل مشكلة الـ Single Point of Failureعند الـ.Database
-أول ن
منة هنا انها .support high availability of database
ن
متوصلي ببعض بحاجة زى الـ heart beatsكدة أول ما واحد ن
والتني -ن يف حالة الـ full replicationبيكون عندى نسخة من الـdatabase server
التان بيشتغل وكل الـ requestsبيحصلها reroutingعىل ن
التان. يقع ن
-نف حالة الـ partial replicationبعمل كون لجزء بس من الداتا وبشتغل عليه وكل ى
فنة باخد الـ changesالىل عملتها عىل الـ replicaوبنقلها ى ي
للـ headquarterعشان يفضل .up-to-date
ن
التني. -نف حالة الـ fragmentationباخد الـ fragmentsأما horizontalاو verticalاو hybridن
بي ي
Relational Database:
• It consists of relations or tables of relations.
• Each table consists of columns and tuples (records).
• The intersection between them is domain.
• The domain can only have a single value.
• Each table has a primary key that can be one column or multiple columns together.
• The primary key (underlined): - must contain a unique value for each row of data.
- cannot contain null values.
Entity
Attribute
• A relationship describes how two or more entities are related to each other.
• Relationships represent the associations between entities in the database.
• In an ERD, relationships are depicted by diamonds connecting entities.
• Example: In a university database, a relationship could be "Enrolls," which links "Student" and "Course,"
indicating that students enroll in courses.
- Simple attributes: are not divisible and have a single value for a particular entity instance.
- Multi-valued attributes: have a set of values for the same entity instance.
- Candidate (Primary) key: an attribute that can uniquely identify one specific occurrence of an entity. (Underlined
attribute)
Types of Entities
- Strong entity:
• Definition: A strong entity exists independently of other entities and has a primary key that uniquely
identifies each instance of the entity.
• Example: In a university database, "Student" and "Course" are strong entities because each student and
course can be uniquely identified by their "Student ID" and "Course ID," respectively.
- Weak entity:
• Definition:
o A weak entity cannot exist without being associated with another entity, known as its "owner" or
"parent" entity.
o It does not have a primary key of its own but relies on a "foreign key" or "partial key" from the
owner entity.
• Example: "Relative" in a company’s medical insurance system might be a weak entity if it is defined only in
the context of an "Employee". The "Employee ID" might be used as part of the identifying key for "Relative".
Relationships:
Relationship Degree
• Definition: A unary relationship involves only one entity type, where the entity is related to itself.
• Example: An "Employee" manages another "Employee". In this case, the relationship "Manages" is unary
because it involves the "Employee" entity both as the manager and the subordinate.
• Definition: A binary relationship involves two different entity types. It is the most common type of
relationship in ERDs.
• Example: A "Student" enrolls in a "Course". The relationship "Enrolls" is binary because it involves two
entities: "Student" and "Course".
• Definition: A ternary relationship involves three different entity types. It represents a relationship that
includes three entities simultaneously.
• Example: A "Doctor" prescribes a "Medication" to a "Patient". The relationship "Prescribes" is ternary
because it involves the entities "Doctor," "Medication," and "Patient".
• Definition: An N-ary relationship involves N different entity types, where N is greater than three. This is a
more complex relationship that includes multiple entities.
• Example: In a supply chain system, a relationship might involve "Supplier," "Product," "Warehouse," and
"Transporter," forming a quaternary (4-ary) relationship.
• The cardinality ratio describes the numerical relationship between entities participating in a relationship.
• It defines how many instances of one entity can or must be associated with instances of another entity.
• Participation refers to the extent to which entities in a relationship must participate in that relationship.
• It indicates whether the presence of a relationship between entities is mandatory (must) or optional (may).
o Total Participation: Every instance of the entity is involved in the relationship (Mandatory
participation). Represented by a double line in ERDs.
o Partial Participation: Some instances of the entity may not be involved in the relationship (Optional
participation). Represented by a single line in ERDs.
سواءrelationship instance ممكن تشارك بيه ن يف الـentity بعن عن اقل رقم الـ
هنا انا ى-
.)must() او واحدmay(صفر
لكن القسم ممكن يكون لسه، من عند الموظفrelation ن يف الـdouble line يبق هعملمعي ى
ن ن-
يعن مثال الموظف لزم ع األقل يشتغل تبع قسم
ى ن
. من عند القسمone line اتعي لسه يبق هعمل فاتح ومفيش فيه حد
نparticipation الـ-
.weak من ناحية الـmust بتاعتها لزم يكونowner entity والـweak entity بي الـ
يعن مثال ن يف حالة الـ الىل بسأل عنها ىrule واحدة بس بتكرس الـrelationship instance لو عندى-
ن، may لزم يكونparticipation يبق هنا الـ
يبق العالقة هنا لزم الرسكة دة الوحيد الىل مالوش مسئول ى
الموظفي يكون ليهم مسئول لكن مدير ر
ن “ المفروض ان كلsupervise” relationship
. برضوmay وبالتال العالقة هتكون ن ن
وطبعا بالنسبة للناحية التانية مش كل الموظفي لزم يكونوا مسئولي عن حد، may تكون
ي
ن
موظفي يعن مثال هل ر
المرسوع لزم يكون فيه لما ىternary بتاع الـparticipation ن يف الـ-
ن، معايا3 entites باج اسأل السؤال بحاول ادخل الـ
الموظفي لزم يكون عندهم المهارات دى نف ر
.المرسوع دة ن موظفي نف ر
هل، مرسوع ن هل المهارات لزم تكون عند، بالمهارات دى
ي ي
-الـ relationshipالىل ن
بي الـ weakوالـ ownerبتكون اسمها ، identifying relationship
وبمنها نان بخىل شكل الـ diamondبتاع الـ relationshipيبق .double-lined
ى ن
• Foreign Key:
o A foreign key is a column or set of columns in one table that refers to the primary key in another
table.
o The foreign key creates a link between the data in the two tables, enforcing referential integrity.
o It ensures that a record in the child table cannot reference a non-existent record in the parent table.
• The derived attribute is not stored in the database by default except when needed.
نattribute ألن وقت ما احتاجه ممكن استنتجه من
لكن بخزنه لما بيكون الطلب عليه، تان نderived attributeيعن انا مش بخزن الـ
ن •
ى
. بخزنه بقcomputing عىل الـheadache كبن فبدل ما كل مرة احسبه واعمل
Step 2: Mapping of weak entity
• The foreign key here is the primary key of the owner entity.
• The primary key of the weak entity table is the combination of foreign key and a partial key from the table.
• The logical design at the end of the first two steps is:
Step 3: Mapping of relationship with (Unary - Binary) degree and (1:N) cardinality
• Here, we add the primary key of 1 side as a foreign key to N side.
ألن لو خدت الـ primary keyبتاع الـ N sideوحطيته as foreign keyنف الـ 1 sideى
يبق كدة خانة طب ليه انا بعمل كدة مش العكس ،ن •
ي ن ن
ى
شغالي يف القسم الواحد ،لكن العكس هيبق صحيح ان الموظف ن ن
موظفي كتن هتبق multi-valuedألن يف ى الـ SSNن يف جدول الـDept
يعن مثال ن يف حالة جدول الـ Empانا هكرر عامود الـ SSNوعشان متلخطبش هسميه مثال ، Sup-SSNوانا هنا الواحد شغال نف قسم واحد ،ن
ي
مش بكرر الداتا ألن الـ SSNبتاع الموظف الواحد ى
هيبق ادامه SSNمختلف بتاع المدير بتاعه.
بعن عن معلومة جديدة ،وممكن ن ن ن •
يف الـ unaryبضيف الـ primaryتان عادى لنفس الـ entityوانا هنا مش بعمل تكرار للداتا لن هنا ى
اضيفه باسم متغن عشان ميحصلش لخبطة.
لو كان الـ primaryأصال موجود ن يف الناحية التانية زى مثال حالة الـ weak entityهنا انا مش محتاج اضيفه تان.
ن •
Step 4: Mapping of relationship with (Unary - Binary) degree and (M:N) cardinality
هنا انا باخد الـ primary keysبتوع الـ entitiesكـ foreign keysن يف جدول جديد باسم الـ .relationship •
الـ primary keyبتاع الجدول الجديد هو الـ combinationبتاع الـ .foreign keys •
يعن اى mapping of relationshipبيطلع منه foreign keyفانا لو نف attributeعىل الـ relationshipدايما بيتبع الـ ، foreign keyن •
ي
في وبحط الـ attributeدى معاه.بشوف الـ foreign keyدة راح ن
Step 5: Mapping of relationship with (Unary - Binary) degree and (1:1) cardinality
هنا انا باخد الـ primary keyبتاع الـ mayوبحطه كـ foreign keyعند الـ.must o
بي الـ Employeeوالـ Deptهاخد الـ primary keyبتاع المدير الىل هو الـ SSNواحطه كـforeign keyيعن مثال نف حالة العالقة Manageن ن o
ي
ن
الموظفي هيكونوا رؤساء ن
عند الجدول بتاع الـ Deptألن لزم القسم يكون له مدير فدايما هيكون يف قيمة للـ SSNعند الـ ، Deptلكن مش كل
اقسام فلو عملت العكس هيكون ن يف خانات فاضية ن يف جدول الـ.Employee
ن
كان عندى attributeعىل الـ relationshipفعملت زى القاعدة وخليته يتبع الـ foreign keyوحطيته يف جدول الـ.Dept o
o May-may
التان كـ ، foreign keyاو حل تالت نان اعمل جدول جديد بيهم لكن دة مش مفضل.
هنا انا ممكن اخد أي primary keyواحطه عند ن
o Mus-must
. ن يف الجدول الجديدforeign keys بتوع الجداول القديمة كـ3 primary keys هنا مفيش غن نان اعمل جدول جديد وهحط الـ
ن
بمعن انه لزم األول اضيف قسم ببياناته -ن يف حالة لو انا بعمل insertلزم األول أكون عامل parent recordعشان اقدر اضيف ، child record
عشان اقدر لما ىاج اضيف بيانات موظف احط رقم القسم دة.
ن
بمعن انه لزم اغن كل ارقام اقسام -ن يف حالة لو انا بعمل deleteلزم األول امسح كل الـ child recordsعشان اقدر امسح الـ ، parent record
شغالي ن يف القسم الىل همسحه قبل ما امسح القسم نفسه.
ن ن
الموظفي الىل
SQL
. نفسها لكن مقدرش اعدل ن يف الداتا نفسهاdatabase بتاع الـstructure الىل عن طريقها بقدر اعدل ن يف الـcommands ه عبارة عن مجموعة الـ
ي
(CREATE – ALTER – DROP – TRUNCATE - RENAME)
CREATE: ALTER:
This command is used to create the database or its This command is used to add, delete or change columns
objects (like table, index, function, views, store in the existing table. The user needs to know the existing
procedure, and triggers). table name.
DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and other
controls of the database system.
GRANT: REVOKE:
This command gives users access privileges to the This command withdraws the user’s access privileges
database. given by using the GRANT command.
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
ANOTHER_USER; REVOKE ALL on TABLE department FROM Mary;
They are the SQL commands that deal with the manipulation of data present in the database belonging to DML or
Data Manipulation Language and this includes most of the SQL statements.
It is the component of the SQL statement that controls access to data and to the database. Basically, DCL statements
are grouped with DML statements.
INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES (104, ‘Anmol’, 89, 19);
بس الىل انا عاوزهاcolumns أو لو عاوز اضيف قيم معينة بس لزم اكتب األول أسماء الـ.3
UPDATE Table_name SET [column_name1= value_1, ….., column_nameN = value_N] WHERE CONDITION;
UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id = 103 AND Stu_Id = 202;
. كله مع بعضcolumn لو مكتبتهاش كدة انا هعدل ن يف الـ، الىل انا عاوز اعدل بياناتهrecord الرسط او الـ
دى الىل بتحددل رwhere جملة
ن
الداتابن وشغال عىلaccess طول مانا عامل-
بعدل ن يف البيانات التعديل دة بيحصل عىل
الميمورى بتاىع بس مش بيحصل تعديل عىل
ن
الداتابن غن الىل عليهاphysical memory الـ
.commit لما بعمل
دة بياخد كل التعديالتcommit لما بعمل-
.physical memory الىل عملتها وينقلها عىل الـ
اول ماauto-commit بتعملDDL أوامر الـ-
.بنفذها
SELECT
SELECT Emp_Id, Emp_Salary FROM Employee; ---------> retrieve all the values of a specific column.
SELECT * FROM Student WHERE Stu_Marks = 80; ---------> retrieve all the records of a specific condition.
نcolumns لو أنا بكتب أسماء الـ-
بحط اسمه ن، وف واحد منهم اسمه فيه مسافة
.square brackets [ column name ] بي
BETWEEN
SELECT FullName FROM employees WHERE salary BETWEEN 1500 AND 2500;
IN
LIKE
بالنسبة للـ ? فىه، زى الىل بكتبهاexact لن ساعتها هكون بدور ع قيمة بدل ما استعمل = نmatch pattern لما أكون عاوزlike هنا انا بستعمل-
ن
.معي من صفر لحد مالنهاية بتعن عن عدد حروف
بتعن عن حرف واحد و الـ * ى ى
ALIAS
ORDER BY
JOINING
• In SQL, joins are used to combine rows from two or more tables based on a related column.
• There are different types of joins, including INNER JOIN, OUTER JOIN, and EQUI JOIN.
نف نفس الوقت بيكون نف رابط ن، اكن من جدول مش جدول واحد
بي الجداول عموما هو نان عاوز اجيب داتا موجودة نف ىjoiningفكرة الـ •
ي ي ي
.foreign key والـprimary key الىل هو غالبا بيكون الـ، دى
1- EQUI JOIN
• An EQUI JOIN is a type of join that uses the equality operator (=) to match rows between tables.
• The result set includes only those rows where the specified columns have matching values.
SELECT fname, depName FROM employees, departments WHERE id=mngID;
منهم موجود ن يفcolumn لكن كل، لن عاوز اجيب أسماء المديرين وأسماء األقسام بتاع كل واحد فيهم
ن، Equal join هنا انا بستعمل حاجة اسمها-
يكون هو نفسهid عشان أقوله اربط كل اسم بقسمه عن طريق انjoin فاستعملت الـ، وف نفس الوقت ملهمش عالقة ببعض جدول مختلف ن
.mngID
. بيكون عدد الـجداول ناقص واحدjoin conditions عدد الـ-
بتكون عالقة نjoin condition الـ-
. بتاعهforeign key والـprimary key بي الـ
2- INNER JOIN
رkeyword انا هستعمل، join هنا ىبق انا مش هستعمل الـ = عشان اعمل
.joiningمباشة تعمل عملية الـ
• An OUTER JOIN returns all rows from one table and the matching rows from the other table.
• If there’s no match, NULL values are returned for columns of the table that lacks a match.
ن، condition من الـmatching حن لو محصلش
: أنواع3 وف منها بتختلف نف انها بتعرضىل كل الداتا ىouter join هنا الـ-
ي
• Returns all rows from the left table and the matching rows from the right table.
• If there's no match, NULLs are returned for the columns of the right table.
• Returns all rows from the right table and the matching rows from the right left.
• If there's no match, NULLs are returned for the columns of the left table.
4- Self Join
فظهرت، انا عاوز اعرض اسم كل موظف واسم المدير بتاعه، recursive relationship ودة غالبا بتكون مع جدول فيهself join هنا انا بستخدم-
جبتjoin وف رشط الـ ن، للموظفي ونسخة للمديرين
ن كأن عملت نسخة للجدول نalias فعملت، تي مر نcolumn عندى مكلة نان عاوز اعرض نفس الـ
. بتاع المدير من جدول المديرid بتاع المدير بتاع الموظف من جدول الموظف وربطته بالـid الـ
وف رن ن ن ن هنا انا بحاول اشوف ن-
بتاعprimary key بجيب الـjoinالرسط بتاع الـ ، النسختي بتوع الجدول الىل بعملهم يفchildومي الـ parentمي الـ
ى ى
ألنه المدير الواحد له اكن من موظف تحته لكنparent هو الـSupervisor فمثال هالف ان الـ، child بتاع الـforeign key واساويه بالـparentالـ
.الموظف له مدير واحد
نف الغالب دايما بيكون الجدول الىل موجود عندى نف الداتا ن-
.parent والجدول النسخة منه الىل بيتعمل جديد بيكون هو الـchildبن أصال هو الـ ي ي
Sub-queries
وعشان المرتب دة معلومة مش عندى جاهزة انا لسه هجيبها من جوة الجدول فاستخدمت، اكن من مرتب احمد عىل ن
الموظفي الىل مرتبهم ى هنا انا عاوز اعرض كل-
.nested-queries اوsub-queries
Multi-row Operators: (IN – ALL – ANY)
• In SQL, multi-row operators like ALL and ANY are used in conjunction with subqueries to compare a value to
a set of values returned by the subquery.
• These operators allow you to perform comparisons between a single value and multiple values.
1. ALL Operator
• Where:
o expression: The value or column you're comparing.
o operator: A comparison operator, such as =, >, <, >=, <=, <>.
o subquery: A subquery that returns a set of values.
• Example: Find employees who have a salary greater than all salaries in the Sales department.
SELECT *
FROM Employees
WHERE Salary > ALL (SELECT Salary FROM Employees WHERE Department = 'Sales');
2. ANY Operator
• Where:
o expression: The value or column you're comparing.
o operator: A comparison operator, such as =, >, <, >=, <=, <>.
o subquery: A subquery that returns a set of values.
• Example: Find employees who have a salary greater than any salary in the Sales department.
SELECT *
FROM Employees
WHERE Salary > ANY (SELECT Salary FROM Employees WHERE Department = 'Sales');
Consider a scenario where you want to find employees whose salary is higher than the highest salary in the Sales
department (ALL) and whose salary is higher than at least one salary in the HR department (ANY):
SELECT *
FROM Employees
WHERE Salary > ALL (SELECT Salary FROM Employees WHERE Department = 'Sales') AND
Salary > ANY (SELECT Salary FROM Employees WHERE Department = 'HR');
SQL Aggregate Functions: ( MAX() – MIN() – AVG() – COUNT() - SUM() )
- SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It
returns a single value.
COUNT()
- COUNT function is used to Count the number of rows in a database table. It can work on both numeric and non-
numeric data types.
- COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*) considers
duplicate and Null.
SUM()
- Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.
AVG()
- The AVG function is used to calculate the average value of the numeric type. AVG function returns the average of
all non-null values.
MAX()
- MAX function is used to find the maximum value of a certain column. This function determines the largest value of
all selected values of a column.
MIN()
- MIN function is used to find the minimum value of a certain column. This function determines the smallest value of
all selected values of a column.
• The GROUP BY and HAVING clauses in SQL are used together to group rows that share certain properties and
filter the results based on aggregate functions. They are often used to organize and summarize data.
• The GROUP BY clause is used to group rows that have the same values in specified columns into summary
rows.
• The HAVING clause is used to filter the results after the GROUP BY clause has been applied.
• It’s similar to the WHERE clause, but WHERE filters rows before grouping, while HAVING filters groups after
aggregation.
• The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
• In the query, the GROUP BY clause is placed after the WHERE clause.
• In the query, the GROUP BY clause is placed before the ORDER BY clause if used.
• In the query, the Group BY clause is placed before the Having clause.
• Place condition in the having clause.
بتمس عىل كل صف وتطبق ر كله نColumn بتشتغل عىل الـWHERE ألن الـAggregate Functions معWHERE • مينفعش استخدم
يعن
.HAVING فعشان كدة بستخدم معاهاone value ىبنجعAggregate Function لكن الـConditionالـ
row عىل كلCondition ىبنوح تنفذ الـWHERE ألن هنا الـWHERE SUM(Salary) > 1000 بمعن نان مينفعش اكتب حاجة زى كدة ن •
ن ى
. كاملColumn واحد المفروض انها بتتعمل عىلrow عىلAggregate function فمش منطق ان اعمل
:يعن مثال ن يف المثال الىل جاى دة
ن، query نف اىaggregate functions• بس دة برضو مش معناه نان مينفعش استعملها خالص مع الـ
ي
SELECT COUNT(Eid), Address
FROM Emplyee
WHERE Did IN (10,30)
GROUP BY Address
Imagine you have an Orders table with columns OrderID, CustomerID, OrderDate, and TotalAmount. You want to
find customers who have made more than 5 orders and spent more than $10,000 in total.
Explanation:
SELECT column_name
FROM table_name
WHERE column_name REGEXP 'pattern';
Dot (.)
SELECT 'abc' REGEXP 'a.c'; -- Returns 1 (true), matches "a" followed by any character, then "c"
Caret (^)
SELECT 'abc' REGEXP '^a'; -- Returns 1 (true), matches strings starting with "a"
Dollar ($)
SELECT 'abc' REGEXP 'c$'; -- Returns 1 (true), matches strings ending with "c"
Asterisk (*)
SELECT 'aaab' REGEXP 'a*b'; -- Returns 1 (true), matches zero or more "a"s followed by "b"
Plus (+)
SELECT 'aaab' REGEXP 'a+b'; -- Returns 1 (true), matches one or more "a"s followed by "b"
SELECT 'ab' REGEXP 'a?b'; -- Returns 1 (true), matches zero or one "a" followed by "b"
SELECT 'abc' REGEXP '[ab]'; -- Returns 1 (true), matches either "a" or "b"
SELECT 'abc' REGEXP '[^ab]'; -- Returns 1 (true), matches any character except "a" or "b"
Execution sequence of SELECT:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Example (1):
Display the department name and the maximum salary for each department given that its average salary is greater
than 1200, then sort the result by department name.
SELECT dname, MAX(salary) as max
FROM employee e, departments d
WHERE e.dno=d.dno
GROUP BY dname
HAVING AVG(salary) > 1200
ORDER BY dname
ترتيب تنفيذ الـ:query
كأن بروح اجيب الجداول الىل قولت عليها واسجلهم ن يف الميمورى.
-1اول حاجة بتتنفذ ه الـ fromودة ن
ي
ن
للجدولي يعن بروح اشوف ايه الـ conditionsالىل كاتبها ادامها وبنفذها ،هنا مثال انا بعمل EQUI JOIN ن
تان حاجة بتتنفذ ه الـ ، whereن -2
ي
موظفي ن يف جدول الـ employeeمفيش ادامهم ارقام إدارة فـ اتشالوا من
ن فكأنهم اتحطوا جوة جدول واحد ،وبما نان عملت joinوكان ن يف
الجدول الجديد.
-ومن اللحظة دى ىبق الـ DBMSمعدش شايف داتا جوة الجدول غن الىل انا كنت ذاكرها جوة الـ GROUP BYبس ،ن
يعن معدش شايف غن
الـ.dname
يعن هينفذ الىل جوة HAVINGوالىل جوة SELECTويروح يحطهم ن يف
-4بعد كدة بنوح ينفذ أي aggregate functionموجودة عندى ،ن
الـ labelبتاع كل جروب.
ى
بتاعن. الرسط فكدة هيتشال من الـresult set ى
فهالف ان DP2مش محقق ر ر
ينفذالرسط بتاع الـ HAVINGنفسها ، -5بعد كدة هنوح
-6بعد كدة هنوح ينفذ الـ ، SELECTفهيشوف انا طالب منه يعرض ايه ويعمل بيه result setجديدة ،ولزم الىل انا طالبه يعرضه دة يكون
يعن من الخر لزم أكون كاتبه جوة الـ GROUP BYاو حاسبه بـ ، aggregate functionن
يعن لو مثال موجود جوة الـ labelبتاع كل جروب ،ن
عاوز اعرض الـ dnoلزم أكون عامله mentionجوة الـ.GROUP BY
-7اخر حاجة ىبق هنوح ينفذ الـ ORDER BYوبرضو لزم يعمل اوردر بحاجة تكون موجودة جوة الـ labelى
حن لو انا مش عارضها جوة
الـ ، SELECTفهيكون شكل الـ queryالنهائية كدة:
Views
• In SQL, a view is a virtual table (logical table) based on the result-set of an SQL statement (SELECT).
• A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.
• A View can either have all the rows of a table or specific rows based on certain conditions.
• You can add SQL statements and functions to a view and present the data as if the data were coming from
one single table.
• A view contains no data of its own, but it’s like a window through which data from tables can be viewed or
changed.
• The tables on which a view is based are called the base tables.
• The views is stored as a SELECT statement in the data dictionary.
• A view always shows up-to-date data! The database engine recreates the view, every time a user queries it.
فدةaggregations وfunctions بتاىع بيكون معمول فيهView ألن الـDML Operations مش دايما هقدر اعملComplex Views ن يف حالة الـ-
. الصليةtablesمعناه ان الداتا الىل ظاهرة دى أصال مش حقيقية او مش زى الداتا الىل ن يف الـ
دة الـview عىل الـDML دة معناه نان لما ىاج اعمل اى، view with check option هنا انا عملت-
بيتحقق كل مرة من رDBMS
هو نفسه معندوشview وطبعا بما ان الـ، قبل ما يعملهwhereالرسط بتاع الـ
.base tables بيقوم واخدها ورايح يعملها عىل الـDBMS الـDML فلما ىاج اعمل اىdata of its own
له نفس السم بيعمل واحدview هنا هو بيشوف األول لو مفيش-
لن مينفعش ن، ولو نف واحد أصال بيعدل فيه، جديد
views اتني ي
.يكون ليهم نفس السم
Advantages of Views:
1- Restricting data access – By creating views, you can restrict access to specific rows or columns of a table,
ensuring that users only see the data they are authorized to access.
.table دى عىل أجزاء من الـrestrictions لكن انا هنا ممكن اقسم كمان الـ، كلهtable عىل الـrestrictions بتعملDCL ودة ألن الـ
2- Simplify commands for the user – Views can present a simplified, business-focused schema to end-users or
applications, hiding the complexity of the underlying database structure.
3- Store complex queries – Views allow you to encapsulate complex SQL queries in a simplified and reusable
way. Once a view is created, users can query the view as if it were a simple table, without needing to
understand or repeatedly write the underlying complex SQL logic.
4- Reusability Across Applications – A view can be reused in multiple queries, reports, or applications, ensuring
consistency in data retrieval and logic.
This reduces code duplication and maintenance efforts that If the business logic changes, you only need to
update the view definition rather than changing multiple queries scattered across the application.
5- Consistency Across Changes – If the underlying data changes, the view dynamically reflects the updated
data, ensuring that users always see the most current information.
6- Multiple view facility – Different views can be created on the same table for different users.
7- Data Independence – Views allow you to present a logical view of the data that is independent of how the
data is actually stored in the underlying tables.
This means that changes to the physical schema (e.g., adding or removing columns, splitting or merging
tables) can be made without requiring changes to the queries that users or applications use, as long as the
view definitions are appropriately adjusted.
Index
• An index is a schema object.
• It is used by the server to speed up the retrieval of rows by using a pointer.
• It can reduce disk I/O(input/output) by using a rapid path access method to locate data quickly.
• An index helps to speed up select queries and where clauses, but it slows down data input, with the update
and the insert statements (DMLs).
• Indexes can be created or dropped with no effect on the data.
• Indexes is used to solve stored data problems:
o Not sorted
o Scattered: data are not stored in consecutive spaces on physical memory.
Data Redundancy
• Redundant data means storing the same piece of data in multiple places.
• This not only wastes storage space but also creates potential issues with data consistency.
• If data is duplicated and one instance is updated while others are not, it leads to inconsistency.
• Normalization helps reduce redundancy by breaking down data into separate tables, ensuring that each
piece of information is stored only once.
• Data modification anomalies refer to potential problems that can occur when inserting, updating, or deleting
data in a database that is not properly normalized.
Insertion Anomaly
• An insert anomaly occurs when certain attributes cannot be inserted into the database without the presence
of other attributes.
يعن مش هقدر اضيف اى بيانات عن ى
ن، بتاع الجدولprimary key دة الـSSNهالف ان الـ ن
EMP-DEPTيعن مثال لو بصيت عىل جدول الـ •
ن
.متعي فيه ن ن
قسم معي غن لما يكون يف موظف
Update Anomaly
• An update anomaly occurs when data is duplicated in multiple rows, and a change in one instance requires
the same change to be made in all instances.
• Failure to update all copies leads to inconsistencies.
100 موظف فانا كدة عاوز اعدل المعلومة دى ن يف الـ100 لو القسم دة فيه، )Dmgr_SSN( معي
ن ن
يعن لو مثال عاوز اعدل رقم رئيس قسم •
ن
. بتوع موظفي القسم دةrow
Deletion Anomaly
• A delete anomaly occurs when the deletion of data representing one fact results in the unintended loss of
other data.
ن
بتاع الموظف دة كدة انا مسحت بيانات القسمrecord لو جيت مسحت الـ، دة شغال فيه موظف واحد بس1 يعن مثال عندى القسم رقم •
ن
بتاعdeletion فكدة وجود القسم معتمد عىل وجود الموظف وهيعمىل مشكلة يف الـ، يعتن القسم قفل ومعدش موجود عندى ن
يعن ى، كمان
.الموظف
Functional Dependency
• A functional dependency X →Y is full if Y is functionally dependent on X and not on any proper subset of X.
بمعن ن
، SSN معتمد اعتماد كىل عىل وجود الـBdate زى مثال وجود الـ، Non-key attribute is fully dependent on the key تان ن • او
.{SSN,Pnumber} معتمد اعتماد كىل عىلHoursاو وجود الـ
• However, higher levels of normalization can lead to more complex database designs and queries. It is
important to strike a balance between normalization and practicality when designing a database.
.(Multivalued attribute – Repeating group – Composite Attribute) لزم ميكونش فيها1NF بتاعن ن يف الـ
ى relation عشان أقول أن الـ-
( دول كل واحدة فيهم لوحدهاSubj , Subj-Desc , G) والـ، multi-valued attribute دةTel ن يف المثال بتاىع أنا عندى ال ـ-
.repeating group سوى فيه عالقة بينهم اذا هما3 لكن الـMulti-valued attribute
ى
.separate relations بتاعن لـ ى-
relation لزم اكرس الـ1NF يبق علشان اخليهم عىل الـ
Repeating Group:
• A repeating group occurs when a database table has a field (or set of fields) that stores multiple related
values for a single entity or record.
• This is often seen when a table includes fields that hold lists or arrays of values, rather than representing
each value as a separate record in a related table.
.composite primary key دول مع بعضSubject وStud_ID والـ، composite primary key دول مع بعضTel وStud_ID الـ-
. separate attributes within the same table بقسمه لـcomposite attribute لو كان عندى-
.1NF وطبعا تكون عىل الـPartial Dependency لزم ميكونش فيها2NF بتاعن ن يف الـ
ى relation عشان أقول أن الـ-
الجدول ن، partial dependency فمفيش كدة كدةsingle بتاعهkey اول جدول الـ-
non- لكن معنديش أصالcomposite بتاعهkeyالتان الـ
ن
fully عىل بعضه اذا هوcomposite key معتمد عىل الـGاتني لكن بما أن الـ الجدول التالت ىبق عندى، يبق برضو مفيش مشكلة
ىkey attribute
.Subj-Desc غن الـpartial dependency يبق معنديش ى، dependent
-الحل هنا بيكون نان باخد الـ attributeدة مع جزء الـ composite keyالىل بيعتمد عليه واعملهم ن يف جدول لوحدهم ،ساعتها هيكون جزء
الـ composite keyهو الـ primary keyوبيكون برضو foreign keyنف الجدول الىل فات عشان كل الجداول ى
تبق مربوطة ببعض وألن الـ Gكمان ي
معتمدة عىل الـ composite keyعىل بعضه فمينفعش افصله.
بتاعن ن يف الـ 3NFلزم ميكونش فيها Transitive Dependencyوطبعا تكون عىل الـ .2NF
ى -عشان أقول أن الـ relation
-هنا انا عندى الـ Level_Mgrبيعتمد عىل الـ levelنفسه ،والـ levelبيعتمد عىل الـ primary keyالىل هو Stud_IDاذا انا عندى Transitive
.dependency
-الحل هنا بيكون نان باخد الـ attributeدة مع الـ attributeالىل بيعتمد عليه واعملهم ن يف جدول لوحدهم ،ساعتها هيكون الـ attributeهو الـ
تبق مربوطة ببعض وألن الـ levelمعلومة مهمة عن الطالب primary keyوبيكون برضو foreign keyنف الجدول الىل فات عشان كل الجداول ى
ي
فالزم يفضل ن يف جدول الطالب.
-ن يف 4NFو 5NFوهكذا وكل ما بزود كل ما بكرس الـ relationsوازود عدد الجداول لكن دة مش recommendedاوى لن انا كدة بأثر عىل
ى
بتاعن. استخداىم للداتا وعىل حسب الـbusiness case الـ perfomanceبس برضو دة كله بيتحدد عىل طبيعة
ي
Example:
Given the student sheet example provided, design a relational database schema that captures all the information in
the sheet. The database should be normalized to at least the Third Normal Form (3NF) to eliminate redundancy and
ensure data integrity.
Solution Steps:
1- Turn the report (customer sheet) into 0NF (All attributes in one table):
Problem:
Problem:
ه بس الىل partially dependentألنها معتمدة بس عىل القسم نفسه ملهاش دعوة برقم الطالب ،لكن
هنا الـ Dept_descي -
ن
محتاجي معلومة القسم ومعلومة الطالب. ن
التني الـ Ad_GradeوالـComments
Solution:
4- Transform 2NF to 3NF
Problem:
Solution:
ACID Transactions
• A transaction is any operation that is treated as a single unit of work, which either completes fully or does
not complete at all and leaves the storage system in a consistent state.
• The classic example of a transaction is what occurs when you withdraw money from your bank account.
o Either the money has left your bank account, or it has not — there cannot be an in-between state.
• ACID transactions are a set of properties that ensure reliable processing in database management systems.
Example:
-- Start a transaction
START TRANSACTION;