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

Unit 1 DBMS

Notes of dbms unit 1 for ipu students

Uploaded by

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

Unit 1 DBMS

Notes of dbms unit 1 for ipu students

Uploaded by

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

Basic concepts: database & database users

A database is an organized collection of structured information, or data, typically stored electronically in a


computer system. A database is usually controlled by a database management system (DBMS).
A database is an organized collection of structured information, or data, typically stored electronically in a
computer system. A database is usually controlled by a database management system (DBMS). Together, the
data and the DBMS, along with the applications that are associated with them, are referred to as a database
system, often shortened to just database.

Data within the most common types of databases in operation today is typically modeled in rows and columns in
a series of tables to make processing and data querying efficient. The data can then be easily accessed, managed,
modified, updated, controlled, and organized. Most databases use structured query language (SQL) for writing
and querying data.

Database Users
i. End Users: End users are the people whose jobs require access to a database for querying, updating and
generating reports.
ii. Application user:The application user is someone who accesses an existing application program to perform
daily tasks.
iii. Sophisticated user:Sophisticated users are those who have their own way of accessing the database. This
means they do not use the application program provided in the system. Instead, they might define their own
application or describe their need directly by using query languages. These specialized users maintain their
personal databases by using ready-made program packages that provide easy-to-use menu driven commands,
such as MS Access
iv. Application Programmers:These users implement specific application programs to access the stored data.
They must be familiar with the DBMSs to accomplish their task.
v. Database Administrators (DBA):This may be one person or a group of people in an organization responsible
for authorizing access to the database, monitoring its use and managing all of the resources to support the
use of the entire database system.
vi. System Analyst − A System Analyst has also known as a business technology analyst. These professionals
are responsible for the design, structure, and properties of databases. The application programmer uses the
specifications provided by the system analyst to construct the software that is used by end users. The analyst
will gather information from the shareholders as well as end users to understand their requirements and
translate it into functional specifications for the new system.
Examples of System Analysts −They serve as team leaders.; They are responsible for managing
projects.;They are the supervisor who manages the lower-level information Staff.
vii. Temporary Users/Casual Users − These users utilize the database for testing and are only accessible for a
limited time. According to business requirements, these users update a little or new information to the
database with the help of a database administrator. It helps to maintain the security and integrity of
data.https://codex.cs.yale.edu/avi/db-book/slides-dir/index.html

Characteristics of the database systems

There are a number of characteristics that distinguish the database approach from the file-based system or
approach. This chapter describes the benefits (and features) of the database system.

Self-describing nature of a database system: A database system is referred to as self-describing because it not
only contains the database itself, but also metadata which defines and describes the data and
relationships between tables in the database. This information is used by the DBMS software or database users if
needed. This separation of data and information about the data makes a database system totally different from the
traditional file-based system in which the data definition is part of the application programs.
Insulation between program and data: In the file-based system, the structure of the data files is defined in the
application programs so if a user wants to change the structure of a file, all the programs that access that file
might need to be changed as well.

On the other hand, in the database approach, the data structure is stored in the system catalogue and not in the
programs. Therefore, one change is all that is needed to change the structure of a file. This insulation between the
programs and data is also called program-data independence.

Support for multiple views of data: A database supports multiple views of data. A view is a subset of the
database, which is defined and dedicated for particular users of the system. Multiple users in the system might
have different views of the system. Each view might contain only the data of interest to a user or group of users.

Sharing of data and multiuser system: Current database systems are designed for multiple users. That is, they
allow many users to access the same database at the same time. This access is achieved through features
called concurrency control strategies. These strategies ensure that the data accessed are always correct and
that data integrity is maintained. The design of modern multiuser database systems is a great improvement from
those in the past which restricted usage to one person at a time.

Control of data redundancy: In the database approach, ideally, each data item is stored in only one place in the
database. In some cases, data redundancy still exists to improve system performance, but such redundancy is
controlled by application programming and kept to minimum by introducing as little redudancy as possible when
designing the database.

Data sharing: The integration of all the data, for an organization, within a database system has many advantages.
First, it allows for data sharing among employees and others who have access to the system. Second, it gives
users the ability to generate more information from a given amount of data than would be possible without the
integration.

Enforcement of integrity constraints: Database management systems must provide the ability to define and
enforce certain constraints to ensure that users enter valid information and maintain data integrity. A database
constraint is a restriction or rule that dictates what can be entered or edited in a table such as a postal code using
a certain format or adding a valid city in the City field.

There are many types of database constraints. Data type, for example, determines the sort of data permitted in a
field, for example numbers only. Data uniqueness such as the primary key ensures that no duplicates are entered.
Constraints can be simple (field based) or complex (programming).

Restriction of unauthorized access: Not all users of a database system will have the same accessing privileges.
For example, one user might have read-only access (i.e., the ability to read a file but not make changes), while
another might have read and write privileges, which is the ability to both read and modify a file. For this reason,
a database management system should provide a security subsystem to create and control different types of user
accounts and restrict unauthorized access.

Data independence: Another advantage of a database management system is how it allows for data
independence. In other words, the system data descriptions or data describing data (metadata) are separated from
the application programs. This is possible because changes to the data structure are handled by the database
management system and are not embedded in the program itself.
Transaction processing: A database management system must include concurrency control subsystems. This
feature ensures that data remains consistent and valid during transaction processing even if several users update
the same information.

Provision for multiple views of data : By its very nature, a DBMS permits many users to have access to its
database either individually or simultaneously. It is not important for users to be aware of how and where the
data they access is stored

Backup and recovery facilities :Backup and recovery are methods that allow you to protect your data from
loss. The database system provides a separate process, from that of a network backup, for backing up and
recovering data. If a hard drive fails and the database stored on the hard drive is not accessible, the only way to
recover the database is from a backup.
If a computer system fails in the middle of a complex update process, the recovery subsystem is responsible for
making sure that the database is restored to its original state. These are two more benefits of a database
management system.

Schema & Instance


Schema refers to the overall description of any given database
Instance refers to a collection of data & information that the database stores at any particular movement

The overall design of the database is called database schema. Schema will not be changed frequently. It is the
logical structure of a database. It does not show the data in the database.

The schema is pictorially represented as follows −

Types of Schema

The different types of schemas are as follows −

Physical schema − It is a database design at the physical level.It is hidden below the logical schema and
can be changed easily without affecting the application programs.
Logical schema − It is a database design at the logical level. Programmers construct applications using
logical schema.
External − It is schema at view level. It is the highest level of a schema which defines the views for end
users.

Generally the Database Management System (DBMS) assists one physical schema, one logical schema and
several sub or external schemas.
Database schema refers to the format and layout of the database in which the data will be stored. It is the one
thing that remains the same throughout unless otherwise modified. It defines the structure of what type of data
and how it will be stored.

Example

A database schema for a person will have fields for name, email, phone and address as shown below −

Person

Name Email Phone no

Instance

Instance or extension or database state is a collection of information that stored in a database at a particular
moment is called an instance of the database. The Database instance refers to the information stored in the
database at a given point of time. Thus, it is a dynamic value which keeps on changing.

Example

A database instance for the Person database can be (User1,emai.com,11345679,addr) So the person construct
will contain their individual entities in the attributes called as instance. This is shown below −

Person

Name Email Phone no


BOB [email protected] 2343435
JANU [email protected] 5345464
PRIYA [email protected] 2342342

Differences

The major differences between schema and instance are as follows −

Database Schema Database Instance

It is the definition of the It is a snapshot of a database at a specific


database or it is defined as moment.
the description of the
database.
It rarely changes. It changes frequently.
Example” We take two At a moment, what is the value of the database
tables emp table and dept schema is called instance.At t=8 A.M
table.Emp
Empid name salary did
Database Schema Database Instance

Id 1 A 5000 d1
Name 2 B 2000 d2
Salary At t=9 A.M
3
dept
Dept C
Dept_id 3000
dname d3
Emp and dept both called Empid 1 and 2 are called as Instance 1
as schemas At time 9 A.M instance 2 changes
It gives database definition
This corresponds to the The value of the variable in a program at a point
variable declaration of a in time corresponds to an instance of the
programming language. database schema.

DBMS Architecture

o The DBMS design depends upon its architecture. The basic client/server architecture is used to deal with
a large number of PCs, web servers, database servers and other components that are connected with
networks.
o The client/server architecture consists of many PCs and a workstation which are connected via the
network.
o DBMS architecture depends upon how users are connected to the database to get their request done.

Types of DBMS Architecture

Database architecture can be seen as a single tier or multi-tier. But logically, database architecture is of two types
like: 2-tier architecture and 3-tier architecture.

1-Tier Architecture
o In this architecture, the database is directly available to the user. It means the user can directly sit on the
DBMS and uses it.
o Any changes done here will directly be done on the database itself. It doesn't provide a handy tool for end
users.
o The 1-Tier architecture is used for development of the local application, where programmers can directly
communicate with the database for the quick response.

2-Tier Architecture

o The 2-Tier architecture is same as basic client-server. In the two-tier architecture, applications on the
client end can directly communicate with the database at the server side. For this interaction, API's
like: ODBC, JDBC are used.
o The user interfaces and application programs are run on the client-side.
o The server side is responsible to provide the functionalities like: query processing and transaction
management.
o To communicate with the DBMS, client-side application establishes a connection with the server side.

Fig: 2-tier Architecture

3-Tier Architecture

o The 3-Tier architecture contains another layer between the client and server. In this architecture, client
can't directly communicate with the server.
o The application on the client-end interacts with an application server which further communicates with
the database system.
o End user has no idea about the existence of the database beyond the application server. The database also
has no idea about any other user beyond the application.
o The 3-Tier architecture is used in case of large web application.
Fig: 3-tier Architecture

The Database Management System (DBMS) architecture shows how data in the database is viewed by the users.
It is not concerned about how the data are handled and processed by the DBMS.

It helps in implementation, design, and maintenance of a database to store and organize information for
companies. The concept of DBMS depends upon its architecture. The architecture can be designed as centralized,
decentralized, or hierarchical.

The architecture of DBMS can be defined at three levels as follows − External levels; Conceptual levels.;
Internal levels.

The main objective of the three level architecture is nothing but to separate each user view of the data from the
way the database is physically represented. The database internal structure should be unaffected while changes to
the physical aspects of storage.

The DBA should be able to change the conceptual structure of the database without affecting all other users.

External level/ View level: describes a part of the database that is relevant to each user. This level insulates the
users from the details of conceptual and the internal level.

Conceptual level/ logic level: describes what data is stored into the database and the relationship among the
data.

It represents the following − All the entities, attributes and their relationships. The constraints on the data.
Security and integrity information.

Internal level/ storage level; Internal level is the physical representation of the database on the computer. This
level describes how the data is stored in the database. It covers the data structure and file organization used to
store the data on storage devices.

The levels in the architecture of DBMS are shown below in diagram form −
Data Models

Data Model is the modeling of the data description, data semantics, and consistency constraints of the data. It
provides the conceptual tools for describing the design of a database at each level of data abstraction. Therefore,
there are following four data models used for understanding the structure of the database:

1) Relational Data Model: This type of model designs the data in the form of rows and columns within a table.
Thus, a relational model uses tables for representing data and in-between relationships. Tables are also called
relations. This model was initially described by Edgar F. Codd, in 1969. The relational data model is the widely
used model which is primarily used by commercial data processing applications.

2) Entity-Relationship Data Model: An ER model is the logical representation of data as objects and
relationships among them. These objects are known as entities, and relationship is an association among these
entities. This model was designed by Peter Chen and published in 1976 papers. It was widely used in database
designing. A set of attributes describe the entities. For example, student_name, student_id describes the 'student'
entity. A set of the same type of entities is known as an 'Entity set', and the set of the same type of relationships
is known as 'relationship set'.
3) Object-based Data Model: An extension of the ER model with notions of functions, encapsulation, and
object identity, as well. This model supports a rich type system that includes structured and collection types.
Thus, in 1980s, various database systems following the object-oriented approach were developed. Here, the
objects are nothing but the data carrying its properties.

4) Semistructured Data Model: This type of data model is different from the other three data models (explained
above). The semistructured data model allows the data specifications at places where the individual data items of
the same type may have different attributes sets. The Extensible Markup Language, also known as XML, is
widely used for representing the semistructured data. Although XML was initially designed for including the
markup information to the text document, it gains importance because of its application in the exchange of data.

o The data which is stored in the database at a particular moment of time is called an instance of the
database.
o The overall design of a database is called schema.
o A database schema is the skeleton structure of the database. It represents the logical view of the entire
database.
o A schema contains schema objects like table, foreign key, primary key, views, columns, data types,
stored procedure, etc.
o A database schema can be represented by using the visual diagram. That diagram shows the database
objects and relationship with each other.
o A database schema is designed by the database designers to help programmers whose software will
interact with the database. The process of database creation is called data modeling.

A schema diagram can display only some aspects of a schema like the name of record type, data type, and
constraints. Other aspects can't be specified through the schema diagram. For example, the given figure neither
show the data type of each data item nor the relationship among various files.

In the database, actual data changes quite frequently. For example, in the given figure, the database changes
whenever we add a new grade or add a student. The data at a particular moment of time is called the instance of
the database.
Data modeling using entity relationship approach
ERD: Logical relationship among data items, known as ERD.
o This model is used to define the data elements and relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and easy to design view of
data.

An Entity Relationship Diagram is a diagram that represents relationships among entities in a database. It is
commonly known as an ER Diagram.
An ER Diagram in DBMS plays a crucial role in designing the database.
Today’s business world previews all the requirements demanded by the users in the form of an ER Diagram.
Later, it's forwarded to the database administrators to design the database.

ER diagram is created based on three principal components: entities, attributes, and relationships.
Why Use ER Diagrams in DBMS?
i. ER Diagram helps you conceptualize the database and lets you know which fields need to be embedded for a
particular entity
ii. ER Diagram gives a better understanding of the information to be stored in a database
iii. It reduces complexity and allows database designers to build databases quickly
iv. It helps to describe elements using Entity-Relationship models
v. It allows users to get a preview of the logical structure of the database
Symbols Used in ER Diagrams

 Rectangles: This Entity Relationship Diagram symbol represents entity types


 Ellipses: This symbol represents attributes
 Diamonds: This symbol represents relationship types
 Lines: It links attributes to entity types and entity types with other relationship types
 Primary key: Here, it underlines the attributes
 Double Ellipses: Represents multi-valued attributes

An entity that depends on another entity called a weak entity. The weak entity doesn't contain any key attribute
of its own. The weak entity is represented by a double rectangle.

Components of ER Diagram
You base an ER Diagram on three basic concepts:

i. Entities :Weak Entity

ii. Attributes: Key Attribute; Composite Attribute; Multivalued Attribute; Derived Attribute;

iii. Relationships: One-to-One Relationships; One-to-Many Relationships; Many-to-One Relationships; Many-


to-Many Relationships

Entities:An entity can be either a living or non-living component. It showcases an entity as a rectangle in an ER
diagram. For example, in a student study course, both the student and the course are entities.
Weak Entity

An entity that makes reliance over another entity is called a weak entity. You showcase the weak entity as a
double rectangle in ER Diagram.

In the example below, school is a strong entity because it has a primary key attribute - school number. Unlike
school, the classroom is a weak entity because it does not have any primary key and the room number here acts
only as a discriminator.

Attribute: An attribute exhibits the properties of an entity. You can illustrate an attribute with an oval shape in
an ER diagram.

Key Attribute: Key attribute uniquely identifies an entity from an entity set. It underlines the text of a key
attribute. For example: For a student entity, the roll number can uniquely identify a student from a set of students.
Composite Attribute: An attribute that is composed of several other attributes is known as a composite attribute.
An oval showcases the composite attribute, and the composite attribute oval is further connected with other ovals.

Multivalued Attribute: Some attributes can possess over one value, those attributes are called multivalued
attributes. The double oval shape is used to represent a multivalued attribute.

Derived Attribute: An attribute that can be derived from other attributes of the entity is known as a derived
attribute. In the ER diagram, the dashed oval represents the derived attribute.
Relationship: The diamond shape showcases a relationship in the ER diagram. It depicts the relationship
between two entities. In the example below, both the student and the course are entities, and study is the
relationship between them.

One-to-One Relationship: When a single element of an entity is associated with a single element of another
entity, it is called a one-to-one relationship. For example, a student has only one identification card and an
identification card is given to one person.

One-to-Many Relationship: When a single element of an entity is associated with more than one element of
another entity, it is called a one-to-many relationship. For example, a customer can place many orders, but an
order cannot be placed by many customers.

Many-to-One Relationship: When more than one element of an entity is related to a single element of another
entity, then it is called a many-to-one relationship. For example, students have to opt for a single course, but a
course can have many students.
Many-to-Many Relationship: When more than one element of an entity is associated with more than one
element of another entity, this is called a many-to-many relationship. For example, you can assign an employee
to many projects and a project can have many employees.

Objective:
ER Diagram in DBMS is widely used to describe the conceptual design of databases.
It helps both users and database developers to preview the structure of the database before implementing
the database.
ERD Library Management System
Human Resource Application
Schema Diagram of the Project
The Enhanced ER Model

As the complexity of data increased in the late 1980s, it became more and more difficult to use the traditional ER
Model for database modelling. Hence some improvements or enhancements were made to the existing ER Model
to make it able to handle the complex applications better.

Hence, as part of the Enhanced ER Model, along with other improvements, three new concepts were added to
the existing ER Model, they were

1. Generalization
2. Specialization
3. Aggregration
Let's understand what they are, and why were they added to the existing ER Model.

Generalization is a bottom-up approach in which two lower level entities combine to form a higher
level entity. In generalization, the higher level entity can also combine with other lower level entities to
make further higher level entity.

It's more like Superclass and Subclass system, but the only difference is the approach, which is bottom-
up. Hence, entities are combined to form a more generalised entity, in other words, sub-classes are
combined to form a super-class.
For example, Saving and Current account types entities can be generalised and an entity with
name Account can be created, which covers both.

It is a form of abstraction that specifies two or more entities (sub class) having common characters that can be
generalized into one single entity (super class) at higher level hiding all the differences.

Specialization is opposite to Generalization.

Specialization is a process of identifying subsets of an entity that shares different characteristics. It breaks an
entity into multiple entities from higher level (super class) to lower level (sub class). The breaking of higher level
entity is based on some distinguishing characteristics of the entities in super class.

It is a top down approach in which we first define the super class and then sub class and then their attributes and
relationships.

It is a top-down approach in which one higher level entity can be broken down into two lower level entity. In
specialization, a higher level entity may not have any lower-level entity sets, it's possible.
Aggregration
Aggregration is a process when relation between two entities is treated as a single entity.

In the diagram above, the relationship between Center and Course together, is acting as an Entity,
which is in relationship with another entity Visitor.

Now in real world, if a Visitor or a Student visits a Coaching Center, he/she will never enquire about the
center only or just about the course, rather he/she will ask enquire about both.
Aggregation represents relationship between a whole object and its component. Using aggregation we can
express relationship among relationships. Aggregation shows ‘has-a’ or ‘is-part-of’ relationship between entities
where one represents the ‘whole’ and other ‘part’.

Consider a ternary relationship Works_On between Employee, Branch and Manager. Now the best way to model
this situation is to use aggregation, So, the relationship-set, Works_On is a higher level entity-set. Such an entity-
set is treated in the same manner as any other entity-set. We can create a binary relationship, Manager, between
Works_On and Manager to represent who manages what tasks.
Mapping of ER Model To Relational Model

Step 1: Regular Entity Types

i. For each regular/strong entity type, create a corresponding relation that includes all the simple attributes
(includes simple attributes of composite relations)

ii. Choose one of the key attributes as primary - If composite, the simple attributes together form the primary
key

iii. Any remaining key attributes are kept as secondary unique keys (these will be useful for physical tuning w.r.t.
indexing analysis

Strong Entity Types with simple attributes can be mapped into relations in a straightforward manner. Attributes
acting as keys in the ER model are retained as keys in the relational model.
Step 2: Weak Entity Types

i. For each weak entity type, create a corresponding relation that includes all the simple attributes

ii. Add as a foreign key all of the primary key attribute(s) in the entity corresponding to the owner entity type

iii. The primary key is the combination of all the primary key attributes from the owner and the partial key of the
weak entity, if any

For weak entity types, include the key of the owner entity type as key attribute(s).

These key attributes also form a foreign key into the owner entity type.
Step 3: Mapping Binary 1-to-1

– Foreign Key

• Usually appropriate - Merged Relation

• Possible when both participation are total

In a 1:1 binary relationship between two entity types S and T, choose one of them (say S) as the “base” relation.

i.If either S or T has a total participation, choose that one as the base.

ii.Include the primary key of the other entity type as a foreign key of the base.
iii.Include any relationship attributes as attributes of the base.

Step 4: Binary 1-to-N

i. Choose the S relation as the type at the N-side of the relationship, other is T

ii. Add as a foreign key to S all of the primary key attribute(s) of T


Step 5: Binary M-to-N

i. Create a new relation S (termed: relationship relation)

– In some ERD dialects, actually drawn in

ii. Add as foreign keys the primary keys of both relations; their combination forms the primary key of S

iii. Add any simple attributes of the M:N relationship to S

M:N binary relationship, it is not possible to collapse the relationship into any one of the entity types, since the
relationship does not identify either entity type uniquely.

A separate relation is required to complete the mapping.


Step 6: Multivalued Attributes

i. Create a new relation S

ii. Add as foreign keys the primary keys of the corresponding relation

iii. Add the attribute to S (if composite, the simple attributes); the combination of all attributes in S forms the
primary key

Mapping Multi-valued Attributes

For each multi-valued attributes of a given entity type S, create a separate relation that has the primary key of S,
paired with all values of the multi-valued attribute.
Step 7: Specialization/Generalization

Specialization is a process in which an entity is divided into sub-entities.

You can think of it as a reverse process of generalization, in generalization two entities combine together to form
a new higher level entity.

Specialization is a top-down process.

The idea behind Specialization is to find the subsets of entities that have few distinguish attributes.

For example – Consider an entity employee which can be further classified as subentities Technician, Engineer
& Accountant because these sub entities have some distinguish attributes
Aggregation

Aggregation is a process in which a single entity alone is not able to make sense in a relationship so the
relationship of two entities acts as one entity. I know it sounds confusing but don’t worry the example we will
take, will clear all the doubts. In real world, we know that a manager not only manages the employee working
under them. but he has to manage the project as well. In such scenario if entity “Manager” makes a “manages”
relationship with either “Employee” or “Project” entity alone then it will not make
Structured query language (SQL - 1970 for relational data model) is a programming language for storing and
processing information in a relational database.
A relational database stores information in tabular form, with rows and columns representing different data
attributes and the various relationships between the data values.
Data Analysists and develper use it, because it integrates with different PL
SQL - DDL, DML, DCL and DQL
DDL - A data definition language (DDL) is a computer language used to create and modify the structure of
database objects in a database.
i. Create - This command is used to create the database or its objects(Table, view, sequence, synonyms,
procedure, function , triggers)
Create table <table-name> (Columname <datatype - SIZe,…….)
Create index indx-name on <table-name(colname)>
ii. Alter - This command is used to alter the structure of database.
iii. Drop - This command is used to delete the object from database,can not be undone
DROP TABLE table_name;
iv. Truncate - This command is used remove all records from a table, including all spaces allocated for the
records are removed.
Delete all data from a table, but the structure of table remains. Its fast way to clear large data from
table.
Example: TRUNCATE TABLE table_name;
 Rename - This command is to rename an object in the database

Data Manipulation Language or DML is a subset of operations used to insert, delete, and update data in a
database.
i. Insert -
Update - This command is used to modify the existing records in a table.
 Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
 The WHERE clause specifies which records should be updated. Without it, all records in the table will be
updated.

Delete - This command is used to remove one or more rows from a table.
 Syntax: DELETE FROM table_name WHERE condition;
 Like with UPDATE, the WHERE clause specifies which rows should be deleted. Omitting
the WHERE clause will result in all rows being deleted.
Data Control Language is the sublanguage responsible for the administrative tasks of controlling the database
itself, most notably granting and revoking database permissions for users. In SQL, this corresponds to the
GRANT , REVOKE
Right, Permissions and others controls of database
Data Control Language (DCL) is a subset of SQL commands used to control access to data in a database. DCL is
crucial for ensuring security and proper data management, especially in multi-user database environments. The
primary DCL commands in SQL include:

1. GRANT: This command is used to give users access privileges to the database. These privileges can
include the ability to select, insert, update, delete, and so on, over database objects like tables and views.
 Syntax: GRANT privilege_name ON object_name TO user_name;
 For example, GRANT SELECT ON employees TO user123; gives user123 the permission to read
data from the employees table.
2. REVOKE: This command is used to remove previously granted access privileges from a user.
 Syntax: REVOKE privilege_name ON object_name FROM user_name;
 For example, REVOKE SELECT ON employees FROM user123; would remove user123‘s
permission to read data from the employees table.

Transaction Control Language (TCL) is a subset of SQL commands used to manage transactions in a database.
Transactions are important for maintaining the integrity and consistency of data. They allow multiple database
operations to be executed as a single unit of work, which either entirely succeeds or fails. The primary TCL
commands in SQL include:
1. BEGIN TRANSACTION (or sometimes just BEGIN): This command is used to start a new transaction.
It marks the point at which the data referenced in a transaction is logically and physically consistent.
 Syntax: BEGIN TRANSACTION;
 Note: In many SQL databases, a transaction starts implicitly with any SQL statement that accesses
or modifies data, so explicit use of BEGIN TRANSACTION is not always necessary.
2. COMMIT: This command is used to permanently save all changes made in the current transaction.
 Syntax: COMMIT;
 When you issue a COMMIT command, the database system will ensure that all changes made
during the current transaction are saved to the database.
3. ROLLBACK: This command is used to undo changes that have been made in the current transaction.
 Syntax: ROLLBACK;
 If you issue a ROLLBACK command, all changes made in the current transaction are discarded,
and the state of the data reverts to what it was at the beginning of the transaction.
4. SAVEPOINT: This command creates points within a transaction to which you can later roll back. It
allows for partial rollbacks and more complex transaction control.
 Syntax: SAVEPOINT savepoint_name;
 You can roll back to a savepoint using ROLLBACK TO savepoint_name;
5. SET TRANSACTION: This command is used to specify characteristics for the transaction, such as
isolation level.
 Syntax: SET TRANSACTION [characteristic];
 This is more advanced usage and may include settings like isolation level which controls how
transaction integrity is maintained and how/when changes made by one transaction are visible to other
transactions.

Data Query Language (DQL) is a subset of SQL commands used primarily to query and retrieve data from
existing database tables. In SQL, DQL is mostly centered around the SELECT statement, which is used to fetch
data according to specified

1. SELECT: The main command used in DQL, SELECT retrieves data from one or more tables.
 Basic Syntax: SELECT column1, column2, ... FROM table_name;
 To select all columns from a table, you use SELECT * FROM table_name;
2. WHERE Clause: Used with SELECT to filter records based on specific conditions.
 Syntax: SELECT column1, column2, ... FROM table_name WHERE condition;
 Example: SELECT * FROM employees WHERE department = 'Sales';
3. JOIN Clauses: Used to combine rows from two or more tables based on a related column between them.
 Types include INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN.
 Syntax: SELECT columns FROM table1 [JOIN TYPE] JOIN table2 ON table1.column_name =
table2.column_name;
4. GROUP BY Clause: Used with aggregate functions (like COUNT, MAX, MIN, SUM, AVG) to group
the result set by one or more columns.
 Syntax: SELECT column1, aggregate_function(column2) FROM table_name GROUP BY
column1;
5. ORDER BY Clause: Used to sort the result set in ascending or descending order.
 Syntax: SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC],
column2 [ASC|DESC];

SQL Constraints are rules used to limit the type of data that can go into a table, to maintain the accuracy and
integrity of the data inside table. Constraints can be divided into the following two types,

Constraints are used to make sure that the integrity of data is maintained in the database. Following are the most
used constraints that can be applied to a table.

 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT

NOT NULL Constraint

By default, a column can hold NULL values. If you do not want a column to have a NULL value, use the NOT
NULL constraint.

 It restricts a column from having a NULL value.


 We use ALTER statement and MODIFY statement to specify this constraint.
One important point to note about this constraint is that it cannot be defined at table level.

Example using NOT NULL constraint:

CREATE TABLE Student


( s_id int NOT NULL,
name varchar(60),
age int
);
The above query will declare that the s_id field of Student table will not take NULL value.

If you wish to alter the table after it has been created, then we can use the ALTER command for it:

ALTER TABLE Student


MODIFY s_id int NOT NULL;

UNIQUE Constraint

It ensures that a column will only have unique values. A UNIQUE constraint field cannot have any duplicate
data.

 It prevents two records from having identical values in a column


 We use ALTER statement and MODIFY statement to specify this constraint.

Example of UNIQUE Constraint:

Here we have a simple CREATE query to create a table, which will have a column s_id with unique values.

CREATE TABLE Student


( s_id int NOT NULL,
name varchar(60),
age int NOT NULL UNIQUE
);
The above query will declare that the s_id field of Student table will only have unique values and wont take
NULL value.

If you wish to alter the table after it has been created, then we can use the ALTER command for it:

ALTER TABLE Student


MODIFY age INT NOT NULL UNIQUE;
Primary Key Constraint
Primary key constraint uniquely identifies each record in a database. A Primary Key must contain unique value
and it must not contain null value. Usually Primary Key is used to index the data inside the table.

PRIMARY KEY constraint at Table Level


CREATE table Student
( s_id int PRIMARY KEY,
Name varchar(60) NOT NULL,
Age int);
The above command will creates a PRIMARY KEY on the s_id.

PRIMARY KEY constraint at Column Level


ALTER table Student
ADD PRIMARY KEY (s_id);
The above command will creates a PRIMARY KEY on the s_id.

Foreign Key Constraint


Foreign Key is used to relate two tables. The relationship between the two tables matches the Primary Key in one
of the tables with a Foreign Key in the second table.

This is also called a referencing key.


We use ALTER statement and ADD statement to specify this constraint.
To understand FOREIGN KEY, let's see its use, with help of the below tables:

Customer_Detail Table

c_id Customer_Name address


101 Adam Noida
102 Alex Delhi
103 Stuart Rohtak
Order_Detail Table

Order_id Order_Name c_id


10 Order1 101
11 Order2 103
12 Order3 102
In Customer_Detail table, c_id is the primary key which is set as foreign key in Order_Detail table. The value
that is entered in c_id which is set as foreign key in Order_Detail table must be present in Customer_Detail table
where it is set as primary key. This prevents invalid data to be inserted into c_id column of Order_Detail table.

If you try to insert any incorrect data, DBMS will return error and will not allow you to insert the data.

FOREIGN KEY constraint at Table Level


CREATE table Order_Detail(
order_id int PRIMARY KEY,
order_name varchar(60) NOT NULL,
c_id int FOREIGN KEY REFERENCES Customer_Detail(c_id)
);
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id column in
Customer_Detail table.

FOREIGN KEY constraint at Column Level


ALTER table Order_Detail
ADD FOREIGN KEY (c_id) REFERENCES Customer_Detail(c_id);
Behaviour of Foriegn Key Column on Delete
There are two ways to maintin the integrity of data in Child table, when a particular record is deleted in the main
table. When two tables are connected with Foriegn key, and certain data in the main table is deleted, for which a
record exits in the child table, then we must have some mechanism to save the integrity of data in the child table.

foriegn key behaviour on delete - cascade and Null


On Delete Cascade : This will remove the record from child table, if that value of foriegn key is deleted from the
main table.
On Delete Null : This will set all the values in that record of child table as NULL, for which the value of foriegn
key is deleted from the main table.
If we don't use any of the above, then we cannot delete data from the main table for which data in child table
exists. We will get an error if we try to do so.
ERROR : Record in child table exist

CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs check on the values,
before storing them into the database. Its like condition checking before saving data into a column.

Using CHECK constraint at Table Level


CREATE table Student(
s_id int NOT NULL CHECK(s_id > 0),
Name varchar(60) NOT NULL,
Age int
);
The above query will restrict the s_id value to be greater than zero.

Using CHECK constraint at Column Level


ALTER table Student ADD CHECK(s_id > 0);

You might also like