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

Database Development Level 4

please make sure downloading

Uploaded by

reponceishimwe3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Database Development Level 4

please make sure downloading

Uploaded by

reponceishimwe3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Elements of competence Performance criteria

1.1 Database fundamentals are properly described based on database


standards
1. Analyse Database
1.2 Data dictionary is clearly described based on database model

1.3 Database Task requirements are properly identified based on user


requirements

2. Design Database 2.1 Conceptual Database schema is properly designed based on system
requirements

2.2 Logical Database schema is properly designed based on system


requirements

2.3 Database optimization is effectively enforced based on database


schema

2.4 Physical Database Schema is appropriately created based on the


Physical Data Model.

3.1 Data definition language commands are effectively applied based on


database schema
3. Implement
Database 3.2 Data manipulation language commands are effectively applied based
on database schema

3.3 Data control language commands are effectively applied based on


database schema

3.4 Data Query Language commands are effectively applied based on


database schema
3.5 Transaction Control Language commands are effectively applied
based on database schema

4. Secure Database 4.1 Access control is properly enforced based on database security
measures

4.2 Auditing and logging are clearly managed based on the security
policies

4.3 Data encryption is correctly implemented based on data security


measures

4.4 Backup and Recovery of data are regularly configured based on


DBMS

Learning outcomes 1: ANALYSE DATABASE


1.1: Description of database fundamental
1.1.1. Definition of key terms

1.1.1.1. Database
A database is a structured collection of data that is organized, stored, and managed in a way that
allows for efficient retrieval, modification, and manipulation of information. It typically consists
of tables or files, each containing records with fields or attributes that hold specific data.
Databases are used to store, organize, and retrieve data for various purposes, such as information
management, analysis, and application development. They are a fundamental component of
modern computer systems and play a crucial role in data-driven decision-making.

1.1.1.2. Data

Data Data has little meaning on its own; it becomes valuable when it is processed, organized, and
interpreted to extract meaningful insights or to support decision-making. Data can be collected
from various sources, including sensors, surveys, databases, and more. It is a fundamental
component in fields like computer science, statistics, and information technology, and it serves
as the foundation for analysis, research, and the operation of many modern technologies and
systems.
1.1.1.3. Information

Information is data that has been processed, organized, and given context or meaning, making it
meaningful and useful to someone. It is the result of interpreting and understanding data within a
specific context. In essence, information is data that has been refined to provide knowledge,
insight, or answers to questions.

For example, numbers in isolation may be data, but when those numbers are organized into a
table that represents monthly sales figures for a company, it becomes information that can be
used to analyze trends, make decisions, or understand the company's performance.
In summary, data is raw, unprocessed facts, while information is data that has been processed
and structured to provide valuable insights or knowledge.

1.1.1.4. Entities

Entities typically refer to distinct objects, individuals, or concepts that are represented and stored
in a database or data model. In the context of databases and data modeling:

1.1.1.5.Table

In the context of databases, a table is a structured arrangement of data organized into rows and
columns. Tables are a fundamental concept in relational databases, and they serve as containers
for storing and managing data. Here's what you need to know about tables:

1. Rows: Each row in a table represents a single record or data entry. It contains a set of values,
each corresponding to a specific attribute (or field) of the entity being described. For example,
in a "Customer" table, each row represents information about an individual customer,
including attributes like name, email, and phone number.

2. Columns: Columns, also known as fields or attributes, define the types of data that can be
stored in the table. Each column has a name and a data type, which specifies the kind of
information it can hold. For instance, a "Product" table might have columns like "Product ID,"
"Product Name," "Price," and "Quantity."

3. Relational Databases: Tables are a core component of relational database management


systems
(RDBMS), such as MySQL, PostgreSQL, and Microsoft SQL Server. In a relational database,
multiple tables can be related to one another through keys (e.g., primary keys and foreign keys)
to establish connections between different entities.
4. Data Integrity: Tables often enforce data integrity constraints to maintain the quality and
consistency of data. Common constraints include unique constraints to ensure data uniqueness,
primary keys to uniquely identify records, and foreign keys to establish relationships between
tables.

5. Querying: Users can query tables using SQL (Structured Query Language) to retrieve, insert,
update, or delete data as needed. SQL provides a standardized way to interact with the data
stored in tables.

Tables play a vital role in organizing and structuring data within a database, making it accessible,
efficient to manage, and suitable for various applications and analysis purposes.

1.1.1.6.Records

1. Database Records: In a relational database, each record corresponds to a row in a table.


Each row contains a complete set of attributes (fields) that describe a specific instance of the
entity the table represents. For example, in a "Student" table, each record might represent
information about a single student, with attributes like "Student ID," "Name," "Birthdate," and so
on.

2. File Systems: In some file-based systems, records are used to store structured data.
These records can represent items, transactions, or any other type of information. For instance, in
a filebased inventory system, each record could represent a specific product with attributes like
"Product ID," "Name," "Price," and "Quantity."

3. Data Formats: Records are used in various data formats, such as CSV (Comma-
Separated Values) files, where each line typically represents a record, and the fields within that
line are separated by commas.

1.1.1.7.Database schema

A database schema is a logical blueprint or design that defines the structure, organization, and
relationships of data within a relational database management system (RDBMS) or other data
storage systems. It serves as a framework for how data is organized and stored in a database.
Here are some key aspects of a database schema:

1. Table Definitions: A database schema defines the tables that will exist within the
database, including their names, attributes (columns), and data types. Each table represents a
specific entity or concept, and its schema specifies the fields (attributes) that make up the table.
2. Constraints: The schema can include constraints that enforce data integrity rules, such as
primary keys (unique identifiers for each record), foreign keys (relationships between tables),
and check constraints (rules for valid data values).

3. Relationships: It defines the relationships between tables, indicating how data in one
table relates to data in another. These relationships are often expressed through foreign keys,
which establish links between tables.

4. Indexes: A schema can specify which columns should be indexed to optimize data
retrieval performance. Indexes make it faster to search and retrieve data but come with trade-offs
in terms of storage space and update speed.

5. Security and Permissions: Database schemas can include access control settings,
specifying who has permission to perform various operations on the tables and data within the
schema.

6. Views and Procedures: The schema may encompass views (virtual tables that present
data from one or more tables) and stored procedures (predefined routines for data manipulation
and processing).

7. Data Types: It defines the types of data that can be stored in each column, such as text,
numbers, dates, or binary data.

Database schemas play a critical role in ensuring data consistency, integrity, and organization
within a database. They provide a structured framework for database administrators, developers,
and users to understand how data is organized and how it can be accessed and manipulated.
Additionally, schemas help maintain data quality and consistency throughout the database's
lifecycle.

1.1.1.8.DBMS

DBMS stands for "Database Management System." It is software that enables users and
applications to interact with databases, providing a structured and efficient way to store, retrieve,
update, and manage data. Here are key features and functions of a DBMS:

1.1.1.9.SQL

SQL, or Structured Query Language, is a domain-specific programming language used for


managing and manipulating relational databases. SQL provides a standardized way to interact
with databases, allowing users to perform various operations on the data stored within a
database.

1.2. Applications of databases

Databases are a foundational technology used in a wide range of applications across various
industries. Here are some common applications of databases:

1. Business and Enterprise Systems:


 Customer Relationship Management (CRM): Databases store customer data,
purchase history, and interactions, helping businesses manage relationships and
improve customer service.
 Enterprise Resource Planning (ERP): ERP systems rely on databases to integrate
and manage business processes such as finance, inventory, and human resources.

2. E-commerce:
 Online Shopping: Databases store product catalogs, customer profiles, order histories,
and transaction records for online retailers.

3. Healthcare:
 Electronic Health Records (EHR): Databases store patient records, medical histories,
prescriptions, and test results, facilitating efficient healthcare management and patient
care.

4. Finance:
 Banking and Finance: Databases store customer accounts, transaction records, and
financial data, enabling secure and efficient financial operations.

5. Education:
 Student Information Systems (SIS): Databases store student profiles, grades,
attendance, and course information, supporting educational institutions in managing
student data.

6. Logistics and Supply Chain Management:


 Inventory Management: Databases track inventory levels, order histories, and supply
chain data, optimizing supply chain operations.
7. Social Media and Content Management:
 Social Media Platforms: Databases store user profiles, posts, comments, and media
files for social networks.
 Content Management Systems (CMS): Databases manage content, articles, images,
and user-generated content on websites and blogs.
8. Telecommunications:
 Call Detail Records (CDR): Databases store call logs, subscriber data, and network
information for telecommunications providers.

9. Government and Public Services:


 Voter Registration: Databases manage voter information and election records.
 Public Health: Databases track disease outbreaks, vaccinations, and health statistics.

10. Scientific Research:


 Laboratory and Research Data: Databases store experimental data, research findings,
and scientific measurements for analysis and collaboration.

11. Gaming:
 Gaming Databases: Databases store player profiles, achievements, game states, and
ingame transactions for online and mobile games.

12. Agriculture:
 Precision Agriculture: Databases store data on soil conditions, weather, crop yields,
and equipment telemetry, helping farmers make informed decisions.

13. Energy and Utilities:


 Smart Grids: Databases manage data from smart meters and sensors to monitor and
optimize energy distribution.

14. Airlines and Transportation:


 Flight Reservations: Databases handle flight schedules, passenger bookings, and
ticketing systems for airlines.

15. E-government:
 Government Services: Databases support online government services, such as tax
filing, permit applications, and license renewals.

Databases are a crucial tool for organizing, storing, and retrieving structured data, making them
essential for modern information management and decision-making in various domains. Their
versatility and ability to handle large volumes of data make them integral to numerous
applications.

1.3. ADVANTAGES AND DISADVANTAGES OF DATABASES


Databases offer many advantages, but they also come with some disadvantages. Here's an overview of the
pros and cons of using databases:

Advantages of Databases:

1. Data Organization: Databases provide a structured and organized way to store and manage data,
making it easier to locate and retrieve information.

2. Data Integrity: Databases can enforce data integrity constraints, ensuring that data remains
accurate and consistent over time.

3. Efficient Retrieval: Using queries and indexing, databases enable efficient and quick data
retrieval, even from large datasets.

4. Concurrency Control: Databases manage multiple users or applications accessing the data
simultaneously, preventing conflicts and ensuring data consistency.

5. Security: Databases offer security features like user authentication and access control to protect
sensitive information.

6. Data Redundancy Reduction: Databases minimize data duplication, reducing storage space
requirements and maintenance efforts.

7. Scalability: Databases can scale to handle growing amounts of data and users, making them
suitable for both small and large applications.

8. Data Backup and Recovery: Databases support backup and recovery mechanisms to safeguard
against data loss due to hardware failures or other issues.

Disadvantages of Databases:

1. Complexity: Setting up and managing databases can be complex and may require specialized
knowledge and skills.

2. Cost: Databases often involve significant initial and ongoing costs for software, hardware,
maintenance, and licensing.

3. Performance Overhead: Some database operations, such as indexing and locking, can introduce
performance overhead, especially in high-transaction environments.

4. Data Security Concerns: Despite security features, databases can still be vulnerable to security
breaches and require constant monitoring and updates.
5. Resource Intensive: Running a database system requires sufficient computational resources
(CPU, RAM, storage) which may lead to resource contention in shared environments.

6. Data Migration Challenges: Moving data between different database systems or versions can be
challenging and time-consuming.

7. Data Lock-In: Depending on the chosen database technology, migrating away from a specific
database system can be difficult due to data lock-in.

8. Backup and Recovery Complexity: While databases offer backup and recovery mechanisms,
setting them up correctly and ensuring data integrity during recovery can be complex.

In summary, databases provide a powerful and organized way to manage and retrieve data efficiently, but
they also require careful planning, management, and consideration of associated costs and complexities.
The choice of whether to use a database depends on the specific needs and requirements of the application
or organization.

1.4. Identification of database models

1.4.1. Relational database


A relational database is a type of database that organizes and stores data in a structured way
using tables, where data is stored in rows and columns. This database model is based on the
principles of the relational data model, which was introduced by Edgar F. Codd in 1970.
Popular relational database management systems (RDBMS) include MySQL, PostgreSQL,
Oracle Database, Microsoft SQL Server, and SQLite, among others. Relational databases are
widely used in various applications and industries due to their ability to provide structured,
consistent, and reliable data storage and retrieval.

1.4.2. Hierarchical database

A hierarchical database is a type of database management system (DBMS) that stores and
organizes data in a tree-like structure with parent-child relationships. In a hierarchical database,
data is organized into a hierarchy, where each data element is linked to one parent and can have
multiple children. This model was prevalent in early database systems and is characterized by the
following features:

It's important to note that hierarchical databases have largely been superseded by relational
databases due to their limitations in handling complex and dynamically changing data structures.
Relational databases provide a more flexible and efficient way to manage and query data.
However, hierarchical databases are still used in some specialized applications where data
naturally fits a hierarchical structure.

1.4.3. Network database


A network database, also known as a network model, is a database management system
(DBMS) that represents data as a collection of records linked together by predefined
relationships. This model extends the hierarchical database model and provides greater
flexibility in representing complex data structures.
It's important to note that network databases were widely used in the 1960s and 1970s but have
largely been replaced by relational databases due to their complexity and the development of
standardized SQL-based querying. However, the network model is still employed in some
specialized applications where the data structure naturally fits this model or where legacy
systems are in use.

1.4.4. Object oriented model

The Object-Oriented Database Model (OODBMS) is a database management system that extends
the principles of object-oriented programming (OOP) to databases. In OODBMS, data is
organized and represented as objects, similar to how objects are used in object-oriented
programming. Here are key characteristics and concepts associated with the object-oriented
database model:

The object-oriented database model is particularly suitable for applications where data entities
and their relationships are naturally represented in an object-oriented fashion, such as in software
development, engineering, and simulations. However, OODBMS adoption is not as widespread
as relational databases due to the complexity of implementing and querying them, as well as the
dominance of relational database systems in many industries.

1.5. Identification of database Relationship

Database relationships are connections between tables that define how data in one table is related
to data in another table. There are several types of relationships:
1. One-to-One (1:1): In this type of relationship, each record in one table is associated with
one and only one record in another table.

For example, Imagine a library system where each library card is linked to a unique person. In
this scenario:
 Person is one entity, and each person can have only one library card.
 Each library card is also linked to one person
So, it's a one-to-one relationship between people and library cards. Each person has a unique
library card, and each library card belongs to only one person. This helps students grasp the
concept of a one-to-one relationship in databases, where each record in one table is related to
exactly one record in another table
2. One-to-Many (1:N): In a one-to-many relationship, one record in one table can be
associated with multiple records in another table, but each record in the second table is
associated with only one record in the first table. For instance, a customer can have multiple
orders, but each order is linked to only one customer.
Example: Teacher and Students
In a school database:
1. Teacher is one entity, and each teacher can have many students in their class.
2. Each student is linked to one teacher.
So, it's a one-to-many relationship between teachers and students. Each teacher can have
multiple students, but each student has only one teacher.
3 . Many-to-One (N:1): This is the reverse of a one-to-many relationship. Many records in one
table can be associated with one record in another table. For instance, many employees may
belong to a single department.
4. Many-to-Many (N:N): In a many-to-many relationship, multiple records in one table can be
associated with multiple records in another table. For example, students can be enrolled in
multiple courses, and each course can have multiple students.
Example: Students and Courses
In a school database:

1. **Students** can enroll in **many** courses.


2. Each **course** can have **many** students.
This creates a many-to-many relationship between students and courses. Multiple students can be
enrolled in multiple courses simultaneously.
1.6. Determination of data types

1.6.1. Definition of Data type

In a database context, a “data type” refers to a classification that specifies which type of data can
be stored in a particular column or field of a database table. Data types are used to ensure that
data is stored accurately and efficiently, and they determine how the database system should treat
the data.
1.6.2. Types of Data Types

1.6.2.1. character data type


The character data type is used to store textual data in a database. It is commonly used for storing
strings of characters, such as names, addresses, and other textual information. Character data
types come in various forms, including:
1. CHAR: This is a fixed-length character data type. When you define a column as CHAR(10),
for example, it will always occupy 10 characters of storage, padding with spaces if necessary.
This can be useful for data that has a consistent length, like postal codes.
2. VARCHAR: This is a variable-length character data type. It only uses as much storage as
needed for the actual data, plus a few bytes for length information. For example, if you store
"John" in a VARCHAR(20) column, it will occupy 4 characters plus some additional bytes for
length metadata.
3. TEXT: This data type is used for longer text values, and it allows for even more flexibility in
terms of length. TEXT columns can store large amounts of textual data, such as paragraphs of
text, without a fixed maximum length.
The choice between CHAR, VARCHAR, or TEXT depends on your specific data storage
requirements. Use CHAR when you have a consistent length for your data, VARCHAR when
the length varies but is relatively short, and TEXT when you need to store longer text data.
1.6.2.2. Numeric Data Type
The numeric data type is used to store numeric values in a database. It's crucial for representing
various types of numerical data. Depending on the specific database system you're using, there
can be different numeric data types available, but here are some common ones:
1. INT (Integer): INT is used to store whole numbers, typically with a range of values. It can be
either signed (positive and negative values) or unsigned (only positive values). For example, an
INT can store values like -2,147,483,648 to 2,147,483,647 (for a 32-bit signed INT).
2. **BIGINT:** BIGINT is used to store larger integer values. It has a wider range than INT and
is often used for situations where you need to store very large integers.
3. **DECIMAL or NUMERIC (Fixed-Point):** These data types are used to store exact numeric
values with a specified precision and scale. Precision represents the total number of digits, and
scale represents the number of decimal places. For example, DECIMAL(8, 2) can store values
like 12345.67.
4. **FLOAT and DOUBLE (Floating-Point):** FLOAT and DOUBLE are used to store
floating-point numbers, which include real numbers with decimal points. DOUBLE typically has
higher precision than FLOAT.
5. **REAL:** REAL is another floating-point type with a single-precision floating-point
format. It's often used for applications where precision is not as critical as with DOUBLE.
6. **MONEY:** MONEY is a specialized numeric data type used to store currency values,
ensuring precision for financial calculations.
7. **SERIAL (Auto-incrementing):** Some database systems offer a SERIAL or
AUTO_INCREMENT data type that automatically increments a numeric value when inserting a
new record. It's often used for primary keys.
8. **BIT or BOOLEAN:** These data types are used to store binary values such as true/false or
0/1. They are often used for representing Boolean
1.6.2.3. Date Data Type
The date data type is used to store date and time information in a database. Here are some
common date data types:
1. **DATE:** The DATE data type stores calendar dates without any time information. For
example, you can use it to represent a birthdate or an order date.
2. **TIME:** The TIME data type stores time of day without a date component. It is used to
represent specific times, such as appointment times.
3. **DATETIME or TIMESTAMP:** These data types store both date and time information.
They are versatile and commonly used for representing events that occur at a specific date and
time, such as log entries or financial transactions.

1.7. Description of data dictionary

1.7.1. Definition of Data Dictionary

A data dictionary, often referred to as a metadata (data about data or information about data)
repository or data catalog, is a centralized repository or document that contains detailed
information about data elements, data structures, database schema, and the meaning and usage of
data within a database or information system. It serves as a valuable resource for data
management, database administrators, developers, and other stakeholders.
Employee Data Dictionary
Field Name Data Type Length Format Description
EmployeeID Integer 4 NNNN Unidue identifier
for each
employee
FirstName String 50 AlphaNumeric First name of the
employee
LastName String 50 AlphaNumeric Last name of the
employee
DateOfBirth Date YYYY-MM-DD Date of birth of
the employee
Department String 50 Alpha Department
where the
employee works
Salary Decimal(10,2)| NNNNNN.NN Annual salary of
the employee

1.7.2. Elements of Data Dictionary

A data dictionary typically contains several key elements of information about the data within a
database or information system. These elements help describe and document the data, making it
easier to manage and understand. Here are the essential elements found in a data dictionary:
1. **Data Element Name:** The name or identifier for the data element, which corresponds to a
specific field or column in a database table.
 Data Type
 Name
 Description
 Length
 Format
 Constraints
 Validation Rules
 Indexes

A well-structured data dictionary serves as a valuable reference for data management, data
governance, and database design efforts within an organization. It ensures that data is well-
documented, understood, and used effectively across different teams and projects.
1.8. Identification of database requirements
1.8.1. Types of database requirements

 Functional requirement

Functional requirements in database specify what the database must do. They detail data entry,
retrieval, modification, security, integrity, and other function to ensure it meets user needs and
objectives
Functional reequipments outline how the database should function with in the library
management system, addressing various aspects of data handling, security, and user interaction
 Non-functional requirement

Non-functional requirements describe the quality attributes and characteristics of a system or


software, such as performance, security, usability, and scalability, that define how it should
behave or perform, rather than what it should do.
1.8.2. Methods to collect data

1. Interviews: Conduct one-on-one or group interviews to gather in-depth information.


2. Observation: Directly watch and record behaviors or events. Without directly
interfering or influencing what is being observed
3. Documentation: Analyze existing records, documents, or reports.
4. Questionnaire: is a common method for collecting structured data through a set of pre-
defined questions

END LEARNING OF OUTCOME ONE!!!!!!!!!!!!!!


Learning outcome 2: Design Database
2.1. Description of database schema

2.1.1. Types of Database Schema


A database schema is the blueprint or structure that defines how data is organized and stored in a
database. It includes information about tables, columns, relationships, keys, and constraints,
providing a framework for managing and accessing data efficiently and accurately and there is
three types of database schema
1) conceptual schema
A conceptual schema is a high-level abstract representation of a database's structure, defining its
entities, attributes, and their relationships, without specifying technical implementation details. It
provides a clear, non-technical view of the data model.
2) logical database schema
A logical database schema is a detailed representation of a database's structure that includes
tables, columns, data types, and relationships between tables. It's independent of the physical
implementation and focuses on data organization and integrity.
3) logical database schema
A logical database schema serves as a bridge between the high-level conceptual schema and the
physical implementation of a database. It defines the structure of the database in more detail than
the conceptual schema but is still abstracted from the specific technical aspects like storage
mechanisms and indexing.
Differences between conceptual, logical, and physical database schemas
Conceptual Schema Logical Schema Physical Schema
 Abstraction Level:  Abstraction Level:  Abstraction Level:
High-level Intermediate-level Low-level, concrete
abstraction. abstraction implementation

 Purpose: Provides a  Purpose Describes  Purpose: Specifies


global view of the the database structure the technical
entire database in detail, including implementation
system, defining tables, columns, data details of how data is
entities, their types, and stored, such as file
attributes, and relationships between formats, storage
relationships. tables. locations, indexing
methods, and
 Audience: Intended  Audience Primarily hardware
for business for database designers considerations.
stakeholders and users and developers who
who need a non- need to design the  Audience: Targeted
technical at database
understanding of the database structure. administrators and
data model system architects
 Implementation responsible for
 Implementation Details: Independent configuring and
Details: Does not of the specific optimizing the
specify technical hardware or software, database system.
implementation but defines the logical
details like tables or organization of data.  Implementation
data types. Details: Defines the
actual storage
mechanisms and
optimizations specific
to the chosen
hardware and
software platform

Conclusion: the conceptual schema is the high-level "what" of the database, the logical schema
is the detailed "how" in terms of data structure, and the physical schema is the even more
detailed "how" in terms of storage and performance considerations. These three schemas provide
different views of the same database, each tailored to specific stakeholders and purposes in the
database design and manipulation

2.1.2. Data abstraction levels

In DBMS data abstraction means hiding unnecessary background details from the end user to
make the accessing of data easy and secure. In DBMS , there Are 3 Levels Of Data Abstraction :
1) Physical level or internal level
This is the layer of data abstraction where the raw data is physically stored as files. This layer
contains all the complex data structures and the data accessing methods defined. The physical
layer is the lowest level of data abstraction in a DBMS. It is the database administrator who
decides how the data is to be stored in these physical hard drives.
Example:
When we access data we may get a single data or a table of data. Moreover, by the term
"relational database" we visualize a table of rows and columns. But at a physical level, these
tables are stored in hard drives which are located at a very secure data center.
This is the layer where the raw is stored in file format on physical hard drives
2) Logical Level or Conceptual Level:
After taking the raw data from the physical or internal level, the structure of the data is defined at
the logical or conceptual level. This is like a blueprint of the raw data. This layer does not have
any information about how the end user will view the data.
Example:
We have data of a few products like product id, product name, and manufacturing date, and we
have another set of data of customers containing customer id, customer name, and customer
address. Now, we need to frame this data in proper tables of products and customers. After that,
we can even frame a join to show which product has been ordered by which customer.
In this layer, the raw data is taken from the physical layer and organized in a proper structure,
like in tabular format
3) View Level or External Level
This is what an end-user gets to see. He/she does not get the entire database, but depending on
the queries made from the front-end the user gets to see the data. It may be a single data from the
entire database or a collection of data in tabular format. Multiple views of the same data are
available to the user, the representation can be a table, a graph, or a pie chart. View Level is the
highest level of data abstraction in DBMS.
Example:
Concerning the example in the logical level section, let us say a customer wants to view the order
history, he gets to see only the orders he had made in the past. Now, let us say a shop owner
needs to see the products that are on the order list. He gets to see a table containing all the info
about the products and the customers to whom they need to be delivered.

The following diagram will give you a clear view of how the implementation is done
Starting from the very bottom, we have the physical or internal layer, then we have the middle
layer, the logical or conceptual layer, and finally, we have the view or external layer.
2.1.3. Types of data independence
Data independence is the ability to modify one level of DBMS without affecting the schema
definition of the next higher level’s data structure
1) Physical data independence
This is defined as the ability to modify the physical schema of the database without the
modification causing any changes in the logical /conceptual or View/external level

Why is Physical Data Independence Important?


 Physical data independence allows you to distinguish between conceptual and internal/physical
levels.
 It allows you to describe the database logically without needing to identify physical structures.
 Physical data independence allows you to modify physical storage structures or devices without
affecting the conceptual model of the database
 preventing any modifications to the conceptual level.

Examples of Physical Data Independence:


 Changing from one data structure to another.
 Making use of new storage technology, such as a hard drive or magnetic tapes
 Change the location of the database from one drive to another.
 Changing the database's file organization.

2) Logical data independence

Logical Data Independence Is the ability to modify logical schema without causing any
unwanted modifications to the external schema or the application programs to be rewritten.
Why is Logical Data Independence Important?
 Logical data is database data, which means it stores information about how data is managed
within the database.
 Logical data independence is a method that makes sure that if we make modifications to the table
format, the data should not be affected.
 Used to distinguish the external level from the conceptual view, logical data independence is
used.
 Any modifications to the conceptual representation of the data will not affect the user's view of
the data.

2.2. Description of database schema

2.2.1. Description of conceptual database schema

A conceptual database schema is a high-level representation of the structure and organization of


a database. It defines the entities (tables), attributes (columns), and the relationships between
them, without specifying technical implementation details. This schema helps in understanding
the data model and designing the database. Here's a simplified example of a conceptual database
schema for a library:
Entities:
1. Book
- Attributes: ISBN, Title, Author, Publication Year
2. Author
- Attributes: Author ID, Name, Birthdate, Nationality
3. Publisher
- Attributes: Publisher ID, Name, Address, Phone
Relationships:
- A Book is written by an Author (Many-to-One)
- An Author can write many Books (One-to-Many)
- A Book is published by a Publisher (Many-to-One)
- A Publisher can publish many Books (One-to-Many)

2.2.2. Entity relationship diagram (ERD)

2.2.2.1. Entity relationship diagram (ERD)

The Entity Relational Model is a model for identifying entities to be represented in the database
and representation of how those entities are related. The ER data model specifies enterprise
schema that represents the overall logical structure of a database graphically.
 Symbols Used in ER Model

ER Model is used to model the logical view of the system from a data perspective which consists
of these symbols:

Rectangles: Rectangles represent Entities in the ER Model.


Ellipses: Ellipses represent Attributes in the ER Model.
Diamond: Diamonds represent Relationships among Entities.
Lines: Lines represent attributes to entities and entity sets with other relationship types.
Double Ellipse: Double Ellipses represent Multi-Valued Attributes.
Double Rectangle: Double Rectangle represents a Weak Entity.
 Components of ER Diagram

ER Model consists of Entities, Attributes, and Relationships among Entities in a Database


System.

Entity
An Entity may be an object with a physical existence – a particular person, car, house, or
employee or it may be an object with a conceptual existence – a company, a job, or a university
course.

Entity Set: An Entity is an object of Entity Type and a set of all entities is called an entity set.
For Example, E1 is an entity having Entity Type Student and the set of all students is called
Entity Set. In ER diagram, Entity Type is represented as:
1. Strong Entity
A Strong Entity is a type of entity that has a key Attribute. Strong Entity does not depend on
other Entity in the Schema. It has a primary key, that helps in identifying it uniquely, and it is
represented by a rectangle. These are called Strong Entity Types.
2. Weak Entity
An Entity type has a key attribute that uniquely identifies each entity in the entity set. But some
entity type exists for which key attributes can’t be defined. These are called Weak Entity types.
For Example, A company may store the information of dependents (Parents, Children, Spouse)
of an Employee. But the dependents don’t have existed without the employee. So Dependent will
be a Weak Entity Type and Employee will be Identifying Entity type for Dependent, which
means it is Strong Entity Type.
A weak entity type is represented by a Double Rectangle. The participation of weak entity types
is always total. The relationship between the weak entity types and its identifying strong entity
type is called identifying relationship and it is represented by a double diamond.
Attributes
Attributes are the properties that define the entity type. For example, Roll_No, Name, DOB,
Age, Address, and Mobile_No are the attributes that define entity type Student. In ER diagram,
the attribute is represented by an oval.

1. Key Attribute
The attribute which uniquely identifies each entity in the entity set is called the key attribute. For
example, Roll_No will be unique for each student. In ER diagram, the key attribute is
represented by an oval with underlying lines.

2. Composite Attribute
An attribute composed of many other attributes is called a composite attribute. For example, the
Address attribute of the student Entity type consists of Street, City, State, and Country. In ER
diagram, the composite attribute is represented by an oval comprising of ovals.

3. Derived Attribute

An attribute that can be derived from other attributes of the entity type is known as a derived
attribute. e.g.; Age (can be derived from DOB). In ER diagram, the derived attribute is
represented by a dashed oval.

4. Multivalued Attribute
An attribute consisting of more than one value for a given entity. For example, Phone_No (can
be more than one for a given student). In ER diagram, a multivalued attribute is represented by a
double oval.
How to Draw ER Diagram
 The very first step is Identifying all the Entities, and place them in a Rectangle, and labeling them
accordingly.
 The next step is to identify the relationship between them and pace them accordingly using the
Diamond, and make sure that, Relationships are not connected to each other.
 Attach attributes to the entities properly.
 Remove redundant entities and relationships.
 Add proper colors to highlight the data present in the database.

Employee Management System ERD Template


Use our employee management system ERD template to streamline administrative tasks for your
department. Whether you are part of the HR department or belong to a different team, this
system will bring along benefits that will ease workflows and improve performance.
What is an employee management system?
An employee management system is a powerful tool built mainly for human resource
departments to help streamline their duties. Its use can also be transferred to other departments
for organizing administrative key operations.
Our template incorporates basic employee information you can quickly expand or modify to fit
your business’ requirements. Here are a few examples of what you can include:
 Employee information - name, contact details

 Login credentials

 Role name and description

 Department name and description


2.2. Design of logical database schema

2.2.1. Table constraints

In the context of databases and database management systems (DBMS), a constraint is a rule or
condition applied to data within a database table to maintain the integrity, accuracy, and
consistency of the data. Constraints are used to ensure that data adheres to certain criteria, and
they prevent the insertion, modification, or deletion of data that would violate these criteria.
Constraints play a crucial role in maintaining data quality and preventing errors in a database.
Here are some common types of constraints:

1. NOT NULL Constraint.

A NOT NULL constraint is a rule in a relational database that ensures a column cannot contain
NULL (missing or undefined) values. It enforces that every row in a table must have a value for
that column. This constraint helps maintain data integrity by preventing the insertion of
incomplete or ambiguous data.
By default, a table column can hold NULL Values
The following SQL enforces the "P_Id" column and the "LastName" column to not accept
NULL values:
CREATE TABLE Persons(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255);
2. UNIQUE Constraint.

A unique constraint is a database constraint that ensures that the values in a column or a set of
columns are unique across all rows in a table. In other words, it enforces the uniqueness of data
within a specific column or combination of columns, preventing duplicate entries.
Key points about unique constraints:
1. Uniqueness: Each value in the specified column(s) must be unique; no two rows can have the
same value(s) in the constrained column(s).
2. Single or Composite: You can apply a unique constraint to a single column or a combination
of columns. When applied to multiple columns, it enforces uniqueness across the combination of
those columns.
3. Data Integrity: Unique constraints help maintain data integrity by preventing the insertion of
duplicate or conflicting data into a table.
4. Indexed: In most database systems, unique constraints are automatically indexed to improve
query performance when searching for unique values.
5. **Primary Key vs. Unique Constraint**: While both primary keys and unique constraints
enforce uniqueness, there are differences. A primary key is a unique constraint with the
additional requirement that it cannot contain NULL values and is often used as the main
identifier for a row. Unique constraints can allow NULL values unless specified otherwise.
Here's an example of defining a unique constraint in SQL:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeEmail VARCHAR(255) UNIQUE,
EmployeeSSN VARCHAR(15) UNIQUE
);
3. DEFAULT Constraint.

The DEFAULT constraint is used to insert a default value into a column when the INSERT
INTO statement does not provide a specific value.
4. CHECK Constraint.

The CHECK constraint is used to limit the value range that can be placed in a column.If you
define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
SQL CHECK Constraint on CREATE TABLE
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table
is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.
CREATE TABLE Persons(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0));

5. PRIMARY KEY Constraint.

A primary key is a field or a set of fields in a database table that uniquely identifies each record
(row) in that table. It serves as a way to ensure data integrity and provide a way to access and
reference individual records within a database. Here are some key characteristics and points
about primary keys:
Uniqueness: Every value in a primary key column must be unique within the table. This means
that no two records can have the same value in their primary key field(s).
Non-null: A primary key field cannot contain null values. It must have a valid, non-null value
for every record in the table.
Indexing: Primary keys are often automatically indexed by database management systems
(DBMS) for faster data retrieval. This indexing helps improve the efficiency of searching for
specific records.
Single or Composite: A primary key can consist of a single field (e.g., an employee ID) or
multiple fields combined (e.g., a combination of employee ID and department ID). In the latter
case, it's called a composite primary key.
Data Integrity: Primary keys help enforce data integrity by ensuring that there are no duplicate
or null values in the key field(s). This constraint helps maintain the quality and consistency of
the data in the database.
Foreign Keys: Primary keys are often used in relationships between tables. When a field in one
table references the primary key of another table, it's called a foreign key. Foreign keys establish
relationships between tables in a relational database.
Auto-incrementing: In some databases, primary key fields can be set to auto-increment, meaning
that a new unique value is automatically generated for each new record. This is common for
surrogate keys, where the primary key doesn't have a meaningful business value but is solely
used for identification.
Primary keys are defined using constraints in SQL (Structured Query Language) to enforce the
uniqueness and non-null rules. Common SQL commands for defining primary keys include
PRIMARY KEY constraints in CREATE TABLE statements.
Example:
CREATE TABLEEmployees (EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50),
LastName VARCHAR(50), DepartmentID INT );
In this example, "EmployeeID" is defined as the primary key for the "Employees" table, ensuring
that each employee has a unique identification number.
6. FOREIGN KEY Constraint.
A FOREIGN KEY constraint is a database constraint that enforces referential integrity between
two tables in a relational database. It defines a relationship between the data in two tables: a
parent table (referenced table) and a child table (dependent table). The FOREIGN KEY
constraint ensures that the values in the child table's foreign key column(s) correspond to values
in the parent table's primary key column(s).
Here are some key points about FOREIGN KEY constraints:
Relationship: A FOREIGN KEY constraint establishes a relationship between two tables based
on a common column or columns. The column(s) in the child table that serve as foreign keys
reference the primary key column(s) in the parent table.
Referential Integrity: The primary purpose of a FOREIGN KEY constraint is to maintain
referential integrity, which means that the data in the child table remains consistent with the data
in the parent table. It prevents orphaned records in the child table, ensuring that the child table's
foreign key values correspond to valid primary key values in the parent table.
Cascade Actions: When defining a FOREIGN KEY constraint, you can specify what actions
should occur when records in the parent table are modified or deleted. Common options include:
CASCADE: If a record in the parent table is updated or deleted, the corresponding records in the
child table are updated or deleted as well.
SET NULL: If a record in the parent table is updated or deleted, the foreign key values in the
child table are set to NULL.
SET DEFAULT: Similar to SET NULL, but sets the foreign key values to their default values.
NO ACTION or RESTRICT: Prevents any update or deletion in the parent table if it would
create orphaned records in the child table.
Multiple Foreign Keys: A table can have multiple FOREIGN KEY constraints, each referencing
a different parent table and column(s).
Syntax: In SQL, FOREIGN KEY constraints are defined when creating a table using the
FOREIGN KEY keyword, and they reference the parent table's primary key column(s). Here's an
example:
sqlCopy code
CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT, OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );
In this example, the "Orders" table has a foreign key constraint on the "CustomerID" column,
which references the "CustomerID" column in the "Customers" table.
Enforcement: The FOREIGN KEY constraint enforces data integrity by preventing the insertion
of records in the child table with foreign key values that do not exist in the parent table's primary
key.
By using FOREIGN KEY constraints, you ensure that your database maintains consistency and
relationships between related tables, which is a fundamental aspect of relational database
management systems (RDBMS).
2.2.2. Convert conceptual database schema to logical database schema
Converting a conceptual database schema to a logical database schema is an important step in the
database design process. The conceptual schema represents the high-level view of the data and
its relationships, while the logical schema provides a detailed blueprint of how the data will be
structured in a relational database management system (RDBMS).
Let's walk through an example of converting a conceptual database schema into a logical
database schema.
Conceptual Database Schema: Suppose we have a conceptual database schema for a library
system. The main entities in our conceptual schema are:
 Books
 Authors
 Borrowers
The relationships between these entities are as follows:
 Authors can write multiple books.
 Books can have multiple authors.
 Borrowers can borrow multiple books.
 Books can be borrowed by multiple borrowers.
Steps to Convert to Logical Database Schema:
Identify Entities and Attributes:
Books
Attributes: ISBN (Primary Key), Title, Publication Year, Genre
Authors
Attributes: AuthorID (Primary Key), Author Name
Borrowers
Attributes: BorrowerID (Primary Key), Borrower Name
Define Relationships:
Authors can write multiple books, and books can have multiple authors. This is a many-to-many
relationship.
Borrowers can borrow multiple books, and books can be borrowed by multiple borrowers. This
is also a many-to-many relationship.
Refine Relationships:
To represent the many-to-many relationships, we need two additional tables: one to link books
and authors and another to link books and borrowers.
Normalize Tables:
We'll ensure that our tables are in at least the Third Normal Form (3NF). In this case, no
additional normalization is required.
Create Logical Schema:
We create the following tables in our logical schema:
Books (ISBN, Title, Publication Year, Genre)
Authors (AuthorID, Author Name)
Borrowers (BorrowerID, Borrower Name)
BookAuthors (ISBN, AuthorID) - to represent the many-to-many relationship between books and
authors.
BookBorrowers (ISBN, BorrowerID) - to represent the many-to-many relationship between
books and borrowers.
Define Constraints:
Primary key constraints are defined on the primary key columns (ISBN, AuthorID, BorrowerID)
of their respective tables.
Foreign key constraints are added to the linking tables (Book_Authors and Book_Borrowers) to
enforce referential integrity.
2.3. Optimization of database

2.3.1. Data normalization


Normalization in the context of databases is a process used to organize data in a relational
database efficiently. It involves breaking down a large table into smaller, related tables and
establishing relationships between them. The main goals of normalization are to reduce data
redundancy, improve data integrity, and minimize anomalies during data updates.
Normalization typically involves dividing a table into multiple tables and using relationships like
foreign keys to link them. The most common normalization forms are the First Normal Form
(1NF), Second Normal Form (2NF), Third Normal Form (3NF), and others. Each form has
specific rules to ensure data is organized in a way that avoids data anomalies and redundancy.
 FIRST NORMAL FORM(1NF):
The First Normal Form (1NF) is one of the fundamental principles of database normalization,
and it ensures that a relational database table is organized in a structured and consistent way. To
meet the criteria of 1NF, a table must have the following characteristics:

1. Atomic Values: Each cell in the table must hold a single, indivisible (atomic) value. This
means that each attribute (column) should contain only one value, and these values should not be
arrays, lists, or sets. If you have multi-valued attributes, you should create separate rows for each
combination of values.
2. Unique Column Names: Every column (attribute) in the table should have a unique name.
This ensures that there is no ambiguity in identifying the attributes.
3. Orderly Rows: The order in which rows are stored should not affect the data's integrity or
meaning. In other words, the rows should be unordered, and the database should be able to
retrieve data without relying on a specific row order.
4. Primary Key: Each table must have a primary key that uniquely identifies each row in the
table. This key helps establish relationships between tables and ensures that each row is distinct.
5.No Repeating Groups: There should be no repeating groups or arrays within a cell. If you
need to store multiple values for an attribute, create a new table and establish a relationship
between the original table and the new one.
Let's illustrate the characteristics of the First Normal Form (1NF) with a simple example.
Suppose you have a table named "StudentCourses" that keeps track of students and the courses
they are enrolled in. Here's how it might look before and after applying 1NF:
Before Applying 1NF:
StudentI Courses
D
1 Math, Physics, Chemistry
2 History, English
3 Computer Science, Mathematics, Gym

In this table, the "Courses" column violates 1NF because it contains multiple values separated by
commas. This is not atomic, and it's challenging to work with this data efficiently.

2.3.2. Indexing
Indexing in a database is a technique used to improve the speed of data retrieval operations on
tables. It works by creating a data structure (the index) that provides a faster way to look up
records based on the values in one or more columns of a table. Here are some key points about
indexing in databases:
 Types of Indexes:

1. Single-Column Index
2. Composite Index
3. Unique Index
4. Clustered Index
5. Non-Clustered Index

 Pros of Indexing (Advantages)


1. Faster data retrieval for SELECT queries, especially when dealing with large datasets.
2. Improved performance for JOIN operations and WHERE clauses.
3. Supports enforcing constraints like uniqueness.

 Cons of Indexing (Disadvantages):


1. Takes up storage space because it duplicates some data.
2. Slows down data modification operations (INSERT, UPDATE, DELETE) due to the
overhead of maintaining indexes.
3. Poorly chosen indexes can degrade performance instead of improving it.

2.4. Design of Physical database schema

2.4.1. Description of DBMS

A Database Management System (DBMS) is software that enables users to interact with a
database, which is a structured collection of data. Here are key components and functions of a
DBMS:
Examples of popular DBMSs include Oracle, MySQL, Microsoft SQL Server, PostgreSQL, and
MongoDB (a NoSQL database). The choice of DBMS depends on the specific requirements of
the application and the type of data to be managed.
2.4.2. Preparation of DBMS Environment (MySQL)
To prepare an environment for MySQL, you'll need to install and set up the MySQL database
management system on your computer or server.
1. System Requirements: Ensure that your system meets the minimum hardware and software
requirements for MySQL. You can find these requirements on the official MySQL website or
documentation.

2. Download and Install MySQL:


- Visit the official MySQL website (https://dev.mysql.com/downloads/) to download the MySQL
Community Server edition.
- Choose the appropriate version for your operating system (e.g., Windows, macOS, Linux) and
download the installer.
- Follow the installation wizard to install MySQL on your system.

3. Configure MySQL:
- During installation, you may be prompted to set a root password for the MySQL server. Choose
a strong password and remember it.
- You can also configure MySQL to start automatically when your system boots.

4. Start and Stop MySQL Server

- After installation, you can start and stop the MySQL server using system-specific commands.
- On Windows, you can use the "MySQL" service from the Services panel.

5. Test MySQL Installation:


- Open a command prompt or terminal and run the following command to log in to the MySQL
server using the root account (replace `<password>` with the root password you set during
installation):
mysql -u root -p

- If successful, you should see the MySQL command-line interface.

6. Create Databases and Tables:

- You can use SQL commands or MySQL client tools (e.g., phpMyAdmin, MySQL Workbench)
to create databases and tables within your MySQL environment.

Learning outcome 3: Implement Database.


3.1. Introduction of SQL

SQL, which stands for Structured Query Language, is a domain-specific programming language
used for managing and manipulating relational databases. It serves as a powerful tool for
interacting with and managing data stored in a relational database management system
(RDBMS)
3.2. SQL sub-languages

3.2.1. Data Definition Language (DDL)


This sub-language within SQL is used to define and manage the structure of the database. It
includes commands like CREATE TABLE, ALTER TABLE, and DROP TABLE to create,
modify, or delete database objects like tables, indexes, and constraints.
3.2.2. Data Manipulation Language (DML)
DML is another sub-language used for manipulating data stored in the database. Common DML
commands include SELECT (for querying data), INSERT (for adding new data), UPDATE (for
modifying existing data), and DELETE (for removing data).
3.2.3. Data Control Language (DCL)
DCL deals with the permissions and security aspects of the database. It includes commands like
GRANT (to provide permissions) and REVOKE (to remove permissions).
3.2.4. Transactional Control Language (TCL)
Used for managing transactions in database .it consists of commands that allow you to control
the transactions with in database
The main TCL Commands are
1. COMMIT
2. ROLLBACK
3. SAVEPOINT
4. ROLLBACK TO SAVEPOINT
5. SET TRANSACTION

3.3. SQL Operators

Are special symbols or keywords used to perform operations on data with in SQL queries

3.3.1. Types of Operators

1. SQL Arithmetic Operators


“+” : (Addition): Adds two numeric values.
“-“: (Subtraction): Subtracts one numeric value from another.
“*” : (Multiplication): Multiplies two numeric values.
“/”: (Division): Divides one numeric value by another.
“%” : (Modulus): Returns the remainder of a division operation.

2. SQL Bitwise Operators

Bitwise OR (`|`):
- Performs a bitwise OR operation between two integers. It sets each bit in the result to 1 if at
least one of the corresponding bits in both operands is 1.
- Example: `SELECT 5 | 3;` (This returns 7 because binary 5 is 101 and binary 3 is 011, so the
OR operation results in 111).
3. Bitwise XOR (`^`):
- Performs a bitwise XOR (exclusive OR) operation between two integers. It sets each bit in
the result to 1 if the corresponding bits in the operands are different (one is 1 and the other is 0).
- Example: `SELECT 5 ^ 3;` (This returns 6 because binary 5 is 101 and binary 3 is 011, so the
XOR operation results in 110).
4. Bitwise NOT (`~`):
Performs a bitwise NOT operation on a single integer, inverting all its bits. It changes 0s to 1s
and 1s to 0s.
Example: `SELECT ~5;` (This returns -6 because binary NOT of 5 is NOT 101 which is 010,
and interpreting this as a signed integer gives -6).
3. SQL Compound Operators

Compound operators, also known as compound assignment operators, are shorthand notations in
programming languages, including SQL, that allow you to perform an operation and assign the
result to a variable in a single step. These operators combine an arithmetic or bitwise operation
with the assignment operation. In SQL, these operators work with numeric data types and are
often used in UPDATE statements to modify the values of columns.
Here are some common compound operators in SQL:
1. += (Add and Assign): Adds the right-hand value to the current value of a column and assigns
the result to the column. For example:
Example
UPDATE table_name SET column_name += 5;

2. “-= (Subtract and Assign)”: Subtracts the right-hand value from the current value of a
column and assigns the result to the column.
3. “= (Multiply and Assign)”: Multiplies the current value of a column by the right-hand value
and assigns the result to the column.
4. “/= (Divide and Assign)”: Divides the current value of a column by the right-hand value and
assigns the result to the column.
5. “%= (Modulus and Assign)”: Performs a modulus operation on the current value of a
column and the right-hand value, then assigns the result to the column.
4. SQL Logical Operators

AND: Combines multiple conditions and returns true if all conditions are true.
OR: Combines multiple conditions and returns true if at least one condition is true.
NOT: Negates a condition, returning true if the condition is false and vice versa.
5. Comparison Operators

- `=` (Equal to): Used to compare if two values are equal.


- `!=` or `<>` (Not Equal to): Checks if two values are not equal.
- `<` (Less Than): Compares if one value is less than another.
- `>` (Greater Than): Compares if one value is greater than another.
- `<=` (Less Than or Equal to): Checks if one value is less than or equal to another.
- `>=` (Greater Than or Equal to): Compares if one value is greater than or equal to another.
3.3. Application of DDL commands

3.3.1. CREATE

3.3.1.1. Database

Syntax: CREATE DATABASE DATABASE NAME;


3.3.1.2. Table
Syntax: CREATE TABLE TABLE NAME(column1 datatype………..columnN
datatype);

Example: CREATE TABLE EMPLOYEE( Employee_id INT ,first_name VARCHAR(50),


last_name VARCHAR(50), Job_title VARCHAR(100), Hired_date DATE, Salary
DECIMAL(10, 2);
3.3.1.3. Table Constraints

1. **Primary Key Constraint**: Ensures that a column or a combination of columns has


unique values in each row and is typically used to uniquely identify each row in the table.
CREATE TABLE example (
id INT PRIMARY KEY,
name VARCHAR(255)
);
2. **Unique Constraint**: Ensures that the values in a column or a combination of columns are
unique across all rows, but unlike a primary key, it doesn't have to be the identifier for the row.

CREATE TABLE example (


email VARCHAR(255) UNIQUE,
phone_number VARCHAR(15) UNIQUE
);
3. **Foreign Key Constraint**: Establishes a relationship between two tables, ensuring that
values in a column match values in another table's column. This enforces referential integrity.

CREATE TABLE orders (

order_id INT PRIMARY KEY,


customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
4. **Check Constraint**: Allows you to specify a condition that must be true for data to be
inserted or updated in a table.

CREATE TABLE products (


product_id INT PRIMARY KEY,
price DECIMAL(10, 2),
quantity INT,
CHECK (price > 0 AND quantity >= 0)
);

5. **Not Null Constraint**: Ensures that a column cannot contain NULL values.

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL
);

3.3.2. ALTER Table

The `ALTER TABLE` statement in SQL is used to modify an existing database table's structure.
It allows you to make various changes to a table, including:
1. Adding Columns: You can use `ALTER TABLE` to add new columns to the table.
ALTER TABLE table_name
ADD column_name data_type;
2. Modifying Columns: You can change the data type or constraints of an existing column.
ALTER TABLE table_name
ALTER COLUMN column_name new_data_type;
3. Dropping Columns: You can remove columns from a table.
ALTER TABLE table_name
DROP COLUMN column_name;
4. Renaming Table: You can change the name of the table itself.
ALTER TABLE old_table_name RENAME TO new_table_name;
5. Adding Constraints: You can add constraints like primary keys, foreign keys, or unique
constraints.
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type (column_name);
6. Removing Constraints: You can remove constraints from a table.
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
These are some common use cases for the `ALTER TABLE` statement, but it can be used for
various other table modifications as well. The specific syntax and options may vary depending
on the SQL database management system you are using (e.g., MySQL, PostgreSQL, SQL
Server, etc.). Always be cautious when altering tables, as it can affect the integrity and data in
your database.
3.3.3. DROP

The "DROP" statement in a database is used to delete database objects like tables, indexes, or
views. It permanently removes the specified object and all the data associated with it.
3.3.3.1. Database

Dropping database in SQL involves permanently removing the entire database, including all its
tables, data, and associated objects.
Syntax: DROP DATABASE database_name;
3.3.3.2. Table

Dropping a table in SQL Involves permanently deleting the table all its data, columns, and
associated objects
SYNTAX: DROP TABLE table_name;
3.3.4. TRUNCATE Table

3.3.5. RENAME DATABASE

SYNTAX:
ALTER DATABASE old_database_name RENAME TO new_database_name;
3.2. Application of DML commands

You might also like