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

DBMS Notes

The document provides an overview of databases and database management systems (DBMS), explaining the definition of data and databases, the evolution of database models, and various types of databases including relational, NoSQL, and cloud databases. It highlights the advantages and disadvantages of DBMS, emphasizing improved data security, integration, and decision-making, while also noting challenges such as cost and complexity. Additionally, it discusses the features and functionalities of DBMS, including data organization, sharing, and scalability.

Uploaded by

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

DBMS Notes

The document provides an overview of databases and database management systems (DBMS), explaining the definition of data and databases, the evolution of database models, and various types of databases including relational, NoSQL, and cloud databases. It highlights the advantages and disadvantages of DBMS, emphasizing improved data security, integration, and decision-making, while also noting challenges such as cost and complexity. Additionally, it discusses the features and functionalities of DBMS, including data organization, sharing, and scalability.

Uploaded by

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

Introduction to DBMS

What is Data?
-Data is a collection of a distinct small unit of information. It can be used in a variety of forms
like text, numbers, media, bytes, etc. it can be stored in pieces of paper or electronic memory,
etc.
-Word 'Data' is originated from the word 'datum' that means 'single piece of information.' It is
plural of the word datum.
-In computing, Data is information that can be translated into a form for efficient movement and
processing. Data is interchangeable.
What is Database?
-A database is an organized collection of data, so that it can be easily accessed and managed.
You can organize data into tables, rows, columns, and index it to make it easier to find relevant
information.
-Database handlers create a database in such a way that only one set of software program
provides access of data to all the users.
-The main purpose of the database is to operate a large amount of information by storing,
retrieving, and managing data.
-There are many dynamic websites on the World Wide Web nowadays which are handled
through databases. For example, a model that checks the availability of rooms in a hotel. It is an
example of a dynamic website that uses a database.
-There are many databases available like MySQL, Sybase, Oracle, MongoDB, Informix,
PostgreSQL, SQL Server, etc.
-Modern databases are managed by the database management system (DBMS).
-SQL or Structured Query Language is used to operate on the data stored in a database. SQL
depends on relational algebra and tuple relational calculus.
-A cylindrical structure is used to display the image of a database.
Evolution of Databases
The database has completed more than 50 years of journey of its evolution from flat-file system
to relational and objects relational systems. It has gone through several generations.
1. File-Based
1968 was the year when File-Based database were introduced.
In file-based databases, data was maintained in a flat file.
One of the major advantages is that the file system has various access methods, e.g.,
sequential, indexed, and random.
Though files have many advantages, there are several limitations.
It requires extensive programming in a third-generation language such as COBOL, BASIC.
2. Hierarchical Data Model
1968-1980 was the era of the Hierarchical Database. The prominent hierarchical database
model was IBM's first DBMS. It was called IMS (Information Management System).
In this model, files are related in a parent/child manner.
Below diagram represents Hierarchical Data Model. Small circle represents objects.
Like file system, this model also had some limitations like complex implementation, lack
structural independence, can't easily handle a many-many relationship, etc.
3. Network data model
Charles Bachman developed the first DBMS at Honeywell called Integrated Data Store (IDS). It
was developed in the early 1960s, but it was standardized in 1971 by the CODASYL group
(COnference on DAta SYstems Languages).
In this model, files are related as owners and members, like to the common network model.
Network data model identified the following
components:
o Network schema (Database organization)
o Sub-schema (views of database per user)
o Data management language (procedural)
This model also had some limitations like system complexity and difficult to design and maintain.
4. Relational Database
1970 - Present: It is the era of Relational Database and Database Management. In 1970, the
relational model was proposed by E.F. Codd.
Relational database model has two main terminologies called instance and schema.
The instance is a table with rows or columns
Schema specifies the structure like name of the relation, type of each column and name.
This model uses some mathematical concept like set theory and predicate logic.
The first internet database application had been created in 1995.
During the era of the relational database,
many more models had introduced like
object-oriented model, object-relational
model, etc.
Relational database properties
o Atomicity
o Consistency
o Integrity
o Durability
o Concurrency
o Query processing
5. Cloud database
Cloud database facilitates you to store, manage,
and retrieve their structured, unstructured data
via a cloud platform.
This data is accessible over the Internet.
Cloud databases are also called a database as
service (DBaaS) because they are offered as a
managed service.
Some best cloud options are:
o AWS (Amazon Web Services)
o Snowflake Computing
o Oracle Database Cloud Services
o Microsoft SQL server
o Google cloud spanner

Advantages of cloud database


Lower costs
Generally, company provider does not have to invest in databases. It can maintain and support
one or more data centers.
Automated
Cloud databases are enriched with a variety of automated processes such as recovery, failover,
and auto-scaling.
Increased accessibility
You can access your cloud-based database from any location, anytime. All you need is just an
internet connection.
6. NoSQL Database
A NoSQL database is an approach to design such databases that can accommodate a wide
variety of data models. NoSQL stands for "not only SQL."
It is an alternative to traditional relational databases in which data is placed in tables, and data
schema is perfectly designed before the database is built.
NoSQL databases are useful for a large set of distributed data.
Thus, NoSQL presented a wide variety of database technologies in response to the demands. We
can further divide a NoSQL database into the following four types:
a) Key-value storage: It is the simplest type of database storage where it stores every single
item as a key (or attribute name) holding its value, together.

b) Document-oriented Database: A type of database used to store data as JSON-like


document. It helps developers in storing data by using the same document-model format as
used in the application code.
Graph Databases: It is used for storing vast amounts of data in a graph-like structure. Most
commonly, social networking websites use the graph database.

c) Wide-column stores: It is similar to the data represented in relational databases. Here, data
is stored in large columns together, instead of storing in rows.
Some examples of NoSQL database system with their category are:
o MongoDB, CouchDB, Cloudant (Document-based)
o Memcached, Redis, Coherence (key-value store)
o HBase, Big Table, Accumulo (Tabular)
Advantage of NoSQL:
• High Scalability
NoSQL can handle an extensive amount of data because of scalability. If the data grows, NoSQL
database scale it to handle that data in an efficient manner.
• High Availability
NoSQL supports auto replication. Auto replication makes it highly available because, in case of
any failure, data replicates itself to the previous consistent state.
Disadvantage of NoSQL
• Open source
NoSQL is an open-source database, so there is no reliable standard for NoSQL yet.
• Management challenge
Data management in NoSQL is much more complicated than relational databases. It is very
challenging to install and even more hectic to manage daily.
• GUI is not available
GUI tools for NoSQL database are not easily available in the market.
• Backup
Backup is a great weak point for NoSQL databases. Some databases, like MongoDB, have no
powerful approaches for data backup.
7. The Object-Oriented Databases
The object-oriented databases contain data in the form of object and classes.
Objects are the real-world entity, and classes/types are the collection of objects.
An object-oriented database is a combination of relational model features with objects oriented
principles.
It is an alternative implementation to that of the relational model.
Object-oriented databases hold the rules of object-oriented programming. An object-oriented
database management system is a hybrid application.
The object-oriented database model contains the following properties.
Object-oriented programming properties
o Objects
o Classes
o Inheritance
o Polymorphism
o Encapsulation
8. Graph Databases
A graph database is a NoSQL database.
It is a graphical representation of data. It contains nodes and edges.
A node represents an entity, and each edge represents a relationship between two edges.
Every node in a graph database represents a unique identifier.
Graph databases are beneficial for searching the relationship between data because they
highlight the relationship between relevant data.
Graph databases are very useful when the database contains a complex relationship and
dynamic schema.
It is mostly used in supply chain management, identifying the source of IP telephony.
9. Personal Database
Collecting and storing data on the user's system defines a Personal Database. This database is
basically designed for a single user.
Advantage of Personal Database
It is simple and easy to handle.
It occupies less storage space as it is small in size.
10. Operational Database
The type of database which creates and updates the database in real-time. It is basically
designed for executing and handling the daily data operations in several businesses. For
example, An organization uses operational databases for managing per day transactions.
11. Enterprise Database
Large organizations or enterprises use this database for managing a massive amount of data. It
helps organizations to increase and improve their efficiency. Such a database allows
simultaneous access to users.
Advantages of Enterprise Database:
Multi processes are supportable over the Enterprise database.
It allows executing parallel queries on the system.
DBMS (Data Base Management System)
Database management System is software which is used to
store and retrieve the database.
For example, Oracle, MySQL, etc.; these are some popular
DBMS tools.
DBMS is designed to manage and organize data in a structured
manner.
It allows users to create, modify, and query a database, as well as manage the security and
access controls for that database.
o DBMS provides the interface to perform the various operations like creation, deletion,
modification, etc.
o DBMS allows the user to create their databases as per their requirement.
o DBMS accepts the request from the application and provides specific data through the
operating system.
o DBMS contains the group of programs which acts according to the user instruction.
o It provides security to the database.
Advantage of DBMS
Some of them are given as follows below.
i. Better Data Transferring: Database management creates a place where users have an
advantage of more and better-managed data. Thus, making it possible for end-users to have a
quick look and to respond fast to any changes made in their environment.
ii. Better Data Security: The more accessible and usable the database, the more it is prone to
security issues. As the number of users increases, the data transferring or data sharing rate
also increases thus increasing the risk of data security. It is widely used in the corporate world
where companies invest large amounts of money, time, and effort to ensure data is secure and
used properly. A Database Management System (DBMS) provides a better platform for data
privacy and security policies thus, helping companies to improve Data Security.
iii. Better data integration: Due to the Database Management System we have access to well-
managed and synchronized forms of data thus it makes data handling very easy and gives an
integrated view of how a particular organization is working and also helps to keep track of how
one segment of the company affects another segment.
iv. Minimized Data Inconsistency: Data inconsistency occurs between files when different
versions of the same data appear in different places. For Example, data inconsistency occurs
when a student’s name is saved as “John Wayne” on the main computer of the school but on
the teacher registered system same student name is “William J. Wayne”, or when the price of
a product is $86.95 in the local system of the company and its National sales office system
shows the same product price as $84.95. So if a database is properly designed then Data
inconsistency can be greatly reduced hence minimizing data inconsistency.
v. Faster data Access: The Database management system (DBMS) helps to produce quick
answers to database queries thus making data access faster and more accurate. For example,
to read or update the data. For example, end-users, when dealing with large amounts of sale
data, will have enhanced access to the data, enabling a faster sales cycle. Some queries may
be like:
• What is the increase in sales in the last three months?

• What is the bonus given to each the salespeople in the last five months?

• How many customers have a credit score of 850 or more?

vi. Better decision making: Due to DBMS now we have Better managed data and Improved data
access because of which we can generate better quality information hence on this basis better
decisions can be made. Better Data quality improves accuracy, validity, and the time it takes
to read data. DBMS does not guarantee data quality, it provides a framework to make it easy
to improve data quality. DBMS provides powerful data analysis and reporting tools that allow
users to make informed decisions based on data insights. This helps organizations to improve
their decision-making processes and achieve better business outcomes.
vii. Increased end-user productivity: The data which is available with the help of a combination
of tools that transform data into useful information, helps end-users to make quick,
informative, and better decisions that can make a difference between success and failure in
the global economy.
viii. Simple: Database management system (DBMS) gives a simple and clear logical view of data.
Many operations like insertion, deletion, or creation of files or data are easy to implement.
ix. Data abstraction: The major purpose of a database system is to provide users with an abstract
view of the data. Since many complex algorithms are used by the developers to increase the
efficiency of databases that are being hidden by the users through various data abstraction
levels to allow users to easily interact with the system.
x. Reduction in data Redundancy: When working with a structured database, DBMS provides the
feature to prevent the input of duplicate items in the database. for e.g. – If there are two same
students in different rows, then one of the duplicate data will be deleted.
xi. Application development: A DBMS provides a foundation for developing applications that
require access to large amounts of data, reducing development time and costs.
xii. Data sharing: A DBMS provides a platform for sharing data across multiple applications and
users, which can increase productivity and collaboration.
xiii. Data organization: A DBMS provides a systematic approach to organizing data in a structured
way, which makes it easier to retrieve and manage data efficiently.
xiv. The atomicity of data can be maintained: That means, if some operation is performed on
one particular table of the database, then the change must be reflected for the entire
database.
xv. The DBMS allows concurrent access to multiple users by using the synchronization
technique.
xvi. Data consistency and accuracy: DBMS ensures that data is consistent and accurate by
enforcing data integrity constraints and preventing data duplication. This helps to eliminate
data discrepancies and errors that can occur when data is stored and managed manually.
xvii. Improved data security: DBMS provides a high level of data security by offering user
authentication and authorization, data encryption, and access control mechanisms. This helps
to protect sensitive data from unauthorized access, modification, or theft.
xviii. Efficient data access and retrieval: DBMS allows for efficient data access and retrieval by
providing indexing and query optimization techniques that speed up data retrieval. This
reduces the time required to process large volumes of data and increases the overall
performance of the system.
xix. Scalability and flexibility: DBMS is highly scalable and can easily accommodate changes in data
volumes and user requirements. DBMS can easily handle large volumes of data, and can scale
up or down depending on the needs of the organization. It provides flexibility in data storage,
retrieval, and manipulation, allowing users to easily modify the structure and content of the
database as needed.
xx. Improved productivity: DBMS reduces the time and effort required to manage data, which
increases productivity and efficiency. It also provides a user-friendly interface for data entry
and retrieval, which reduces the learning curve for new users.
Disadvantage of DBMS
i. Size
It occupies large disk space and large memory to run efficiently.
ii. Increased Cost:
These are different types of costs:
a) Cost of Hardware and Software –
This is the first disadvantage of the database management system. This is because, for
DBMS, it is mandatory to have a high-speed processor and also a large memory size. After
all, nowadays there is a large amount of data in every field which needs to be store safely
and with security.
b) Cost of Staff Training –
Educated staff (database administrator, application programmers, data entry operations)
who maintains the database management system also requires a good amount. We need
the database system designers to be hired along with application programmers.
Alternatively, the services of some software houses need to be taken. So there is a lot of
money which needs to be spent on developing software.
c) Cost of Data Conversion –
We need to convert our data into a database management system, there is a requirement
of a lot of money as it adds to the cost of the database management system. This is because
for this conversion we need to hire database system designers whom we have to pay a lot
of money and also services of some software house will be required. All this shows that a
high initial investment for hardware, software, and trained staff is required by DBMS. So,
altogether Database Management System results in a costlier system.
iii. Complexity:
As we all know that nowadays all companies are using the database management system as it
fulfills lots of requirements and also solves the problem. But a problem arises, that is all this
functionality has made the database management system an extremely complex software. For
the proper requirement of DBMS, it is very important to have a good knowledge of it by the
developers, DBA, designers, and also the end-users. This is because if any one of them does
not acquire proper and complete skills then this may lead to data loss or database failure.
These failures may lead to bad design decisions due to which there may be serious and bad
consequences for the organization. So this complex system needs to be understood by
everyone using it. As it cannot be managed very easily. All this shows that a database
management system is not a child’s game as it cannot be managed very easily. It requires a lot
of management. A good staff is needed to manage this database at times when it becomes
very complicated to decide where to pick data from and where to save it.
iv. Currency Maintenance:
This is very necessary to keep your system current because efficiency which is one of the
biggest factors and needs to be overlooked must be maximized. That is we need to maximize
the efficiency of the database system to keep our system current. For this, frequent updation
must be performed on all the components as new threats come daily. DBMS should be
updated according to the current scenario. Also, security measures must be implemented.
Due to advancement in database technology, training cost tends to be significant.
v. Performance:
The traditional file system is written for small organizations and for some specific applications
due to which performance is generally very good. But for the small-scale firms, DBMS does not
give a good performance as its speed is very slow. As a result, some applications will not run as
fast as they could. Hence it is not good to use DBMS for small firms. Because performance is a
factor that is overlooked by everyone. If performance is good then everyone (developers,
designers, end-users) will use it easily and it will be user-friendly too. As the speed of the
system totally depends on the performance so performance needs to be good.
vi. Frequency Upgrade/Replacement Cycles:
Nowadays in this world, we need to stay up-to-date about the latest technologies,
developments arriving in the market. Frequent upgrade of the products is done by the DBMS
vendors to add new functionality to the systems. New upgrade versions of the software often
come bundled. Sometimes these updates also need hardware upgrades. Sometimes these
changes and updates are so fast that the users find it difficult to work with that system
because it is not easy to learn new commands and understand them again when the new
upgrades are done. All these upgrades also cost money to train users, designers, etc. to use
the new features.
vii. Complex design :
Database design is complex, difficult and time consuming.
viii. Damaged part : If one part of database is corrupted or damaged, then entire database may
get affected.
ix. Compatibility: DBMS software may not be compatible with other software systems or
platforms, making it difficult to integrate with other applications.
x. Security: A DBMS can be vulnerable to security breaches if not properly configured and
managed. This can lead to data loss or theft.
Application of DBMS
There are different fields where a database management system is utilized. Following are a few
applications that utilize the information base administration framework.

Applications of DBMS
1. Railway Reservation System
In the rail route reservation framework, the information base is needed to store the record or
information of ticket appointments, status of train’s appearance, and flight. Additionally, if trains
get late, individuals become acquainted with it through the information base update.
2. Library Management System
There are many books in the library so; it is difficult to store the record of the relative multitude
of books in a register or duplicate. Along these lines, the data set administration framework
(DBMS) is utilized to keep up all the data identified with the name of the book, issue date,
accessibility of the book, and its writer.
3. Banking
Database the executive’s framework is utilized to store the exchange data of the client in the
information base.
4. Education Sector
Presently, assessments are led online by numerous schools and colleges. They deal with all
assessment information through the data set administration framework (DBMS). In spite of that
understudy’s enlistments subtleties, grades, courses, expense, participation, results, and so
forth all the data is put away in the information base.
5. Credit card exchanges
The database Management framework is utilized for buying on charge cards and age of month
to month proclamations.
6. Social Media Sites
We all utilization of online media sites to associate with companions and to impart our
perspectives to the world. Every day, many people group pursue these online media accounts
like Pinterest, Facebook, Twitter, and Google in addition to. By the utilization of the data set
administration framework, all the data of clients are put away in the information base and, we
become ready to interface with others.
7. Broadcast communications
Without DBMS any media transmission organization can’t think. The Database the executive’s
framework is fundamental for these organizations to store the call subtleties and month to
month postpaid bills in the information base.
8. Accounting and Finance
The information base administration framework is utilized for putting away data about deals,
holding and acquisition of monetary instruments, for example, stocks and bonds in a data set.
9. E-Commerce Websites
These days, web-based shopping has become a major pattern. Nobody needs to visit the shop
and burn through their time. Everybody needs to shop through web based shopping sites, (for
example, Amazon, Flipkart, Snapdeal) from home. So all the items are sold and added uniquely
with the assistance of the information base administration framework (DBMS). Receipt charges,
installments, buy data these are finished with the assistance of DBMS.
10. Human Resource Management
Big firms or organizations have numerous specialists or representatives working under them.
They store data about worker’s compensation, assessment, and work with the assistance of an
information base administration framework (DBMS).
11. Manufacturing
Manufacturing organizations make various kinds of items and deal them consistently. To keep
the data about their items like bills, acquisition of the item, amount, inventory network the
executives, information base administration framework (DBMS) is utilized.
12. Airline Reservation System
This framework is equivalent to the railroad reservation framework. This framework additionally
utilizes an information base administration framework to store the records of flight takeoff,
appearance, and defer status.
13. Healthcare System
DBMS is used in healthcare to manage patient data, medical records, and billing information.
14. Security
DBMS provides security features to ensure that only authorized users have access to the data.
15. Telecommunication
Database Management Systems (DBMS) are essential to the telecommunications industry
because they manage enormous volumes of data on billing, customer information, and network
optimization.
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.
o The database also has no idea about any other user beyond the application.
o The three schema architecture is also called ANSI/SPARC architecture or three-level
architecture.
o The 3-Tier architecture is used in case of large web application.
o The three schema architecture contains three-levels. It breaks the database down into three
different categories.

The three-schema architecture is as follows:

o Mapping is used to transform the request


and response between various database
levels of architecture.
o Mapping is not good for small DBMS
because it takes more time.
o In External / Conceptual mapping, it is
necessary to transform the request from
external level to conceptual schema.
o In Conceptual / Internal mapping, DBMS transform the request from the conceptual
to internal level.
Objectives of Three schema Architecture
The main objective of three level architecture is to enable multiple users to access the same
data with a personalized view while storing the underlying data only once. Thus it separates
the user's view from the physical structure of the database. This separation is desirable for
the following reasons:
o Different users need different views of the same data.

o The approach in which a particular user needs to see the data may change over time.

o The users of the database should not worry about the physical implementation and

internal workings of the database such as data compression and encryption


techniques, hashing, optimization of the internal structures etc.
o All users should be able to access the same data according to their requirements.

o DBA should be able to change the conceptual structure of the database without

affecting the user's


o Internal structure of the database should be unaffected by changes to physical aspects

of the storage.
Views of DBMS:
1. Internal Level
o The internal level has an internal schema which

describes the physical storage structure of the


database.
o The internal schema is also known as a physical

schema.
o It uses the physical data model. It is used to

define that how the data will be stored in a block.


o The physical level is used to describe complex low-level data structures in detail.

The internal level is generally concerned with the following activities:


o Storage space allocations.

For Example: B-Trees, Hashing etc.


o Access paths.

For Example: Specification of primary and secondary keys, indexes, pointers and
sequencing.
o Data compression and encryption techniques.

o Optimization of internal structures.

o Representation of stored fields.


2. Conceptual Level

o The conceptual schema describes the design of a


database at the conceptual level. Conceptual level
is also known as logical level.
o The conceptual schema describes the structure of
the whole database.
o The conceptual level describes what data are to be stored in the database and also
describes what relationship exists among those data.
o In the conceptual level, internal details such as an implementation of the data structure
are hidden.
o Programmers and database administrators work at this level.
3. External Level

o At the external level, a database contains several schemas that sometimes called as
subschema. The subschema is used to describe the different view of the database.
o An external schema is also known as view schema.
o Each view schema describes the database part that a particular user group is interested
and hides the remaining database from that user group.
o The view schema describes the end user interaction with database systems.
Mapping between Views
The three levels of DBMS architecture don't exist independently of each other. There must
be correspondence between the three levels i.e. how they actually correspond with each
other. DBMS is responsible for correspondence between the three types of schema. This
correspondence is called Mapping.

There are basically two types of mapping in the database architecture:


1. Conceptual/ Internal Mapping
The Conceptual/ Internal Mapping lies between the conceptual level and the internal level.
Its role is to define the correspondence between the records and fields of the conceptual
level and files and data structures of the internal level.

2. External/ Conceptual Mapping

The external/Conceptual Mapping lies between the external level and the Conceptual level.
Its role is to define the correspondence between a particular external and the conceptual
view.
Data Abstraction and Data Independence
Database systems comprise complex data structures. In order to make the system
efficient in terms of retrieval of data, and reduce complexity in terms of usability of users,
developers use abstraction i.e. hide irrelevant details from the users. This approach
simplifies database design.
Level of Abstraction in a DBMS
There are mainly 3 levels of data abstraction:
• Physical or Internal Level

• Logical or Conceptual Level

• View or External Level

Physical or Internal Level


This is the lowest level of data abstraction. It tells us how the data is actually stored in
memory. Access methods like sequential or random access and file organization
methods like B+ trees and hashing are used for the same. Usability, size of memory, and
the number of times the records are factors that we need to know while designing the
database.
Suppose we need to store the details of an employee. Blocks of storage and the amount
of memory used for these purposes are kept hidden from the user.
Logical or Conceptual Level
This level comprises the information that is actually stored in the database in the form of
tables. It also stores the relationship among the data entities in relatively simple
structures. At this level, the information available to the user at the view level is
unknown.
We can store the various attributes of an employee and relationships, e.g. with the
manager can also be stored.
View or External Level
This is the highest level of abstraction. Only a part of the actual database is viewed by the
users. This level exists to ease the accessibility of the database by an individual user.
Users view data in the form of rows and columns. Tables and relations are used to store
data. Multiple views of the same database may exist. Users can just view the data and
interact with the database, storage and implementation details are hidden from them.
Example: In case of storing customer data,
• Physical level – it will contains block of storages (bytes,GB,TB,etc)

• Logical level – it will contain the fields and the attributes of data.

• View level – it works with CLI or GUI access of database


Data Abstraction
The main purpose of data abstraction is to achieve data independence in order to save the
time and cost required when the database is modified or altered.
Data Independence
Data Independence is mainly defined as a property of DBMS that helps you to change
the database schema at one level of a system without requiring to change the schema at
the next level.
It helps to keep the data separated from all
program that makes use of it.
We have namely two levels of data independence
arising from these levels of abstraction:
• Physical level data independence

• Logical level data independence

1. Physical Level Data Independence

It refers to the characteristic of being able to modify


the physical schema without any alterations to the
conceptual or logical schema, done for optimization purposes, e.g., the Conceptual
structure of the database would not be affected by any change in storage size of the
database system server. Changing from sequential to random access files is one such
example. These alterations or modifications to the physical structure may include:
• Utilizing new storage devices.

• Modifying data structures used for storage.

• Altering indexes or using alternative file organization techniques etc.

2. Logical Level Data Independence


It refers characteristic of being able to modify the logical schema without affecting the
external schema or application program. The user view of the data would not be affected
by any changes to the conceptual view of the data. These changes may include insertion
or deletion of attributes, altering table structures entities or relationships to the logical
schema, etc.
Database Languages
1. Data Definition Language 3. Data Control Language
2. Data Manipulation Language 4. Transactional Control Language
1. Data Definition Language
DDL is the short name for Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.
• CREATE: to create a database and its objects like (table, index, views, store procedure,

function, and triggers)


• ALTER: alters the structure of the existing database

• DROP: delete objects from the database

• TRUNCATE: remove all records from a table, including all spaces allocated for the records

are removed
• COMMENT: add comments to the data dictionary

• RENAME: rename an object

2. Data Manipulation Language


DML is the short name for Data Manipulation Language which deals with data manipulation and
includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE, etc., and it is
used to store, modify, retrieve, delete and update data in a database.
• SELECT: retrieve data from a database
• INSERT: insert data into a table
• UPDATE: updates existing data within a table

• DELETE: Delete all records from a database table

• MERGE: UPSERT operation (insert or update)

• CALL: call a PL/SQL or Java subprogram

• EXPLAIN PLAN: interpretation of the data access path

• LOCK TABLE: concurrency Control

3. Data Control Language


DCL is short for Data Control Language which acts as an access specifier to the
database.(basically to grant and revoke permissions to users in the database
• GRANT: grant permissions to the user for running DML(SELECT, INSERT, DELETE,…)

commands on the table


• REVOKE: revoke permissions to the user for running DML(SELECT, INSERT, DELETE,…)

command on the specified table


4. Transactional Control Language
TCL is short for Transactional Control Language, which acts as a manager for all types of
transactional data and all transactions. Some of the commands of TCL are
• Roll Back: Used to cancel or Undo changes made in the database

• Commit: It is used to apply or save changes in the database

• Save Point: It is used to save the data on a temporary basis in the database
A. SQL DDL
I. SQL CREATE Table
In RDBMS, Database tables are used to store the data in the form of some structures (fields and records).
Here, a field is a column defining the type of data to be stored in a table and record is a row containing
actual data. In simple words, we can say a Table is a combination of rows and columns.

SQL provides various queries to interact with the data in a convenient way. We can use SQL statements to
create and delete tables, inserting, updating and deleting data in these tables.
1. The SQL CREATE TABLE Statement

SQL provides the CREATE TABLE statement to create a new table in a given database. An SQL query to
create a table must define the structure of a table. The structure consists of the name of a table and names of
columns in the table with each column's data type. Note that each table must be uniquely named in a
database.
Syntax

CREATE TABLE statement is used to create a new table in a database. −


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
Here are the key points-
• CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want
to create a new table. The unique name or identifier for the table follows the CREATE TABLE
statement.
• The column parameters (e.g. column1, column2, column3, etc.) specify the names of the columns of

the table.
• The datatype parameter specifies the type of data the column can hold (e.g. integer, varchar, string,

etc.).
• PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE

values, and cannot contain NULL values.


Example: Creating Table in SQL
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Here are the key points-


• The following code block is an example, which creates a CUSTOMERS table with column name ID,
NAME, AGE, ADDRESS and, SALARY and ID as a primary key.
• NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this
table.
Verification

Once your table is created, you can check if it has been created successfully or not. You can use SQL DESC
table_name command to list down the description of the table as follows:

DESC CUSTOMERS;

This will display the structure of the table created: column names, their respective data types, constraints (if
any) etc.

Field Type Null Key Default Extra

ID int(11) NO PRI NULL

NAME varchar(20) NO NULL

AGE int(11) NO NULL

ADDRESS char(25) YES NULL

SALARY decimal(18,2) YES NULL

Now, you have CUSTOMERS table available in your database which you can use to store the required
information related to customers.
2. SQL CREATE TABLE IF NOT EXISTS

Consider a situation where you will try to create a table which already exists, in such situation MySQL will
throw the following error.
ERROR 1050 (42S01): Table 'CUSTOMERS' already exists

So to avoid such error we can use SQL command CREATE TABLE IF NOT EXISTS to create a table.
Syntax

Following is the basic syntax of a CREATE TABLE IF NOT EXISTS statement −


CREATE TABLE IF NOT EXISTS table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
Example: Creating Table if Not Exists

The following SQL command will create the CUSTOMERS table only when there is no table exists with the
same name otherwise it will exit without any error.
CREATE TABLE IF NOT EXISTS CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
3. Creating a Table from an Existing Table

Instead of creating a new table every time, one can also copy an existing table and its contents including its
structure, into a new table. This can be done using a combination of the CREATE TABLE statement and the
SELECT statement. Since its structure is copied, the new table will have the same column definitions as the
original table. Furthermore, the new table would be populated using the existing values from the old table.
Syntax

The basic syntax for creating a table from another table is as follows −
CREATE TABLE NEW_TABLE_NAME AS
SELECT [column1, column2...columnN]
FROM EXISTING_TABLE_NAME
WHERE Condition;

Here, column1, column2... are the fields of the existing table and the same would be used to create fields of
the new table.
Example: Creating Table from an Existing Table

Following is an example, which would create a table SALARY using the CUSTOMERS table and having
the fields customer ID and customer SALARY −
CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;
This will create a new table SALARY which will have the following structure −
Field Type Null Key Default Extra
ID int(11) NO PRI NULL
SALARY decimal(18,2) YES NULL

II. SQL ALTER Table – ADD, DROP, MODIFY


The SQL ALTER TABLE command is a part of Data Definition Language (DDL) and modifies the structure of a
table. The ALTER TABLE command can add or delete columns, create or destroy indexes, change the type of
existing columns, or rename columns or the table itself.
The ALTER TABLE command can also change characteristics of a table such as the storage engine used for
the table. We will make use of the following table in our examples

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00
Syntax: Following is the basic syntax of an ALTER TABLE command −
ALTER TABLE table_name [alter_option ...];
Where, the alter_option depends on the type of operation to be performed on a table. This article will
discuss such important operations one by one.

1. ALTER TABLE − ADD Column


If you need to add a new column to a table, you should use the ADD COLUMN option along with ALTER
TABLE statement as shown below −
ALTER TABLE table_name ADD column_name datatype;
Example:
Following is the example to ADD a New Column to an existing table −
ALTER TABLE CUSTOMERS ADD GENDER char(1);
Output:
Executing the query above will produce the following output −
Query OK, 0 rows affected (0.09 sec)
Records: 0 Duplicates: 0 Warnings: 0
Verification:
To verify whether the CUSTOMERS table is altered by adding a new column GENDER, use the SELECT
statement to retrieve the records of the table −
SELECT * FROM CUSTOMERS;

Now, the CUSTOMERS table will be displayed as follows −


ID NAME AGE ADDRESS SALARY GENDER

1 Ramesh 32 Ahmedabad 2000.00 NULL

2 Khilan 25 Delhi 1500.00 NULL

3 Kaushik 23 Kota 2000.00 NULL

4 Chaitali 25 Mumbai 6500.00 NULL

5 Hardik 27 Bhopal 8500.00 NULL

6 Komal 22 Hyderabad 4500.00 NULL

7 Muffy 24 Indore 10000.00 NULL

2. ALTER TABLE − DROP COLUMN


If you need to drop an existing column from a table, you should use the DROP COLUMN option along
with ALTER TABLE statement as shown below.
ALTER TABLE table_name DROP COLUMN column_name;
Example: Following is the example to DROP GENDER column from the existing table.
ALTER TABLE CUSTOMERS DROP COLUMN GENDER;
Output: Executing the query above will produce the following output −
Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
Verification:
To verify whether the CUSTOMERS table is altered by dropping an existing column GENDER, use the
SELECT statement to retrieve the records of the table −
SELECT * FROM CUSTOMERS;

Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement.

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

3. ALTER TABLE − ADD INDEX


You can add index to an existing column of a table using the ADD INDEX statement along with the ALTER
statement −
ALTER TABLE table_name
ADD INDEX index_name [index_type]
Example: Following query adds an index on the column NAME of CUSTOMERS table −
ALTER TABLE CUSTOMERS ADD INDEX name_index (NAME);
Output: The output will be displayed as −
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0

4. ALTER TABLE − DROP INDEX


You can drop an existing index from a table using the DROP INDEX statement along with the ALTER
statement −
ALTER TABLE table_name DROP INDEX index_name;
Example:
Following query adds an index on the column NAME of CUSTOMERS table −
ALTER TABLE CUSTOMERS DROP INDEX name_index;
Output:
The output will be displayed as −
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0

5. ALTER TABLE − ADD PRIMARY KEY


Following is the syntax to add a primary key in an existing table of a database −
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
PRIMARY KEY (column1, column2...);
Example:
Before we add a primary key to an existing table, first let's create a new table called EMPLOYEES as
follows:
CREATE TABLE EMPLOYEES(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2)
);
Following query adds primary key constraint on the column ID of EMPLOYEES table −
ALTER TABLE EMPLOYEES
ADD CONSTRAINT MyPrimaryKey
PRIMARY KEY(ID);
Output:
This will produce the following output −
Query OK, 0 rows affected, 1 warning (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 1
Verification
To verify the above query if you describe the table using the DESC EMPLOYEES command −
DESC EMPLOYEES;
This will display the structure of the table created: column names, their respective data types,
constraints (if any) etc.
Field Type Null Key Default Extra

ID int(11) NO PRI NULL

NAME varchar(20) NO NULL

AGE int(11) NO NULL

ADDRESS char(25) YES NULL

SALARY decimal(18,2) YES NULL

6. ALTER TABLE − DROP PRIMARY KEY


Following is the syntax to delete a primary key from an existing table of a database −
ALTER TABLE table_name DROP PRIMARY KEY;
Example:
Following query deletes primary key constraint from the column ID of EMPLOYEES table −

ALTER TABLE EMPLOYEES DROP PRIMARY KEY;


Output:
This will produce the following output −
Query OK, 0 rows affected, 1 warning (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 1
7. ALTER TABLE − ADD CONSTRAINT
Following is the syntax to add a unique constraint to a column of an existing table −
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
UNIQUE(column1, column2...);
Example:
Following query adds UNIQUE constraint to the table CUSTOMERS −
ALTER TABLE EMPLOYEES ADD CONSTRAINT CONST UNIQUE(NAME);
Output:
This will produce the following output −
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0

8. ALTER TABLE − DROP CONSTRAINT


Following is the syntax to drop a unique constraint from an existing table −
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
Example:
Following query adds UNIQUE constraint to the table CUSTOMERS −
ALTER TABLE EMPLOYEES DROP CONSTRAINT CONST;
Output:
This will produce the following output −
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0

9. ALTER TABLE − RENAME COLUMN


Following is the syntax to rename a column name of an existing table −
ALTER TABLE table_name
RENAME COLUMN old_column_name to new_column_name;
Example:
Following query renames NAME column in table CUSTOMERS −
ALTER TABLE CUSTOMERS RENAME COLUMN name to full_name;
Output:
This will produce the following output −
Query OK, 0 rows affected (0.002 sec)
Records: 0 Duplicates: 0 Warnings: 0

10. ALTER TABLE − MODIFY DATATYPE


Following is the syntax to change the data type of any column in MySQL, MS Server and Oracle.

Syntax:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
Example:
Following query modifies datatype of SALARY column in MySQL CUSTOMERS table −
ALTER TABLE CUSTOMERS MODIFY COLUMN ID DECIMAL(18, 4);
Output:
This will produce the following output −
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0

III. SQL DROP


The SQL DROP Table Statement

The SQL DROP TABLE statement is a Data Definition Language (DDL) command that is used to remove a
table's definition, and its data, indexes, triggers, constraints and permission specifications (if any).

Note − You should be very careful while using this command because once a table is deleted then all the
information available in that table will also be lost forever.

If the table is partitioned, the statement removes the table definition, all its partitions, all data stored in
those partitions, and all partition definitions.
To drop a table in a database, one must require ALTER permission on the said table and CONTROL
permissions on the table schema.
Even though it is a data definition language command, it is different from TRUNCATE TABLE statement as
the DROP statement completely frees the table from the memory.
DROP TABLE causes an implicit commit, except when used with the TEMPORARY keyword.

Syntax:

The basic syntax of this DROP TABLE statement is as follows −


DROP TABLE table_name;
Example:

Assume we have created a table named CUSTOMERS using the CREATE TABLE statement as shown below −
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Let us first verify the CUSTOMERS table using the DESC command then we will delete it from the database

DESC Table
If the table is created successfully the DESC command displays the structure of the table as shown below −

Field Type Null Key Default Extra

ID int(11) NO PRI NULL

NAME varchar(20) NO NULL

AGE int(11) NO NULL

ADDRESS char(25) YES NULL

SALARY decimal(18,2) YES NULL

This means that the CUSTOMERS table is available in the database, so let us now drop it as shown below.
DROP TABLE CUSTOMERS;
Output
The output is displayed as follows −
Query OK, 0 rows affected (0.001 sec)
Verification
Now, to verify if the table is actually dropped, you can use the DESC CUSTOMERS command as shown −
DESC CUSTOMERS;
Following error is displayed −
ERROR 1146 (42S02): Table 'tutorials.CUSTOMERS' doesn't exist
IV. SQL TRUNCATE
SQL provides command to TRUNCATE a table completely in one go instead of deleting table records one by
one which will be very time consuming and cumbersome process.
The SQL TRUNCATE TABLE Statement
The SQL TRUNCATE TABLE command is used to empty a table. This command is a sequence of DROP TABLE
and CREATE TABLE statements and requires the DROP privilege.
You can also use DROP TABLE command to delete a table but it will remove the complete table structure
from the database and you would need to re-create this table once again if you wish you store some data
again.
Syntax:
The basic syntax of a TRUNCATE TABLE command is as follows.
TRUNCATE TABLE table_name;
Example:
First let's create a table CUSTOMERS which can store the personal details of customers including their
name, age, address and salary etc. as shown below:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now insert values into this table using the INSERT statement as follows −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );
The table will be created as follows −
ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00


Following SQL TRUNCATE TABLE CUSTOMER statement will remove all the records of the CUSTOMERS table

TRUNCATE TABLE CUSTOMERS;
Verification:
Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the
code block below −
SELECT * FROM CUSTOMERS;
Output:
Following will be the output −
Empty set (0.00 sec)

TRUNCATE vs DELETE
Even though the TRUNCATE and DELETE commands work similar logically, there are some major
differences that exist between them. They are detailed in the table below.
DELETE TRUNCATE

The DELETE command in SQL removes one or more


SQL's TRUNCATE command is used to remove all of the rows from
rows from a table based on the conditions specified in a
a table, regardless of whether or not any conditions are met.
WHERE Clause.
It is a DML(Data Manipulation Language) command. It is a DDL(Data Definition Language) command.
There is a need to make a manual COMMIT after making
When you use the TRUNCATE command, the modifications made to
changes to the DELETE command, for the modifications
the table are committed automatically.
to be committed.
It deletes rows one at a time and applies same criteria to
It removes all of the information in one go.
each deletion.
The WHERE clause serves as the condition in this case. The WHERE Clause is not available.
TRUNCATE utilizes a table lock, which locks the pages so they
All rows are locked after deletion.
cannot be deleted.
It makes a record of each and every transaction in the log The only activity recorded is the deallocation of the pages on which
file. the data is stored.
It consumes a greater amount of transaction space
It takes comparatively less amount of transaction space.
compared to TRUNCATE command.
If there is an identity column, the table identity is not reset
It returns the table identity to a value it was given as a seed.
to the value it had when the table was created.
It requires authorization to delete. It requires table alter permission.
When it comes to large databases, it is much slower. It is much faster.
TRUNCATE vs DROP
Unlike TRUNCATE that resets the table structure, DROP command completely frees the table space from
the memory. They are both Data Definition Language (DDL) operations as they interact with the definitions
of database objects; which allows the database to automatically commit once these commands are
executed with no chance to roll back.
However, there are still some differences exist between these two commands, which have been
summarized in the following table −
DROP TRUNCATE

The DROP command in SQL removes an entire table The TRUNCATE command is used to remove all of
from a database including its definition, indexes, the rows from a table, regardless of whether or not
constraints, data etc. any conditions are met and resets the table definition.
It is also a DDL(Data Definition Language)
It is a DDL(Data Definition Language) command.
command.
The table space is completely freed from the memory. The table still exists in the memory.
All the integrity constraints are removed. The integrity constraints still exist in the table.
Requires ALTER and CONTROL permissions on the
Only requires the ALTER permissions to truncate
table schema and table respectively, to be able to
the table.
perform this command.
DROP command is much slower than TRUNCATE TRUNCATE command is faster than both DROP
but faster than DELETE. and DELETE commands.

V. SQL Comments
Comments are used to explain sections of SQL statements or to prevent SQL statements from being
executed. As is any programming language comments matter a lot in SQL also. In this set, we will learn
about writing comments in any SQL snippet.
Comments can be written in the following three formats:
1. Single-line comments
2. Multi-line comments
3. In-line comments
1. Single Line Comments
Comments starting and ending in a single line are considered single-line comments. A line starting with ‘–‘ is
a comment and will not be executed.
Syntax:
— single line comment
— another comment
SELECT * FROM Customers;
Let’s see an example in which we have one table name Customers in which we are fetching all the data
records.
Query:
SELECT * FROM customers;
-- This is a comment that explains
the purpose of the query.
2. Multi-Line Comments
Comments starting in one line and ending in different lines are considered as multi-line comments.
A line starting with ‘/*’ is considered as starting point of the comment and is terminated when ‘*/’ is
encountered.
Syntax:
/* multi line comment
another comment */
SELECT * FROM Customers;
Let’s consider that we want to fetch order_date with the year 2022.
Query:
/*
This is a multi-line comment that explains
the purpose of the query below.
The query selects all the orders from the orders
table that were placed in the year 2022.
*/
SELECT * FROM orders WHERE YEAR(order_date) = 2022;
3. In-Line Comments
In-line comments are an extension of multi-line comments, comments can be stated in between the
statements and are enclosed in between ‘/*’ and ‘*/’.
Syntax:
SELECT * FROM /* Customers; */
Let’s Suppose we have on a table with name orders and we are fetching customer_name.
Query:
SELECT customer_name,
/* This column contains the name of
the customer / order_date /
This column contains the date the
order was placed */ FROM orders;

More Examples:
There are a few more examples of Multiline comments and inline comments.
Multi line comment ->
/* SELECT * FROM Students;
SELECT * FROM STUDENT_DETAILS;
SELECT * FROM Orders; */
SELECT * FROM Articles;

In line comment ->


SELECT * FROM Students;
SELECT * FROM /* STUDENT_DETAILS;
SELECT * FROM Orders;
SELECT * FROM */ Articles;
VI. ALTER (RENAME) Table
Sometimes we may want to rename our table to give it a more relevant name. For this purpose, we can
use ALTER TABLE to rename the name of the table. SQL ALTER TABLE is a command used to modify the
structure of an existing table in a database. Here we will discuss Alter Command in SQL in detail.
Alter in SQL
Here we are discussing the syntax of Alter Command in different Databases like MYSQL, MariaDB, Oracle,
etc. Let’s proceed with Syntax first.

Syntax:
ALTER TABLE table_name
RENAME TO new_table_name;
Columns can also be given a new name with the use of ALTER TABLE.

Query:
CREATE TABLE Student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(50),
phone VARCHAR(20)
);
Let’s insert some data and then perform ALTER operation to understand better bout alter command.

INSERT the data in Student Table:


INSERT INTO Student (id, name, age, email, phone)
VALUES
(1, 'Amit', 20, '[email protected]', '9999999999'),
(2, 'Rahul', 22, '[email protected]', '8888888888'),
(3, 'Priya', 21, '[email protected]', '7777777777'),
(4, 'Sonia', 23, '[email protected]', '6666666666'),
(5, 'Kiran', 19, '[email protected]', '5555555555');
Output:

Student Table

Example 1:
Change the name of column name to FIRST_NAME in table Student.

Syntax:
ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;
Query:
ALTER TABLE Student RENAME name TO FIRST_NAME;
Output:

Output

Example 2:
Change the name of the table Student to Student_Details.

Query:
ALTER TABLE Student RENAME TO Student_Details;
Output:
Student_Details Table

Student_Details table
To Add a New Column with ALTER TABLE
To add a new column to the existing table, we first need to select the table with ALTER TABLE command
table_name, and then we will write the name of the new column and its datatype with ADD column_name
datatype. Let’s have a look below to understand better.
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Query:
ALTER TABLE Student ADD marks INT;
Output:

output

B. SQL DML
I. SQL SELECT
a. The SQL SELECT Statement
The SQL SELECT Statement is used to fetch the data from a database table which returns this data in the form
of a table. These tables are called result-sets.
CLAUSES and OPERATORS available in SQL can be used with the SELECT statement in order to retrieve the
filtered records of a database table.
Syntax:
The basic syntax of the SELECT Query is as follows −
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to fetch all
the columns available in a table, then you can use the following syntax −
SELECT * FROM table_name;
Example:
Assume we have created a table named CUSTOMERS using the CREATE TABLE statement as shown below −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, insert values into this table using the INSERT statement as follows −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );
The table will be created as −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00
Retrieving Selected Fields/Columns
The following statement fetches the ID, Name and Salary fields of the records available in CUSTOMERS
table.
SELECT ID, NAME, SALARY FROM CUSTOMERS;

Output:
The above query would produce the following table −
ID NAME Salary
1 Ramesh 2000.00
2 Khilan 1500.00
3 Kaushik 2000.00
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00
Retrieving All Fields/Columns
If you want to fetch all the fields of the CUSTOMERS table, then you should use the query of SELECT
statement with an Asterisk (*) instead of the column names, as shown below −
SELECT * FROM CUSTOMERS;
Output:
The resultant table will be −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00
b. Computing Using SELECT
The SQL SELECT statement can also be used to retrieve the results of various mathematical computations in
the form of a table. In such cases, you do not need to specify any database table in the statement.

Following is the syntax to do so −


SELECT mathematical_expression;
Example:
Following is an example which multiply two given numbers using SQL statement.
SELECT 56*65;
The query above produces the following output −
56*65

3640
c. Aliasing a Column in SELECT Statement
Whenever a column name in a table is too difficult to read and understand, SQL provides a method to alias
this column name into another understandable and relative name. This is done using the AS keyword. You
can use the AS keyword in a SELECT statement to display the column names of a table as an alias name.
Following is the syntax to do so −
SELECT column_name
AS alias_name
FROM table_name;
You can also use an alias to display SELECT expressions with the same syntax; you should use a
mathematical statement instead of column_name.
Example:
In the example below, we are trying to retrieve customer details NAME and AGE in a single column of the
resultant table using the concat() expression and aliasing the column as DETAILS along with the customer
addresses from the CUSTOMERS table. This will be done using SELECT statement in the following query −
SELECT CONCAT(NAME,' ',AGE)
AS DETAILS, ADDRESS
FROM CUSTOMERS ORDER BY NAME;
The query above produces the following output −
DETAILS ADDRESS
Chaitali 25 Mumbai
Hardik 27 Bhopal
Kaushik 23 Kota
Khilan 25 Delhi
Komal 22 Hyderabad
Muffy 24 Indore
Ramesh 32 Ahmedabad
d. The SQL WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
Example: Select all customers from Mexico:
SELECT * FROM Customers
WHERE Country='Mexico';
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!

Operators in The WHERE Clause

You can use other operators than the = operator to filter the search.

Example: Select all customers with a CustomerID greater than 80:


SELECT * FROM Customers
WHERE CustomerID > 80;

The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than


>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

II. SQL INSERT INTO


The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax:

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:


INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the same
order as the columns in the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);

Demo Database:
Below is a selection from the Customers table used in the examples:

CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

INSERT INTO Example:


The following SQL statement inserts a new record in the "Customers" table:

Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway

Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an auto-increment field and will be generated automatically when a
new record is inserted into the table.

Insert Data Only in Specified Columns:


It is also possible to only insert data in specific columns.

The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):

Example:
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country


89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

92 Cardinal null null Stavanger null Norway

Insert Multiple Rows


It is also possible to insert multiple rows in one statement.

To insert multiple rows of data, we use the same INSERT INTO statement, but with multiple values:

Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway'),
('Tasty Tee', 'Finn Egan', 'Streetroad 19B', 'Liverpool', 'L1 0AA', 'UK');

Make sure you separate each set of values with a comma ,.

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway

93 Greasy Burger Per Olsen Gateveien 15 Sandnes 4306 Norway

94 Tasty Tee Finn Egan Streetroad 19B Liverpool L1 0AA UK

III. SQL UPDATE


The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If
you omit the WHERE clause, all records in the table will be updated!

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.
Example:
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y helados Constitución 2222

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

UPDATE Multiple Records

It is the WHERE clause that determines how many records will be updated.

The following SQL statement will update the ContactName to "Juan" for all records where
country is "Mexico":
Example:
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany

2 Ana Trujillo Emparedados Juan Avda. de la México D.F. 05021 Mexico


y helados Constitución 2222

3 Antonio Moreno Taquería Juan Mataderos 2312 México D.F. 05023 Mexico

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berguvsvägen 8 Luleå S-958 22 Sweden


Berglund

Update Warning!Be careful when updating records. If you omit the WHERE clause, ALL records will be
updated!

Example:
UPDATE Customers
SET ContactName='Juan';

The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Juan Obere Str. 57 Frankfurt 12209 Germany

2 Ana Trujillo Emparedados Juan Avda. de la México D.F. 05021 Mexico


y helados Constitución 2222

3 Antonio Moreno Juan Mataderos 2312 México D.F. 05023 Mexico


Taquería

4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Juan Berguvsvägen 8 Luleå S-958 22 Sweden

IV. SQL DELETE


The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit
the WHERE clause, all records in the table will be deleted!
SQL DELETE Example

The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

Example:
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la México D.F. 05021 Mexico
helados Constitución 2222

3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

Delete All Records

It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
Example:
DELETE FROM Customers;

Delete a Table

To delete the table completely, use the DROP TABLE statement:

Example: Remove the Customers table:


DROP TABLE Customers;

You might also like