DBMS Notes
DBMS Notes
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
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?
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.
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
o DBA should be able to change the conceptual structure of the database without
of the storage.
Views of DBMS:
1. Internal Level
o The internal level has an internal schema which
schema.
o It uses the physical data model. It is used to
For Example: Specification of primary and secondary keys, indexes, pointers and
sequencing.
o Data compression and encryption techniques.
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.
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 level – it will contain the fields and the attributes of data.
• TRUNCATE: remove all records from a table, including all spaces allocated for the records
are removed
• COMMENT: add comments to the data dictionary
• 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
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
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.
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
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
Now, the CUSTOMERS table is changed and following would be the output from the SELECT statement.
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
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:
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 −
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
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 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;
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.
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.
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.!
You can use other operators than the = operator to filter the search.
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
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:
89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B Seattle 98128 USA
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:
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
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.
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:
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');
The selection from the "Customers" table will now look like this:
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
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:
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
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:
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
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
4 Around the Horn Juan 120 Hanover Sq. London WA1 1DP UK
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';
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
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