Database System Complete Notes
Database System Complete Notes
CHAPTER 1
Introduction to Databases
A database is an electronically stored, systematic collection of data that can
include words, numbers, images, videos, and other types of files. Databases are
managed using specialized software called a Database Management
System (DBMS), which allows users to store, retrieve, and manipulate data
efficiently. Databases are the backbone of modern applications, supporting
businesses, organizations, and systems across industries.
Key Features of a Database
Organized Data Storage: Data is stored in structured formats, such as
tables, documents, or key-value pairs.
Efficient Access: Advanced search and query capabilities allow for quick
data retrieval.
Security and Scalability: Databases provide robust security measures and
can scale with growing data needs.
Advantages of DBMS
The advantages of the DBMS are explained below −
Redundancy problem can be solved.
In the File System, duplicate data is created in many places because all the
programs have their own files which create data redundancy resulting in
wastage of memory. In DBMS, all the files are integrated in a single database.
So there is no chance of duplicate data.
For example: A student record in a library or examination can contain duplicate
values, but when they are converted into a single database, all the duplicate
values are removed.
Has a very high security level.
Data security level is high by protecting your precious data from unauthorized
access. Only authorized users should have the grant to access the database
with the help of credentials.
Presence of Data integrity.
Data integrity makes unification of so many files into a single file. DBMS allows
data integrity which makes it easy to decrease data duplicity Data integration
and reduces redundancy as well as data inconsistency.
Support multiple users.
DBMS allows multiple users to access the same database at a time without any
conflicts.
Avoidance of inconsistency.
DBMS controls data redundancy and also controls data consistency. Data
consistency is nothing but if you want to update data in any files then all the
files should not be updated again.
In DBMS, data is stored in a single database so data becomes more consistent
in comparison to file processing systems.
Shared data
Data can be shared between authorized users of the database in DBMS. All the
users have their own right to access the database. Admin has complete access
to the database. He has a right to assign users to access the database.
Enforcement of standards
As DBMS have central control of the database. So, a DBA can ensure that all
the applications follow some standards such as format of data, document
standards etc. These standards help in data migrations or in interchanging the
data.
Any unauthorized access is restricted
Unauthorized persons are not allowed to access the database because of
security credentials.
Provide backup of data
Compiled by Sir Touqeer National Academy Abbottabad
MS computer Science
DATABASE SYSTEM NOTES DIT (PART-II)
Data loss is a big problem for all the organizations. In the file system users have
to back up the files in regular intervals which lead to waste of time and
resources.
DBMS solves this problem of taking backup automatically and recovery of the
database.
Tunability
Tuning means adjusting something to get a better performance. Same in the
case of DBMS, as it provides tunability to improve performance. DBA adjusts
databases to get effective results.
Disadvantages of DBMS
The disadvantages of DBMS are as follows:
Complexity
The provision of the functionality that is expected of a good DBMS makes the
DBMS an extremely complex piece of software. Database designers,
developers, database administrators and end-users must understand this
functionality to take full advantage of it.
Failure to understand the system can lead to bad design decisions, which leads
to a serious consequence for an organization.
Size
The functionality of DBMS makes use of a large piece of software which
occupies megabytes of disk space.
Performance
Performance may not run as fast as desired.
Higher impact of a failure
The centralization of resources increases the vulnerability of the system
because all users and applications rely on the availability of DBMS, the failure
of any component can bring operation to halt.
Cost of DBMS
4. Queries
Queries are commands used to interact with the database, allowing users to
retrieve, manipulate, or update data. For relational databases, SQL (Structured
Query Language) is commonly used. For instance, a query like SELECT * FROM
Customers WHERE Country = 'USA'; retrieves all customers from the USA. Queries
are vital for extracting actionable insights and managing data effectively.
5. Users
Users are individuals or applications that interact with the database. They can
have different levels of access based on their roles, such
as administrators, developers, or end-users. For example, a database
administrator might have full control, including the ability to create or delete
tables, while a regular user might only have permission to view specific data.
1. Hierarchical Model
The hierarchical database model organizes data into a tree-like structure,
with a single root, to which all the other data is linked.
The hierarchy starts from the Root data, and expands like a tree,
adding child nodes to the parent nodes.
In this model, a child node will only have a single parent node.
This model efficiently describes many real-world relationships like the index
of a book, etc.
IBM's Information Management System (IMS) is based on this model.
Data is organized into a tree-like structure with a one-to-many
relationship between two different types of data, for example,
one department can have many courses, many teachers, and of course
many students (like shown in the diagram below).
2. Network Model
The Network Model is an extension of the Hierarchical model.
In this model, data is organized more like a graph, and allowed to
have more than one parent node.
This was the most widely used database model before Relational Model was introduced.
The implementation of the Network model is complex, and it's very difficult to maintain it.
You may want to explore this if you are developing some social networking applications,
although the Graph Database model is new and is far better than the Network Database model.
3. Relational Model
In this model, data is organized in two-dimensional tables and the
relationship is maintained by storing a common field.
This model was introduced by E.F Codd in 1970, and since then it has been
the most widely used database model.
Compiled by Sir Touqeer National Academy Abbottabad
MS computer Science
DATABASE SYSTEM NOTES DIT (PART-II)
The basic structure of data in the relational model is tables. All the
information related to a particular type is stored in rows of that table.
Hence, tables are also known as relations in the relational model.
You can design tables, normalize them to reduce data redundancy,
and use Structured Query language or SQL to access data from the tables.
Some of the most popular databases are based on this database model. For
example, Oracle, MySQL, etc.
What is a DBMS?
A DBMS is a system that allows users to create, modify, and query databases while ensuring data
integrity, security, and efficient data access. Unlike traditional file systems, DBMS minimizes data
redundancy, prevents inconsistencies, and simplifies data management with features like concurrent
access and backup mechanisms. It organizes data into tables, views, schemas, and reports, providing a
structured approach to data management.
Example:
A university database can store and manage student information, faculty records, and administrative
data, allowing seamless retrieval, insertion, and deletion of information as required.
understand how different data structures relate to each other. Relationships are a logical connection
between different tables, established on the basis of interaction among these tables.
Non-Relational Database
A non-relational database is a type of database that does not rely on the traditional tabular structure of
rows and columns found in relational databases. Instead, it uses flexible data models such as key-value
pairs, documents, graphs, and wide-column stores.
This flexibility allows non-relational databases to manage unstructured, semi-structured, and structured
data efficiently. They were designed when data was expected to be partitioned across multiple
machines to scale, in contrast to relational databases, which assumed the data would stay on a single
machine.
DBMS RDBMS
No relationship between data. Data is stored in the form of tables which are related to each other.
DBMS RDBMS
FUNCTIONS OF A DBMS:
1. Data Definition:
Defining Database Structure:
DBMS enables users to define the structure of the database, including tables, fields, data types, and
constraints.
It allows for the creation and modification of database schemas, which are the blueprints for organizing
data.
DBMS maintains a catalog or dictionary that stores metadata (data about data), such as data types,
constraints, and access rights.
2. Data Manipulation:
Inserting, Updating, and Deleting Data: DBMS provides functions to insert new data, update
existing data, and delete data from the database.
Data Retrieval: It enables users to retrieve specific data based on queries or criteria.
Data Transformation: DBMS can handle data transformation and presentation, ensuring data is
in the correct format for users.
DBMS provides mechanisms to authenticate users and grant them appropriate access rights to the
database.
It can encrypt sensitive data and implement security measures to protect data from unauthorized
access.
DBMS provides features for backing up data and recovering it in case of system failures or data loss.
4. Data Integrity:
Data Validation:
DBMS can enforce data integrity constraints to ensure data accuracy and consistency.
Transaction Management:
It manages transactions to ensure that data changes are atomic, consistent, isolated, and durable (ACID
properties).
Concurrency Control:
DBMS manages concurrent access to the database by multiple users, preventing conflicts and ensuring
data consistency.
A relational database consists of a collection of tables each of which is assigned a unique name.
Consider a relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE, and AGE shown in
the table.
Table STUDENT
Key Terms
Attribute: Attributes are the properties that define an entity. e.g. ROLL_NO, NAME, ADDRESS.
Data: Facts, figures, statistics etc. having no particular meaning (e.g. 1, ABC, 19 etc).
Relation Schema: A relation schema defines the structure of the relation and represents the
name of the relation with its attributes. e.g. STUDENT (ROLL_NO, NAME, ADDRESS, PHONE, and
AGE) is the relation schema for STUDENT. If a schema has more than 1 relation it is called
Relational Schema.
Tuple: Each row in the relation is known as a tuple. The above relation contains 4 tuples one of
which is shown as:
Relation Instance: The set of tuples of a relation at a particular instance of time is called
a relation instance. It can change whenever there is an insertion, deletion or update in the
database.
Degree: The number of attributes in the relation is known as the degree of the relation. The
STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality. The STUDENT relation
defined above has cardinality 4.
Column: The column represents the set of values for a particular attribute. The column ROLL_NO
is extracted from the relation STUDENT.
NULL Values: The value which is not known or unavailable is called a NULL value. It is
represented by NULL. e.g. PHONE of STUDENT having ROLL_NO 4 is NULL.
Relation Key: These are basically the keys that are used to identify the rows uniquely or also help
in identifying tables. These are of the following types:
o Primary Key
o Candidate Key
o Super Key
o Foreign Key
o Alternate Key
o Composite Key
Types of Keys in Relational Model (Candidate, Super, Primary, Alternate and Foreign)
Keys are one of the basic requirements of a relational database model. It is widely used to identify the
tuples(rows) uniquely in the table. We also use keys to set up relations amongst various columns and
tables of a relational database.
We require keys in a DBMS to ensure that data is organized, accurate, and easily accessible. Keys help to
uniquely identify records in a table, which prevents duplication and ensures data integrity.
Keys also establish relationships between different tables, allowing for efficient querying and
management of data. Without keys, it would be difficult to retrieve or update specific records, and the
database could become inconsistent or unreliable.
Super Key
The set of one or more attributes (columns) that can uniquely identify a tuple (record) is known as Super
Key. For Example, STUD_NO, (STUD_NO, STUD_NAME), etc.
A super key is a group of single or multiple keys that uniquely identifies rows in a table. It
supports NULL values in rows.
A super key can contain extra attributes that aren’t necessary for uniqueness. For example, if the
“STUD_NO” column can uniquely identify a student, adding “SNAME” to it will still form a valid
super key, though it’s unnecessary.
Example:
Table STUDENT
Candidate Key
The minimal set of attributes that can uniquely identify a tuple is known as a candidate key. For Example,
STUD_NO in STUDENT relation.
A candidate key is a minimal super key, meaning it can uniquely identify a record but contains no
extra attributes.
A candidate key must contain unique values, ensuring that no two rows have the same value in
the candidate key’s columns.
A table can have multiple candidate keys but only one primary key.
Example:
Table STUDENT
The candidate key can be simple (having only one attribute) or composite as well.
Example:
Table STUDENT_COURSE
TEACHER_N
STUD_NO O COURSE_NO
1 001 C001
2 056 C005
Note: In SQL Server a unique constraint that has a nullable column, allows the value ‘ null ‘ in that
column only once . That’s why the STUD_PHONE attribute is a candidate here, but cannot be a ‘null’
value in the primary key attribute.
Primary Key
There can be more than one candidate key in relation out of which one can be chosen as the primary
key. For Example, STUD_NO, as well as STUD_PHONE, are candidate keys for relation STUDENT but
STUD_NO can be chosen as the primary key (only one out of many candidate keys).
A primary key is a unique key, meaning it can uniquely identify each record (tuple) in a table.
It must have unique values and cannot contain any duplicate values.
A primary key cannot be NULL, as it needs to provide a valid, unique identifier for every record.
A primary key does not have to consist of a single column. In some cases, a composite primary
key (made of multiple columns) can be used to uniquely identify records in a table.
Databases typically store rows ordered in memory according to primary key for fast access of
records using primary key.
Example:
STUDENT table -> Student(STUD_NO, SNAME, ADDRESS, PHONE) , STUD_NO is a primary key
Table STUDENT
Alternate Key
An alternate key is any candidate key in a table that is not chosen as the primary key. In other words, all
the keys that are not selected as the primary key are considered alternate keys.
An alternate key is also referred to as a secondary key because it can uniquely identify records in
a table, just like the primary key.
An alternate key can consist of one or more columns (fields) that can uniquely identify a record,
but it is not the primary key
Example:
Foreign Key
A foreign key is an attribute in one table that refers to the primary key in another table. The table that
contains the foreign key is called the referencing table, and the table that is referenced is called
the referenced table.
A foreign key in one table points to the primary key in another table, establishing a relationship
between them.
It helps connect two or more tables, enabling you to create relationships between them. This is
essential for maintaining data integrity and preventing data redundancy.
For example, DNO is a primary key in the DEPT table and a non-key in EMP
Example:
Table STUDENT_COURSE
TEACHER_N
STUD_NO O COURSE_NO
1 005 C001
TEACHER_N
STUD_NO O COURSE_NO
2 056 C005
It may be worth noting that, unlike the Primary Key of any given relation, Foreign Key can be NULL as
well as may contain duplicate tuples i.e. it need not follow uniqueness constraint. For Example,
STUD_NO in the STUDENT_COURSE relation is not unique. It has been repeated for the first and third
tuples. However, the STUD_NO in STUDENT relation is a primary key and it needs to be always unique,
and it cannot be null.
Composite Key
Sometimes, a table might not have a single column/attribute that uniquely identifies all the records of a
table. To uniquely identify rows of a table, a combination of two or more columns/attributes can be
used. It still can give duplicate values in rare cases. So, we need to find the optimal set of attributes that
can uniquely identify rows in a table.
Different combinations of attributes may give different accuracy in terms of identifying the rows
uniquely.
Example:
Referential integrity constraints are rules that ensure relationships between tables remain consistent.
They enforce that a foreign key in one table must either match a value in the referenced primary key of
another table or be NULL. This guarantees the logical connection between related tables in a relational
database.
Prevents Orphan Records: Avoids cases where a record in a child table references a non-existent
parent record.
Example:
Here, in below example Block_No 22 entry is not allowed because it is not present in 2nd table.
20 Chandigarh
21 Punjab
25 Delhi
Relationship in DBMS
Any association between two entity types is called a relationship. Entities take part in the relationship. It
is represented by a diamond shape.
For example, A teacher teaches students. Here, " teaches " is a relationship and this is the relationship
between a teacher’s entity and a student entity.
We have two entity types of 'Customers' (Customer_id, Name, City, Phone) and 'Account'(Account_no,
Type, Balance). We store the data of 'Customer' in one table and his accounts details in the 'Account'
table. Now, to link these two tables we need to insert the primary key 'Customer_id' of the 'Customer'
table in the 'Account' table. This key acts as a foreign key for the 'Account' table and refers to a column
with the same name in the 'Customer' table. This is how a relationship between two tables is
established. There are three types of relationships that can exist between two entities.
One-to-One Relationship
Many-to-Many Relationship
One-to-One Relationship
Such a relationship exists when each record of one table is related to only one record of the other table.
For example, If there are two entities ‘Person’ (Id, Name, Age, Address) and ‘Passport’ (Passport_id,
Passport_no). So, each person can have only one passport and each passport belongs to only one
person.
Such a relationship is not very common. However, such a relationship is used for security purposes. In
the above example, we can easily store the passport id in the ‘Person’ table only. But, we make another
table for the ‘Passport’ because Passport number may be sensitive data and it should be hidden from
certain users. So, by making a separate table we provide extra security that only certain database users
can see it.
For example, If there are two entity type ‘Customer’ and ‘Account’ then each ‘Customer’ can have more
than one ‘Account’ but each ‘Account’ is held by only one ‘Customer’. In this example, we can say that
each Customer is associated with many Accounts. So, it is a one-to-many relationship. But, if we see it
the other way i.e. many Accounts is associated with one Customer then we can say that it is a many-to-
one relationship.
Many-to-Many Relationship
Such a relationship exists when each record of the first table can be related to one or more than one
record of the second table and a single record of the second table can be related to one or more than
one record of the first table. A many-to-many relationship can be seen as a two one-to-many relationship
which is linked by a 'linking table' or 'associate table'. The linking table links two tables by having fields
which are the primary key of the other two tables. We can understand this with the following example.
Example: If there are two entity type ‘Customer’ and ‘Product’ then each customer can buy more than
one product and a product can be bought by many different customers.
Now, to understand the concept of the linking table here, we can have the ‘Order’ entity as a linking
table which links the ‘Customer’ and ‘Product’ entity. We can break this many-to-many relationship in
two one-to-many relationships. First, each ‘Customer’ can have many ‘Orders’ whereas each ‘Order’ is
related to only one ‘Customer’. Second, each ‘Order’ is related only one Product where’s there can many
orders for the same Product.
In the above concept of linking can be understood with the help of taking into consideration all the
attributes of the entities 'Customer', 'Order' and 'Product'. We can see that the primary key of both
'Customer' and 'Product' entity is included in the linking table i.e 'Order' table. These key act as foreign
keys while referring to the respective table from the 'Order' table.
A Data Model in Database Management System (DBMS) is the concept of tools that are developed to
summarize the description of the database. Data Models provide us with a transparent picture of data
which helps us in creating an actual database. It shows us from the design of the data to its proper
implementation of data.
Data Models handle Database management systems (DBMS) since they determine the structure,
storage, and manipulation of data. They act as structural blueprints, assuring that data is arranged
consistently and effectively.
Data Models
Let's see these Data models in DBMS with examples one by one,
This approach is used during the requirement-gathering phase, which is before the Database
Designers begin creating a specific database.
Entities, relationships, and even properties that database designers utilize are the focus of the
E/R model.
It is essentially a conceptual design for any database that simplifies creating a data view.
Relationship: Relationships are what establish the connections between various entities.
Data models of this kind are created with a corporate audience in mind.
The conceptual model is created without regard to software or hardware requirements, such as
DBMS vendor and technology, or data storage capacity or location.
Representing data as a user would see it in the "real world" is the main goal.
The Conceptual data models also called Domain models establish fundamental concepts and scope
that all stakeholders can use to develop a shared vocabulary.
The representational data model specifically looks into the database's design.
Tables are essentially used in the Relational Model to represent our data and the relationships
among them.
It is a theoretical idea that is put into practice using a physical data model.
One benefit of using a representational data model is that it offers a framework upon which the
physical model may be built.
In the end, every piece of data within a database is physically kept on discs and tapes or other
secondary storage devices.
Files, records, and a few more types of data structures are used to store this.
It contains all the details on the file formats, database structures, external data structures, and
how they relate to one another.
In this case, tables are essentially saved in memory for effective access.
Better work on the relational model is necessary before we can develop a good physical model.
Its Columns contain default values, given lengths, and precise datatypes.
views, authorizations, access profiles, indexes, primary and foreign keys, etc are defined in it.
In order to organize and structure data and provide database design clarity, data modelling is
essential. It acts as a common language, promoting efficient stakeholder communication. It
directs the best database architecture for effective data storage and retrieval through visual
representation.
Visualizes complex data structures, providing a clear roadmap for understanding relationships.
Acts as a universal language, fostering effective communication between business and technical
stakeholders.
Introduction of ER Model
We typically follow the below steps for designing a database for an application.
Gather the requirements (functional and data) by asking questions to the database users.
Do a logical or conceptual design of the database. This is where ER model plays a role. It is the
most used graphical representation of the conceptual design of a database.
Physical Database Design (Like indexing) and external design (like views)
The Entity Relationship Model is a model for identifying entities (like student, car or company) 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.
ER diagrams represent the E-R model in a database, making them easy to convert into relations
(tables).
ER diagrams provide the purpose of real-world modeling of objects which makes them intently
useful.
ER Model is used to model the logical view of the system from a data perspective which consists of these
symbols:
Lines: Lines represent attributes to entities and entity sets with other relationship types.
Components of ER Diagram
ER Model consists of Entities, Attributes, and Relationships among Entities in a Database System.
Components of ER Diagram
What is 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.
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:
Entity Set
We can represent the entity set in ER Diagram but can’t represent entity in ER Diagram because entity is
row and column in the relation and ER Diagram is graphical representation of data.
Types of Entity
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 can’t exist 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 type and its identifying strong entity type is called
identifying relationship and it is represented by a double diamond.
What is 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.
Attribute
Types of Attributes
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.
Key Attribute
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.
Composite Attribute
3. 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.
Multivalued Attribute
4. 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.
Derived Attribute
The Complete Entity Type Student with its Attributes can be represented as:
A Relationship Type represents the association between entity types. For example, ‘Enrolled in’ is a
relationship type that exists between entity type Student and Course. In ER diagram, the relationship
type is represented by a diamond and connecting the entities with lines.
Entity-Relationship Set
A set of relationships of the same type is known as a relationship set. The following relationship set
depicts S1 as enrolled in C2, S2 as enrolled in C1, and S3 as registered in C3.
Relationship Set
The number of different entities sets participating in a relationship set is called the degree of a
relationship set.
1. Unary Relationship: When there is only ONE entity set participating in a relation, the relationship is
called a unary relationship. For example, one person is married to only one person.
Unary Relationship
2. Binary Relationship: When there are TWO entities set participating in a relationship, the relationship
is called a binary relationship. For example, a Student is enrolled in a Course.
Binary Relationship
3. Ternary Relationship: When there are three entity sets participating in a relationship, the relationship
is called a ternary relationship.
4. N-ary Relationship: When there are n entities set participating in a relationship, the relationship is
called an n-ary relationship.
What is Cardinality?
The number of times an entity of an entity set participates in a relationship set is known as cardinality.
Cardinality can be of different types:
1. One-to-One: When each entity in each entity set can take part only once in the relationship, the
cardinality is one-to-one. Let us assume that a male can marry one female and a female can marry one
male. So the relationship will be one-to-one.
2. One-to-Many: In one-to-many mapping as well where each entity can be related to more than one
entity and the total number of tables that can be used in this is 2. Let us assume that one surgeon
department can accommodate many doctors. So, the Cardinality will be 1 to M. It means one
department has many Doctors.
3. Many-to-One: When entities in one entity set can take part only once in the relationship set and
entities in other entity sets can take part more than once in the relationship set, cardinality is many to
one. Let us assume that a student can take only one course but one course can be taken by many
students. So, the cardinality will be n to 1. It means that for one course there can be n students but for
one student, there will be only one course.
In this case, each student is taking only 1 course but 1 course has been taken by many students.
4. Many-to-Many: When entities in all entity sets can take part more than once in the relationship
cardinality is many to many. Let us assume that a student can take more than one course and one course
can be taken by many students. So, the relationship will be many to many.
In this example, student S1 is enrolled in C1 and C3 and Course C3 is enrolled by S1, S3, and S4. So it is
many-to-many relationships.
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 place them accordingly using the
Diamond, and make sure that, Relationships are not connected to each other.
There are several processes and algorithms available to convert ER Diagrams into Relational Schema.
Some of them are automated and some of them are manual. We may focus here on the mapping
diagram contents to relational basics.
Mapping Entity
Entity's attributes should become fields of tables with their respective data types.
Mapping Process
Declare primary key of higher-level table and the primary key for lower-level table.
It helps you avoid redundancy and maintain the integrity of the database. It also helps you eliminate
undesirable characteristics associated with insertion, deletion, and updating.
Database administrators are able to achieve these relationships by using primary keys, foreign keys, and
composite keys.
To get it done, a primary key in one table, for example, employee_wages is related to the value from
another table, for instance, employee_data.
N.B.: A primary key is a column that uniquely identifies the rows of data in that table. It’s a unique
identifier such as an employee ID, student ID, voter’s identification number (VIN), and so on.
A foreign key is a field that relates to the primary key in another table.
A composite key is just like a primary key, but instead of having a column, it has multiple columns.
1NF, 2NF, and 3NF are the first three types of database normalization. They stand for first normal
form, second normal form, and third normal form, respectively.
There are also 4NF (fourth normal form) and 5NF (fifth normal form). There’s even 6NF (sixth normal
form), but the commonest normal form you’ll see out there is 3NF (third normal form).
All the types of database normalization are cumulative – meaning each one builds on top of those
beneath it. So all the concepts in 1NF also carry over to 2NF, and so on.
For a table to be in the first normal form, it must meet the following criteria:
a single cell must not hold more than one value (atomicity)
each column must have only one value for each row in the table
The 1NF only eliminates repeating groups, not redundancy. That’s why there is 2NF.
has no partial dependency. That is, all non-key attributes are fully dependent on a primary key.
i.e, no non-prime attribute is dependent on any proper subset of any candidate key of the table.
Prime attribute − An attribute, which is a part of the candidate key, is known as a prime attribute.
Non-prime attribute − An attribute, which is not a part of the candidate key, is said to be a non-prime
attribute. For example, we have following table which is having employee data.
When a table is in 2NF, it eliminates repeating groups and redundancy, but it does not eliminate
transitive partial dependency.
This means a non-prime attribute (an attribute that is not part of the candidate’s key) is dependent on
another non-prime attribute. This is what the third normal form (3NF) eliminates.
be in 2NF
Database normalization is quite technical, but we will illustrate each of the normal forms with examples.
Imagine we're building a restaurant management application. That application needs to store data about
the company's employees and it starts out by creating the following table of employees:
state_cod
employee_id name job_code job e home_state
state_cod
employee_id name job_code job e home_state
All the entries are atomic and there is a composite primary key (employee_id, job_code) so the table is
in the first normal form (1NF).
But even if you only know someone's employee_id, then you can determine their name, home_state,
and state_code (because they should be the same person). This means name, home_state,
and state_code are dependent on employee_id (a part of primary composite key). So, the table is not
in 2NF. We should separate them to a different table to make it 2NF.
employee_roles Table
employee_id job_code
E001 J01
E001 J02
E002 J02
E002 J03
E003 J01
employees Table
employee_i
d name state_code home_state
employee_i
d name state_code home_state
jobs table
job_code job
J01 Chef
J02 Waiter
J03 Bartender
home_state is now dependent on state_code. So, if you know the state_code, then you can find
the home_state value.
To take this a step further, we should separate them again to a different table to make it 3NF.
employee_roles Table
employee_id job_code
E001 J01
E001 J02
E002 J02
E002 J03
E003 J01
employees Table
employee_i
d name state_code
E001 Alice 26
employee_i
d name state_code
E002 Bob 56
E003 Alice 56
jobs Table
job_code job
J01 Chef
J02 Waiter
J03 Bartender
states Table
state_cod
e home_state
26 Michigan
56 Wyoming
Chapter-4
What is MySQL?
MySQL is open-source
MySQL is free
MySQL is cross-platform
Huge websites like Facebook, Twitter, Airbnb, [Link], Uber, GitHub, YouTube, etc.
To build a web site that shows data from a database, you will need:
What is SQL?
SQL stands for Structured Query Language, designed specifically for interacting with relational databases.
SQL is a language for storing, manipulating, and retrieving data in relational database management
systems.
You can use the SQL language to modify and create tables in the database, insert new data, modify
existing data, delete data from the tables, and query those tables for specific information.
What is MySQL?
You use it to store data in tables, and the rows of those tables can relate to each other by common
information in the columns.
The basic idea is that you have one or more "tables" (or "databases") and a set of rows (records) and
columns (fields).
Other elements, like keys and indexes, help you define them further.
It is available for Linux, Microsoft Windows, Mac OS X, and Solaris and comes with many web hosting
packages. You can download MySQL Server software, pronounced “my sequel,” from the official website.
MySQL is more secure as it consists of a solid data security layer to protect sensitive data from
intruders and passwords in MySQL are encrypted.
MySQL is available for free to download and use from the official site of MySQL.
MySQL is compatible with most operating systems, including Windows, Linux, NetWare, Novell,
Solaris, and other variations of UNIX.
MySQL provides the facility to run the clients and the server on the same computer or different
computers, via the internet or local network.
MySQL has a unique storage engine architecture which makes it faster, cheaper, and more
reliable.
MySQL is simple and easy to use. You can build and interact with MySQL with only a basic
knowledge of MySQL and a few simple SQL statements.
MySQL has a client-server architecture. There can be any number of clients or application
programs that communicate with the database server (MySQL) to query data, save changes, etc.
MySQL is scalable and capable of handling more than 50 million rows. This is enough to handle
almost any amount of data. Although the default file size limit is 4GB it can be increased to 8TB.
Disadvantages of MySQL:
MySQL is not very efficient in handling very large databases.
MySQL doesn’t have as good a developing and debugging tool as compared to paid databases.
MySQL versions less than 5.0 do not support COMMIT, stored procedure, and ROLE.
MySQL Workbench possesses tools that allow database administrators to virtually create
physical database design models that can be easily transitioned into MySQL databases using
forward engineering.
MySQL Workbench adheres to all objects such as tables, views, stored procedures, triggers, etc.
MySQL Workbench also creates models from a target database or even imported SQL files.
The Visual SQL editor gives developers the access to build, edit, and run queries against MySQL
server databases. It has utilities for viewing data and exporting it.
MySQL Workbench has auto-complete and color highlighters that aid in the writing and
debugging of SQL statements, easily.
Multiple queries can be run at a time, and the result is automatically displayed.
It also saves the queries in the history panel for previewing and running it later on.
You can view the account information of all users on the MySQL server
You can modify global and database permissions on the MySQL server
You can audit to see who did what and when on the server
Moving on, you will look at how to install MySQL Workbench on Windows. The installation process is
similar to other operating systems.
1. Open the MySQL website on a browser. Click on the following link: MySQL Downloads.
6. It will ask for permission; when it does, click Yes. The installer will then open. Now, it will ask to
choose the setup type, here, select Custom.
7. Click on Next. With this, you will be able to install MySQL server, MySQL Workbench, and MySQL
shell.
8. Open MySQL Servers, select the server you want to install, and move it to the Products/Features
to be installed window section. Now, expand Applications, choose MySQL Workbench and
MySQL shell. Move both of them to ‘Products/Features to be installed’.
9. Click on the Next button. Now, click on the Execute button to download and install the MySQL
server, MySQL Workbench, and the MySQL shell.
10. Once the product is ready to configure, click on Next. Under Type and Networking, go with the
default settings and select Next.
13. Go for the default windows service settings and under apply configuration, click on execute.
Once the configuration is complete, click on finish.
14. Complete the installation. This will now launch the MySQL Workbench and the MySQL Shell.
Once MySQL Workbench is installed, select the Local instance and enter the password.
Now, you can use the MySQL query tab to write your SQL queries.
Generally, MySQL Command Line Client is installed together with the MySQL Server, and you don’t need
to download and install the MySQL client separately. To check whether you have the client program on
your machine, go to search, switch to the Apps tab, and type “MySQL”
So, how to start MySQL Command Line Client? To access MySQL Server from the command-line client,
open the program and enter the password. After that, you will be able to use the client.
You can also access MySQL Command Line Client from Command Prompt. For this:
2. Navigate to the bin folder. For example: cd C:\Program Files\MySQL\MySQL Server 9.0\bin
Introduction to SQL
What is SQL?
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
DDL stands for Data Definition Language and refers to SQL commands used to create, modify, and delete
database structures such as tables, indexes, and views. DML stands for Data Manipulation Language and
refers to SQL commands used to insert, update, and delete data within a database. Now, let’s learn
about the DDL and DML commands in depth.
DDL (Data Definition Language) is a type of SQL command used to define data structures and modify
data. It creates, alters, and deletes database objects such as tables, views, indexes, and users.
1. CREATE: It is used to create objects in the database, such as tables, views, stored procedures,
and more.
3. DROP: It is used to delete an entire object or part of an object from the database.
4. TRUNCATE: Used to delete all records from a table but does not delete the table structure.
EmployeeID INT,
FirstName VARCHAR(255),
LastName VARCHAR(255),
Department VARCHAR(255)
);
This code creates a new employee table containing four columns: EmployeeID, FirstName, LastName,
and Department. It then adds an additional column, Salary, to the table. Finally, it drops the Employees
table from the database.
DML (Data Manipulation Language) is a type of SQL command used to manipulate data in a database. It
inserts, updates, and deletes data from a database table. Examples of DML statements include INSERT,
UPDATE, and DELETE.
4. MERGE: Used to combine data from two or more tables into one.
UPDATE Employees
WHERE EmployeeID = 1;
WHERE EmployeeID = 1;
This code inserts a new row into the Employees table with the values of 1, 'John', 'Smith', and 'IT' for the
respective columns. It then updates the Salary column for the row with an EmployeeID of 1 to 50000. It
then selects all of the rows from the Employees table and finally deletes the row with an EmployeeID of
1.
Explore the DDL vs DML commands in SQL in the below table. Understand how DDL commands shape
database structures, while DML commands manipulate data within the database.
DDL DML
Examples of DDL statements include CREATE, ALTER, Examples of DML statements include SELECT,
and DROP. INSERT, UPDATE, and DELETE.
Changes made using DDL affect the structure of the Changes made using DML affect the data stored
database. in the database.
DDL statements are not transactional, meaning they DML statements are transactional, meaning they
cannot be rolled back. can be rolled back if necessary.
DDL statements are usually executed by a database DML statements are executed by application
administrator. developers or end-users.
DDL statements are typically used during the design DML statements are used during normal
and setup phase of a database. operation of a database.
Examples of DDL statements: CREATE TABLE, DROP Examples of DML statements: SELECT, INSERT,
TABLE, ALTER TABLE, CREATE INDEX, etc. UPDATE, DELETE, etc.
sql
Copy
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Examples:
sql
Copy
-- Insert single record
INSERT INTO students (first_name, last_name, date_of_birth, gender, email, department)
VALUES ('Alice', 'Johnson', '2001-03-15', 'Female', 'alice.j@[Link]', 'Computer Science');
Syntax:
sql
Copy
DELETE FROM table_name
WHERE condition;
Examples:
sql
Copy
-- Delete specific record
DELETE FROM students
WHERE student_id = 10;
sql
Copy
CREATE INDEX idx_student_name ON students(last_name, first_name);
2. ALTER Command
Add Column
Syntax:
sql
ALTER TABLE table_name
ADD COLUMN column_name datatype constraints;
Example:
sql
Copy
ALTER TABLE students
ADD COLUMN phone VARCHAR(15) AFTER email;
Modify Column
Syntax:
sql
Copy
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype new_constraints;
Example:
sql
Copy
ALTER TABLE students
MODIFY COLUMN phone VARCHAR(20) NOT NULL;
Rename Column
Syntax:
sql
Copy
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
Example:
sql
Copy
ALTER TABLE students
RENAME COLUMN gpa TO grade_point_average;
Drop Column
Syntax:
sql
Copy
ALTER TABLE table_name
DROP COLUMN column_name;
Example:
sql
Copy
ALTER TABLE students
DROP COLUMN phone;
Add Constraint
Syntax:
sql
Copy
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type (column_name);
Example:
sql
Copy
ALTER TABLE students
ADD CONSTRAINT chk_gpa CHECK (gpa >= 0 AND gpa <= 4);
3. DROP Command
Drop Table
Syntax:
sql
Copy
DROP TABLE [IF EXISTS] table_name;
Example:
sql
Copy
DROP TABLE IF EXISTS temp_students;
Drop Database
Syntax:
sql
Copy
DROP DATABASE [IF EXISTS] database_name;
Example:
sql
Copy
DROP DATABASE IF EXISTS old_student_db;
Drop Index
Syntax:
sql
Copy
ALTER TABLE table_name
DROP INDEX index_name;
Example:
sql
Copy
ALTER TABLE students
DROP INDEX idx_student_name;
4. TRUNCATE Command
Syntax:
sql
Copy
TRUNCATE [TABLE] table_name;
Example:
sql
Copy
TRUNCATE TABLE audit_log;
5. RENAME Command
Rename Table
Syntax:
sql
Copy
RENAME TABLE old_name TO new_name;
Example:
sql
Copy
RENAME TABLE students TO university_students;
Advanced DDL Examples
Create Table with Foreign Key
sql
Copy
CREATE TABLE student_courses (
enrollment_id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT NOT NULL,
course_id INT NOT NULL,
enrollment_date DATE DEFAULT CURRENT_DATE,
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
Create Table with Composite Primary Key
sql
Copy
CREATE TABLE course_prerequisites (
course_id INT,
prerequisite_id INT,
PRIMARY KEY (course_id, prerequisite_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id),
FOREIGN KEY (prerequisite_id) REFERENCES courses(course_id)
);
Create View
sql
Copy
sql
Copy
email VARCHAR(100) -- Student email addresses
Text Types
TEXT: Variable-length (up to 65KB)
sql
Copy
address TEXT -- For longer student addresses
LONGTEXT: Up to 4GB of text
sql
Copy
thesis LONGTEXT -- For storing student papers
3. Date and Time Types
DATE: Date only (YYYY-MM-DD)
sql
Copy
birth_date DATE -- Student date of birth
TIME: Time only (HH:MM:SS)
sql
Copy
class_time TIME -- For class schedules
DATETIME: Date and time (YYYY-MM-DD HH:MM:SS)
sql
Copy
enrollment_datetime DATETIME -- When student enrolled
TIMESTAMP: Automatic timestamp (similar to DATETIME but with timezone support)
sql
Copy
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
YEAR: Year value (1901-2155)
sql
Copy
graduation_year YEAR -- Expected graduation year
4. Specialized Types
Boolean
BOOLEAN/BOOL: Synonym for TINYINT(1) (0 = false, 1 = true)
sql
Copy
is_active BOOLEAN DEFAULT TRUE -- Student status
Enumeration
ENUM: String object with one value from a list
sql
Copy
year_level ENUM('Freshman','Sophomore','Junior','Senior') -- Student year
Set
SET: String object with zero or more values from a list
sql
Copy
extracurriculars SET('Sports','Music','Debate','Theater') -- Student activities
Binary Data
BLOB: Binary large object (up to 65KB)
sql
Copy
student_photo BLOB -- For storing student photos
Practical Example for Student Management System
sql
Copy
CREATE TABLE students (
student_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
date_of_birth DATE NOT NULL,
gender ENUM('Male','Female','Other') NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
phone VARCHAR(15),
address TEXT,
gpa DECIMAL(3,2) CHECK (gpa BETWEEN 0.00 AND 4.00),
enrollment_date DATETIME DEFAULT CURRENT_TIMESTAMP,
graduation_year YEAR,
is_active BOOLEAN DEFAULT TRUE,
student_type ENUM('Undergraduate','Graduate','Exchange'),
courses_taken SET('Math','Science','History','Arts')
);
Examples:
1. Grant SELECT access on a table:
sql
GRANT SELECT ON students TO 'user'@'localhost';
2. Grant INSERT and UPDATE on a table:
sql
GRANT INSERT, UPDATE ON students TO 'teacher'@'%';
3. Grant ALL PRIVILEGES on a database:
sql
GRANT ALL PRIVILEGES ON school_db.* TO 'admin'@'localhost';
4. Grant privileges with GRANT OPTION (allows user to grant permissions to others):
sql
GRANT SELECT ON students TO 'manager'@'%' WITH GRANT OPTION;
2. REVOKE Command
The REVOKE command removes previously granted privileges from a user or role.
Syntax:
sql
REVOKE privilege_type ON object_name
FROM user_or_role;
Examples:
1. Revoke SELECT access:
sql
REVOKE SELECT ON students FROM 'user1'@'localhost';
2. Revoke multiple privileges:
sql
REVOKE INSERT, UPDATE ON students FROM 'teacher'@'%';
3. Revoke ALL PRIVILEGES:
sql
REVOKE ALL PRIVILEGES ON school_db.* FROM 'admin'@'localhost';
4. Revoke GRANT OPTION (without removing other privileges):
sql
REVOKE GRANT OPTION ON students FROM 'manager'@'%';
Exampl
GRANT SELECT ON table TO user; REVOKE SELECT ON table FROM user;
e
Examples:
1. Grant all privileges to admin user:
sql
GRANT ALL PRIVILEGES ON school_db.*
TO 'school_admin'@'localhost' IDENTIFIED BY 'Admin@123';
2. Grant SELECT only to teacher:
sql
GRANT SELECT ON school_db.students
TO 'math_teacher'@'%' IDENTIFIED BY 'Teacher@456';
3. Grant specific privileges to staff:
sql
GRANT SELECT, INSERT, UPDATE ON school_db.students
TO 'office_staff'@'192.168.1.%' IDENTIFIED BY 'Staff@789';
4. Grant column-level privileges:
sql
GRANT SELECT (student_id, first_name, last_name), UPDATE (email)
ON school_db.students TO 'assistant'@'localhost';
5. Grant ability to create temporary tables:
sql
GRANT CREATE TEMPORARY TABLES ON school_db.*
TO 'report_user'@'localhost';
Here are the commands for showing, dropping, truncating, altering, and recreating the students table in
MySQL:
1. SHOW TABLE Command
Show all tables in the database:
sql
SHOW TABLES;
Show the structure of the students table:
sql
DESCRIBE students;
-- OR
SHOW COLUMNS FROM students;
-- OR (for more detailed info)
SHOW CREATE TABLE students;
2. DROP TABLE Command
Drop the students table completely:
sql
DROP TABLE IF EXISTS students;
3. TRUNCATE TABLE Command
Delete all data but keep the table structure:
sql
TRUNCATE TABLE students;
4. ALTER TABLE Commands
Add a new column:
sql
ALTER TABLE students
ADD COLUMN phone_number VARCHAR(15) AFTER email;
Modify a column:
sql
ALTER TABLE students
MODIFY COLUMN department VARCHAR(100);
Rename a column:
sql
ALTER TABLE students
RENAME COLUMN gpa TO grade_point_average;
Drop a column:
sql
ALTER TABLE students
DROP COLUMN is_active;
Add a constraint:
sql
ALTER TABLE students
ADD CONSTRAINT chk_email CHECK (email LIKE '%@%.%');
5. CREATE TABLE Statement (from previous example)
sql
Syntax:
sql
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Examples:
1. Basic equality check:
sql
SELECT * FROM students
WHERE department = 'Computer Science';
2. Numeric comparison:
sql
SELECT first_name, last_name, gpa
FROM students
WHERE gpa > 3.5;
3. Date comparison:
sql
SELECT * FROM students
WHERE enrollment_date >= '2023-01-01';
4. Multiple conditions with AND:
sql
SELECT * FROM students
WHERE department = 'Mathematics' AND gpa >= 3.0;
5. Pattern matching with LIKE:
sql
SELECT * FROM students
WHERE last_name LIKE 'Sm%'; -- Starts with "Sm"
6. List of values with IN:
sql
SELECT * FROM students
WHERE department IN ('Computer Science', 'Physics', 'Mathematics');
7. NULL value check:
sql
SELECT * FROM students
WHERE email IS NULL;
NOT WHERE (Excluding Records)
There are two ways to express "NOT WHERE" in MySQL:
Option 1: Using NOT with WHERE
Syntax:
sql
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Examples:
1. Not equal:
sql
SELECT * FROM students
WHERE NOT department = 'Art History';
-- Equivalent to: WHERE department != 'Art History'
2. Not like:
sql
SELECT * FROM students
WHERE NOT email LIKE '%@[Link]';
3. Not in:
sql
SELECT * FROM students
WHERE NOT department IN ('Art History', 'Drama');
4. Not null:
sql
SELECT * FROM students
WHERE NOT email IS NULL;
-- Equivalent to: WHERE email IS NOT NULL
Option 2: Using <> or != operators
Examples:
1. Not equal:
sql
SELECT * FROM students
WHERE department <> 'Art History';
2. Not between:
sql
SELECT * FROM students
WHERE gpa NOT BETWEEN 2.0 AND 3.0;
Combining WHERE and NOT
Examples:
1. Students in specific departments with low GPA:
sql
SELECT * FROM students
WHERE department IN ('Computer Science', 'Engineering')
AND NOT gpa > 2.5;
2. Active students not in certain departments:
sql
SELECT * FROM students
WHERE is_active = TRUE
AND NOT department IN ('Graduated', 'Suspended');
3. Students enrolled recently but not with specific email domains:
sql
SELECT * FROM students
WHERE enrollment_date > '2023-09-01'
-- OR operator
SELECT * FROM students
WHERE department = 'Mathematics' OR department = 'Physics';
-- NOT operator
SELECT * FROM students
WHERE NOT is_active = FALSE;
Pattern Matching:
sql
-- Students with last names starting with 'Sm'
SELECT * FROM students WHERE last_name LIKE 'Sm%';
sql
-- Students with GPA between 3.0 and 3.5
SELECT * FROM students WHERE gpa BETWEEN 3.0 AND 3.5;
Table Manipulation:
1. Show table
2. Create table statement
3. Drop table statement
Here's a complete set of commands for a student table with 5 basic attributes and 5 records, along with
all the requested operations:
sql
age INT,
email VARCHAR(100)
);
sql
VALUES
sql
DESCRIBE ditpart2;
sql
sql
sql
sql
sql
sql
sql
-- Rename column
-- Modify column
sql
sql
sql
sql
INSERT INTO temp_students SELECT * FROM ditpart2 WHERE age > 20;
sql
sql
sql
3. You can then run any of the other commands in any order (though some like DROP will remove
the table)
The table has 5 basic attributes of students (student_id, first_name, last_name, age, email) and contains
5 records as specified.
| Name | Salary |
+----------------+----------+
| John Doe | 50000.00 |
| Jane Smith | 65000.00 |
| Robert Johnson | 80000.00 |
| Emily Davis | 45000.00 |
| Michael Wilson | 70000.00 |
+----------------+----------+
+------+
| Age |
+------+
| 28 |
| 32 |
| 45 |
| 22 |
| 35 |
+------+
5. WHERE Clause
Definition: Filters records based on a condition.
Syntax:
sql
SELECT * FROM table_name WHERE condition;
Command:
sql
SELECT * FROM customer WHERE Salary > 60000;
Output:
+------------+----------------+------+----------------------+----------+
| CustomerID | Name | Age | Address | Salary |
+------------+----------------+------+----------------------+----------+
|2 | Jane Smith | 32 | 456 Park Ave, Chicago| 65000.00 |
|3 | Robert Johnson | 45 | 789 Elm St, Boston | 80000.00 |
|5 | Michael Wilson | 35 | 654 Pine St, Seattle | 70000.00 |
+------------+----------------+------+----------------------+----------+
7. ORDER BY Clause
Definition: Sorts results in ascending (default) or descending order.
Syntax:
sql
SELECT * FROM table_name ORDER BY column_name;
Command:
sql
SELECT * FROM customer ORDER BY Salary;
Output:
+------------+----------------+------+-----------------------+----------+
| CustomerID | Name | Age | Address | Salary |
+------------+----------------+------+-----------------------+----------+
|4 | Emily Davis | 22 | 321 Oak St, Los Angeles| 45000.00 |
|1 | John Doe | 28 | 123 Main St, New York | 50000.00 |
|2 | Jane Smith | 32 | 456 Park Ave, Chicago | 65000.00 |
|5 | Michael Wilson | 35 | 654 Pine St, Seattle | 70000.00 |
|3 | Robert Johnson | 45 | 789 Elm St, Boston | 80000.00 |
+------------+----------------+------+-----------------------+----------+
8. ORDER BY DESC
Definition: Sorts results in descending order.
Syntax:
sql
SELECT * FROM table_name ORDER BY column_name DESC;
Command:
sql
9. GROUP BY Clause
Definition: Groups rows with the same values into summary rows.
Syntax:
sql
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
Command:
sql
SELECT Age, COUNT(*) AS Count FROM customer GROUP BY Age;
Output:
+------+-------+
| Age | Count |
+------+-------+
| 22 | 1 |
| 28 | 1 |
| 32 | 1 |
| 35 | 1 |
| 45 | 1 |
+------+-------+
| 28 | 1 |
| 32 | 1 |
| 35 | 1 |
| 45 | 1 |
+------+-------+
('John Smith', 28, '[Link]@[Link]', '123 Main St, New York', 55000.00, '555-
0101'),
('Sarah Johnson', 35, 'sarah.j@[Link]', '456 Oak Ave, Boston', 72000.00, '555-0102'),
('Michael Brown', 42, 'michael.b@[Link]', DEFAULT, 85000.00, '555-0103'),
('Emily Davis', 31, 'emily.d@[Link]', '789 Pine Rd, Chicago', 62000.00, '555-0104'),
('Robert Wilson', 45, 'robert.w@[Link]', '321 Elm St, Los Angeles', 90000.00, '555-
0105'),
('Jennifer Lee', 29, 'jennifer.l@[Link]', '654 Maple Dr, Miami', 58000.00, '555-0106'),
('David Miller', 38, 'david.m@[Link]', '987 Cedar Ln, Dallas', 78000.00, '555-0107'),
('Lisa Taylor', 33, 'lisa.t@[Link]', DEFAULT, 67000.00, '555-0108'),
('James Anderson', 40, 'james.a@[Link]', '135 Birch Blvd, Seattle', 82000.00, '555-
0109'),
('Jessica Martinez', 27, 'jessica.m@[Link]', '246 Willow Way, Atlanta', 59000.00, '555-
0110');
Syntax:
sql
column_name data_type NOT NULL
Test:
sql
-- This will fail:
INSERT INTO customers (age, email, salary) VALUES (30, 'test@[Link]', 50000);
-- Error: Field 'name' doesn't have a default value
Syntax:
sql
column_name data_type UNIQUE
Test:
sql
-- This will fail:
INSERT INTO customers (name, age, email, salary)
VALUES ('Duplicate Email', 30, '[Link]@[Link]', 50000);
-- Error: Duplicate entry '[Link]@[Link]' for key '[Link]'
Syntax:
sql
column_name data_type PRIMARY KEY
Test:
sql
-- This will fail:
INSERT INTO customers (customer_id, name, age, email, salary)
VALUES (1, 'Duplicate ID', 30, 'new@[Link]', 50000);
-- Error: Duplicate entry '1' for key '[Link]'
Syntax:
sql
CONSTRAINT constraint_name FOREIGN KEY (column)
REFERENCES parent_table(parent_column)
Test:
sql
-- This works (customer_id 1 exists):
INSERT INTO customer_orders (customer_id, amount) VALUES (1, 150.00);
-- This fails:
INSERT INTO customer_orders (customer_id, amount) VALUES (999, 200.00);
-- Error: Cannot add or update a child row: a foreign key constraint fails
v. CHECK Constraint
Syntax:
sql
column_name data_type CHECK (condition)
Test:
sql
-- This will fail (age < 18):
INSERT INTO customers (name, age, email, salary)
VALUES ('Young Customer', 17, 'young@[Link]', 50000);
Syntax:
sql
column_name data_type DEFAULT default_value
Test:
sql
-- Insert without address:
INSERT INTO customers (name, age, email, salary)
VALUES ('Default Address', 30, 'default@[Link]', 50000);
-- Verify:
SELECT address FROM customers WHERE email = 'default@[Link]';
-- Returns: 'Address not provided'
Syntax:
sql
CREATE INDEX index_name ON table_name (column_name)
Test:
sql
-- Check existing indexes:
SHOW INDEX FROM customers;
First, let's create a product table with 3 attributes and insert 5 sample records:
MySQL Functions with Product Table Examples
-- Create database if not exists
CREATE DATABASE IF NOT EXISTS product_db;
USE product_db;
-- Create products table
CREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
unit VARCHAR(20) NOT NULL,
price DECIMAL(10,2) NOT NULL
);
| total_products|
+---------------+
|5 |
+---------------+
iii. CONCAT() Function
Definition: Combines two or more strings.
Syntax: SELECT CONCAT(string1, string2) FROM table_name;
Example:
sql
SELECT CONCAT(product_id, ' - ', unit) AS product_info FROM products;
Output:
+--------------+
| product_info |
+--------------+
| 1 - LITER |
| 2 - KG |
| 3 - GALLON |
| 4 - POUND |
| 5 - OUNCE |
+--------------+
iv. LOWER() Function
Definition: Converts a string to lowercase.
Syntax: SELECT LOWER(column_name) FROM table_name;
Example:
sql
SELECT LOWER(unit) AS lowercase_unit FROM products;
Output:
+---------------+
| lowercase_unit|
+---------------+
| liter |
| kg |
| gallon |
| pound |
| ounce |
+---------------+
v. LENGTH() Function
Definition: Returns the length of a string in bytes.
Syntax: SELECT LENGTH(column_name) FROM table_name;
Example:
sql
+--------------+
xi. REPEAT() Function
Definition: Repeats a string a specified number of times.
Syntax: SELECT REPEAT(string, count) FROM table_name;
Example:
sql
SELECT product_id, REPEAT('*', product_id) AS stars FROM products;
Output:
+------------+-------+
| product_id | stars |
+------------+-------+
|1 |* |
|2 | ** |
|3 | *** |
|4 | **** |
|5 | ***** |
+------------+-------+
xii. STRCMP() Function
Definition: Compares two strings (returns 0 if equal, -1 if first < second, 1 if first > second).
Syntax: SELECT STRCMP(string1, string2);
Example:
sql
SELECT unit, STRCMP(unit, 'KG') AS comparison_result FROM products;
Output:
+--------+-------------------+
| unit | comparison_result |
+--------+-------------------+
| LITER | 1 |
| KG | 0 |
| GALLON | 1 |
| POUND | 1 |
| OUNCE | 1 |
+--------+-------------------+
xiii. SUBSTR() Function
Definition: Extracts a substring from a string.
Syntax: SELECT SUBSTR(string, start, length) FROM table_name;
Example:
sql
SELECT unit, SUBSTR(unit, 2, 3) AS substring_unit FROM products;
Output:
+--------+---------------+
| unit | substring_unit|
+--------+---------------+
| LITER | ITE |
| KG | G |
| GALLON | AL |
| POUND | OUN |
| OUNCE | UNC |
+--------+---------------+
xiv. SUM() Function
Definition: Returns the sum of values in a numeric column.
Syntax: SELECT SUM(column_name) FROM table_name;
Example:
sql
SELECT SUM(price) AS total_value FROM products;
Output:
+-------------+
| total_value |
+-------------+
| 134.93 |
+-------------+
xv. UPPER() Function
Definition: Converts a string to uppercase.
Syntax: SELECT UPPER(column_name) FROM table_name;
Example:
sql
SELECT UPPER(unit) AS uppercase_unit FROM products;
Output:
+---------------+
| uppercase_unit|
+---------------+
| LITER |
| KG |
| GALLON |
| POUND |
| OUNCE |
+---------------+
These examples demonstrate all the requested MySQL functions using the product table, with
syntax that works in MySQL 8.0 command line. Each function is applied to the table data with
clear output examples.
Operators are symbols or keywords used to perform operations on data in SQL queries, such as
arithmetic calculations, comparisons, and logical conditions.
1. Arithmetic Operators
% or MOD( Modulus
SELECT a % b SELECT 10 % 3; 1
) (remainder)
sql
Output:
1 25.50 28.050
2 42.75 47.025
2. Comparison Operators
Less than or equal WHERE a SELECT * FROM products Returns rows with
<=
to <= b WHERE price <= 30; price ≤ 30
Example:
sql
Output:
2 KG 42.75
3. Logical Operators
SELECT * FROM
Returns rows
NOT Negates a condition WHERE NOT a products WHERE NOT
where price ≤ 30
price > 30;
Example:
sql
SELECT * FROM products WHERE price BETWEEN 15 AND 40 AND NOT unit = 'KG';
Output:
product_i
unit price
d
1 LITER 25.50
3 GALLON 18.99
4 POUND 35.20
Example:
sql
Output:
product_i
unit price
d
1 LITER 25.50
3 GALLON 18.99
4 POUND 35.20
5 OUNCE 12.49
Compariso
=, !=, >, <, >=, <= Comparing values
n
These operators are fundamental for querying and filtering data in MySQL. 🚀
FROM employees
WHERE salary > 60000;
Query the View:
sql
SELECT * FROM high_salary_employees;
Output:
+-------------+------------+--------+
| emp_name | department | salary |
+-------------+------------+--------+
| Jane Smith | IT | 75000 |
| Robert Brown| Finance | 60000 |
| Emily Davis | IT | 80000 |
+-------------+------------+--------+
Summary
Feature Description
sql
SELECT * FROM active_employees;
1. Enhanced Security
Column-Level & Row-Level Data Protection
Views restrict access to sensitive columns (e.g., hiding salary from non-HR users).
Filter rows based on user roles (e.g., a manager sees only their team's data).
2. Simplified Access Control
Role-Based Permissions
Grant permissions on views instead of base tables to limit exposure.
Avoid giving direct table access to users.
3. Data Consistency
Single Source of Truth
Views standardize how data is presented across users/departments.
Ensure all users see the same calculated metrics (e.g., monthly reports).
4. Performance Optimization
Pre-Computed Complex Queries
Store joins, aggregations, or filtered data as views to reduce repetitive processing.
Improve query performance for frequently accessed data.
5. Logical Data Independence
Shield Users from Schema Changes
Modify underlying tables without breaking applications that use views.
Example: Rename a column in the table but keep the view’s interface unchanged.
6. Simplified User Experience
Abstract Complexity
Hide complex joins or subqueries behind simple views.
Let users query customer_orders instead of writing 5-table joins.
Conclusion
Views are essential in multiuser databases to:
✅ Secure data (limit exposure)
✅ Simplify permissions (role-based access)
✅ Standardize reporting (consistent metrics)
✅ Improve performance (reuse complex queries)
A Join in MySQL combines rows from two or more tables based on a related column, allowing you to
query data from multiple tables in a single operation.
Avoid data redundancy (normalized databases use joins instead of duplicate data)
Improve query efficiency (fetch related data in one query instead of multiple)
2. LEFT JOIN (LEFT OUTER JOIN) → Returns all rows from the left table + matched rows from the
right table.
3. RIGHT JOIN (RIGHT OUTER JOIN) → Returns all rows from the right table + matched rows from
the left table.
4. CROSS JOIN → Returns the Cartesian product (all possible row combinations).
An INNER JOIN returns only the rows where there is a match in both tables based on the
specified condition. It filters out non-matching rows from both tables.
Supplier Table
sql
);
Order Table
sql
supplier_id INT,
order_date DATE,
);
(101, 1, '2023-01-15'),
(102, 2, '2023-02-20'),
(103, 1, '2023-03-10'),
(104, 3, '2023-04-05');
sql
FROM table1
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
sql
FROM supplier s
Output
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
6. Key Takeaways
1. INNER JOIN only returns rows with matching values in both tables.
Definition
A LEFT JOIN returns all rows from the left table (first table) and matched rows from the right table. If no
match exists, NULL values are returned for right table columns.
Visual Illustration
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
sql
FROM supplier s
Output
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
Definition
A RIGHT JOIN returns all rows from the right table and matched rows from the left table. If no match
exists, NULL values are returned for left table columns.
Visual Illustration
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+ +----------+-------------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
sql
FROM supplier s
Output
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
3. CROSS JOIN
Definition
A CROSS JOIN returns the Cartesian product of both tables (all possible combinations of rows). No join
condition is needed.
Visual Illustration
+-------------+------------+ +----------+------------+
+-------------+------------+ +----------+------------+
+-------------+------------+ +----------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
+-------------+------------+----------+------------+
sql
FROM supplier s
Output
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
+-------------+--------------+----------+------------+
Key Takeaways