You are on page 1of 76

Overview of database management:

Database is a collection of related data and data is a collection of facts and figures that can be processed to produce
information.

Mostly data represents recordable facts. Data aids in producing information, which is based on facts. For example, if
we have data about marks obtained by all students, we can then conclude about toppers and average marks.

A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and
produce information.

Characteristics

Traditionally, data was organized in file formats. DBMS was a new concept then, and all the research was done to
make it overcome the deficiencies in traditional style of data management. A modern DBMS has the following
characteristics −

● Real-world entity − A modern DBMS is more realistic and uses real-world entities to design its architecture.
It uses the behavior and attributes too. For example, a school database may use students as an entity and
their age as an attribute.
● Relation-based tables − DBMS allows entities and relations among them to form tables. A user can
understand the architecture of a database just by looking at the table names.
● Isolation of data and application − A database system is entirely different than its data. A database is an
active entity, whereas data is said to be passive, on which the database works and organizes. DBMS also
stores metadata, which is data about data, to ease its own process.
● Less redundancy − DBMS follows the rules of normalization, which splits a relation when any of its
attributes is having redundancy in values. Normalization is a mathematically rich and scientific process that
reduces data redundancy.
● Consistency − Consistency is a state where every relation in a database remains consistent. There exist
methods and techniques, which can detect attempt of leaving database in inconsistent state. A DBMS can
provide greater consistency as compared to earlier forms of data storing applications like file-processing
systems.
● Query Language − DBMS is equipped with query language, which makes it more efficient to retrieve and
manipulate data. A user can apply as many and as different filtering options as required to retrieve a set of
data. Traditionally it was not possible where file-processing system was used.
● ACID Properties − DBMS follows the concepts of Atomicity, Consistency, Isolation, and Durability (normally
shortened as ACID). These concepts are applied on transactions, which manipulate data in a database.
ACID properties help the database stay healthy in multi-transactional environments and in case of failure.
● Multiuser and Concurrent Access − DBMS supports multi-user environment and allows them to access
and manipulate data in parallel. Though there are restrictions on transactions when users attempt to handle
the same data item, but users are always unaware of them.
● Multiple views − DBMS offers multiple views for different users. A user who is in the Sales department will
have a different view of database than a person working in the Production department. This feature enables
the users to have a concentrate view of the database according to their requirements.
● Security − Features like multiple views offer security to some extent where users are unable to access data
of other users and departments. DBMS offers methods to impose constraints while entering data into the
database and retrieving the same at a later stage. DBMS offers many different levels of security features,
which enables multiple users to have different views with different features. For example, a user in the Sales
department cannot see the data that belongs to the Purchase department. Additionally, it can also be
managed how much data of the Sales department should be displayed to the user. Since a DBMS is not
saved on the disk as traditional file systems, it is very hard for miscreants to break the code.

Users

A typical DBMS has users with different rights and permissions who use it for different purposes. Some users retrieve
data and some back it up. The users of a DBMS can be broadly categorized as follows −
● Administrators − Administrators maintain the DBMS and are responsible for administrating the database.
They are responsible to look after its usage and by whom it should be used. They create access profiles for
users and apply limitations to maintain isolation and force security. Administrators also look after DBMS
resources like system license, required tools, and other software and hardware related maintenance.
● Designers − Designers are the group of people who actually work on the designing part of the database.
They keep a close watch on what data should be kept and in what format. They identify and design the
whole set of entities, relations, constraints, and views.
● End Users − End users are those who actually reap the benefits of having a DBMS. End users can range
from simple viewers who pay attention to the logs or market rates to sophisticated users such as business
analysts.

Advantages of Database Management System


In contrast with the File Based Data Management System, Dbms has numerous benefits. We are putting light on some of the considerable benefits
here–

1. Data Integrity
Data integrity means data is consistent and accurate in the database. It is essential as there are multiple databases in DBMS. All these databases
contain data which is visible to multiple users. Therefore, it is essential to ensure that data is consistent and correct in all databases for all users.

2. Data Security
Data security is a vital concept in a database. Only users authorized must be allowed to access the database and their identity must be authenticated
using username and password. Unauthorized users shouldn’t be allowed to access the database under any circumstances as it violets the integrity
constraints.

A DBMS provides a better platform for data privacy thus helping companies to offer an improved data security.

3. Better data integration


Due to the database management system, we have access to well managed and synchronized form of data making it easy to handle. It also gives an
integrated view of how a particular organization is working and keeps track of how one segment of the company affects another segment.

4. Minimized Data Inconsistency


Data inconsistency occurs between files when various versions of the same data appear in different places. Data consistency is ensured in the
database; there is no data redundancy. Besides, any database changes are immediately reflected by all users, and there is no data inconsistency.

5. Faster Data Access


The database management system helps the users to produce quick answers to queries making data accessing accurate and faster.
For any given dataset, dbms can help in solving insightful financial queries like:

1. What is the bonus given to every salesperson in the last two months?

2. How many customers have a credit score or more than 800?

3. What is last year’s profit?

4. Better decision making


Due to DBMS, we now have improved and managed data accessing because of which we can generate better quality information which can hence
make better decisions.
Better quality ultimately improves validity, accuracy and time it takes to read data. It doesn’t guarantee data quality; it provides a framework to make it
easy to enhance data quality.

5. Simplicity
DBMS allows us to understand data better with a clear and simple logical view. With dbms, many operations like deletion, insertion or creation of file or
data, are easy to implement.

6. Recovery and Backup


DBMS automatically takes care of recovery and backup. The users are not required to take periodical backup as this is taken care of by DBMS.
Besides, it also restores a database after a system failure or crash to prevent its previous condition.

7. Increased end-user productivity


The available data transform into helpful information with the help of combination tools. It helps end users make better, informative and quick decisions
that can make the difference between success and failure in the global economy.

Additionally, today DBMS is also serving as the backbone of several advanced Technology practices like Data Science, Data Modelling and Machine
Learning. So, if you are someone looking for a career in analytics or automation then dbms is a must have skill for you.

ER (Entity Relationship) Diagram in DBMS


o ER model stands for an Entity-Relationship model. It is a high-level data model. This model is used to define the data elements and
relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and easy to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an entity-relationship diagram.

For example, Suppose we design a school database. In this database, the student will be an entity with attributes like address, name, id, age, etc.
The address can be another entity with attributes like city, street name, pin code, etc and there will be a relationship between them.

Component of ER Diagram
1. Entity:
An entity may be any object, class, person or place. In the ER diagram, an entity can be represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can be taken as an entity.

a. Weak Entity

An entity that depends on another entity called a weak entity. The weak entity doesn't contain any key attribute of its own. The weak entity is
represented by a double rectangle.
2. Attribute
The attribute is used to describe the property of an entity. Eclipse is used to represent an attribute.

For example, id, age, contact number, name, etc. can be attributes of a student.

a. Key Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a primary key. The key attribute is represented by an
ellipse with the text underlined.
b. Composite Attribute

An attribute that composed of many other attributes is known as a composite attribute. The composite attribute is represented by an ellipse, and
those ellipses are connected with an ellipse.

c. Multivalued Attribute

An attribute can have more than one value. These attributes are known as a multivalued attribute. The double oval is used to represent
multivalued attribute.

For example, a student can have more than one phone number.
d. Derived Attribute

An attribute that can be derived from other attribute is known as a derived attribute. It can be represented by a dashed ellipse.

For example, A person's age changes over time and can be derived from another attribute like Date of birth.

3. Relationship
A relationship is used to describe the relation between entities. Diamond or rhombus is used to represent the relationship.

Types of relationship are as follows:

a. One-to-One Relationship

When only one instance of an entity is associated with the relationship, then it is known as one to one relationship.
For example, A female can marry to one male, and a male can marry to one female.

b. One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on the right associates with the relationship then this is
known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only specific scientist.

c. Many-to-one relationship

When more than one instance of the entity on the left, and only one instance of an entity on the right associates with the relationship then it is
known as a many-to-one relationship.

For example, Student enrolls for only one course, but a course can have many students.

d. Many-to-many relationship

When more than one instance of the entity on the left, and more than one instance of an entity on the right associates with the relationship then
it is known as a many-to-many relationship.

For example, Employee can assign by many projects and project can have many employees.
ER (Entity Relationship) Diagram in DBMS
o ER model stands for an Entity-Relationship model. It is a high-level data model. This model is used to define the data elements and
relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and easy to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an entity-relationship diagram.

For example, Suppose we design a school database. In this database, the student will be an entity with attributes like address, name, id, age, etc.
The address can be another entity with attributes like city, street name, pin code, etc and there will be a relationship between them.

Component of ER Diagram
1. Entity:
An entity may be any object, class, person or place. In the ER diagram, an entity can be represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can be taken as an entity.

a. Weak Entity

An entity that depends on another entity called a weak entity. The weak entity doesn't contain any key attribute of its own. The weak entity is
represented by a double rectangle.
2. Attribute
The attribute is used to describe the property of an entity. Eclipse is used to represent an attribute.

For example, id, age, contact number, name, etc. can be attributes of a student.

a. Key Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a primary key. The key attribute is represented by an
ellipse with the text underlined.
b. Composite Attribute

An attribute that composed of many other attributes is known as a composite attribute. The composite attribute is represented by an ellipse, and
those ellipses are connected with an ellipse.

c. Multivalued Attribute

An attribute can have more than one value. These attributes are known as a multivalued attribute. The double oval is used to represent
multivalued attribute.

For example, a student can have more than one phone number.
d. Derived Attribute

An attribute that can be derived from other attribute is known as a derived attribute. It can be represented by a dashed ellipse.

For example, A person's age changes over time and can be derived from another attribute like Date of birth.

3. Relationship
A relationship is used to describe the relation between entities. Diamond or rhombus is used to represent the relationship.

Types of relationship are as follows:

a. One-to-One Relationship

When only one instance of an entity is associated with the relationship, then it is known as one to one relationship.
For example, A female can marry to one male, and a male can marry to one female.

b. One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on the right associates with the relationship then this is
known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only specific scientist.

c. Many-to-one relationship

When more than one instance of the entity on the left, and only one instance of an entity on the right associates with the relationship then it is
known as a many-to-one relationship.

For example, Student enrolls for only one course, but a course can have many students.

d. Many-to-many relationship

When more than one instance of the entity on the left, and more than one instance of an entity on the right associates with the relationship then
it is known as a many-to-many relationship.

For example, Employee can assign by many projects and project can have many employees.
ER (Entity Relationship) Diagram in DBMS
o ER model stands for an Entity-Relationship model. It is a high-level data model. This model is used to define the data elements and
relationship for a specified system.
o It develops a conceptual design for the database. It also develops a very simple and easy to design view of data.
o In ER modeling, the database structure is portrayed as a diagram called an entity-relationship diagram.

For example, Suppose we design a school database. In this database, the student will be an entity with attributes like address, name, id, age, etc.
The address can be another entity with attributes like city, street name, pin code, etc and there will be a relationship between them.

Component of ER Diagram
1. Entity:
An entity may be any object, class, person or place. In the ER diagram, an entity can be represented as rectangles.

Consider an organization as an example- manager, product, employee, department etc. can be taken as an entity.

a. Weak Entity

An entity that depends on another entity called a weak entity. The weak entity doesn't contain any key attribute of its own. The weak entity is
represented by a double rectangle.
2. Attribute
The attribute is used to describe the property of an entity. Eclipse is used to represent an attribute.

For example, id, age, contact number, name, etc. can be attributes of a student.

a. Key Attribute

The key attribute is used to represent the main characteristics of an entity. It represents a primary key. The key attribute is represented by an
ellipse with the text underlined.
b. Composite Attribute

An attribute that composed of many other attributes is known as a composite attribute. The composite attribute is represented by an ellipse, and
those ellipses are connected with an ellipse.

c. Multivalued Attribute

An attribute can have more than one value. These attributes are known as a multivalued attribute. The double oval is used to represent
multivalued attribute.

For example, a student can have more than one phone number.
d. Derived Attribute

An attribute that can be derived from other attribute is known as a derived attribute. It can be represented by a dashed ellipse.

For example, A person's age changes over time and can be derived from another attribute like Date of birth.

3. Relationship
A relationship is used to describe the relation between entities. Diamond or rhombus is used to represent the relationship.

Types of relationship are as follows:

a. One-to-One Relationship

When only one instance of an entity is associated with the relationship, then it is known as one to one relationship.
For example, A female can marry to one male, and a male can marry to one female.

b. One-to-many relationship

When only one instance of the entity on the left, and more than one instance of an entity on the right associates with the relationship then this is
known as a one-to-many relationship.

For example, Scientist can invent many inventions, but the invention is done by the only specific scientist.

c. Many-to-one relationship

When more than one instance of the entity on the left, and only one instance of an entity on the right associates with the relationship then it is
known as a many-to-one relationship.

For example, Student enrolls for only one course, but a course can have many students.

d. Many-to-many relationship

When more than one instance of the entity on the left, and more than one instance of an entity on the right associates with the relationship then
it is known as a many-to-many relationship.

For example, Employee can assign by many projects and project can have many employees.
Difference between Strong and Weak Entity


Prerequisite – ER Model
Strong Entity:
A strong entity is not dependent on any other entity in the schema. A strong entity will always have a primary key. Strong entities are
represented by a single rectangle. The relationship of two strong entities is represented by a single diamond.
Various strong entities, when combined together, create a strong entity set.
Weak Entity:
A weak entity is dependent on a strong entity to ensure its existence. Unlike a strong entity, a weak entity does not have any primary
key. It instead has a partial discriminator key. A weak entity is represented by a double rectangle.
The relation between one strong and one weak entity is represented by a double diamond. This relationship is also known
as identifying relationship.

What do you mean by relational model?


Relational model in DBMS is an approach to logically represent and manage the data stored in a database by storing data in tables.
Relations, Attributes and Tuples, Degree and Cardinality, Relational Schema and Relation instance, and Relation Keys are some important
components of the Relational Model.
Or

The relational model means that the logical data structures—the data tables, views, and indexes—are separate
from the physical storage structures. This separation means that database administrators can manage physical
data storage without affecting access to that data as a logical structure.

RDBMS (relational database management system)


A relational database management system (RDBMS) is a collection of programs and capabilities that enable IT
teams and others to create, update, administer and otherwise interact with a relational database. RDBMSes store
data in the form of tables, with most commercial relational database management systems using Structured Query
Language (SQL) to access the database. However, since SQL was invented after the initial development of the
relational model, it is not necessary for RDBMS use.

The RDBMS is the most popular database system among organizations across the world. It provides a dependable method
of storing and retrieving large amounts of data while offering a combination of system performance and ease of
implementation.
RDBMS vs. DBMS
In general, databases store sets of data that can be queried for use in other applications. A database management system
supports the development, administration and use of database platforms.

An RDBMS is a type of database management system (DBMS) that stores data in a row-based table structure which
connects related data elements. An RDBMS includes functions that maintain the security, accuracy, integrity and
consistency of the data. This is different than the file storage used in a DBMS.

Other differences between database management systems and relational database management systems include:

● Number of allowed users. While a DBMS can only accept one user at a time, an RDBMS can operate with multiple
users.
● Hardware and software requirements. A DBMS needs less software and hardware than an RDBMS.
● Amount of data. RDBMSes can handle any amount of data, from small to large, while a DBMS can only manage small
amounts.
● Database structure. In a DBMS, data is kept in a hierarchical form, whereas an RDBMS utilizes a table where the
headers are used as column names and the rows contain the corresponding values.
● ACID implementation. DBMSes do not use the atomicity, consistency, isolation and durability (ACID) model for storing
data. On the other hand, RDBMSes base the structure of their data on the ACID model to ensure consistency.
● Distributed databases. While an RDBMS offers complete support for distributed databases, a DBMS will not provide
support.
● Types of programs managed. While an RDBMS helps manage the relationships between its incorporated tables of
data, a DBMS focuses on maintaining databases that are present within the computer network and system hard disks.
● Support of database normalization. An RDBMS can be normalized, but a DBMS cannot.

Features of relational database management systems


Elements of the relational database management system that overarch the basic relational database are so intrinsic to
operations that it is hard to dissociate the two in practice.

The most basic RDBMS functions are related to create, read, update and delete operations -- collectively known as CRUD.
They form the foundation of a well-organized system that promotes consistent treatment of data.

The RDBMS typically provides data dictionaries and metadata collections that are useful in data handling. These
programmatically support well-defined data structures and relationships. Data storage management is a common capability
of the RDBMS, and this has come to be defined by data objects that range from binary large object -- or blob -- strings
to stored procedures. Data objects like this extend the scope of basic relational database operations and can be handled in
a variety of ways in different RDBMSes.
The most common means of data access for the RDBMS is SQL. Its main language components comprise data
manipulation language and data definition language statements. Extensions are available for development efforts that pair
SQL use with common programming languages, such as the Common Business-Oriented Language (COBOL), Java and
.NET.

RDBMSes use complex algorithms that support multiple concurrent user access to the database while maintaining data
integrity. Security management, which enforces policy-based access, is yet another overlay service that the RDBMS
provides for the basic database as it is used in enterprise settings.

RDBMSes support the work of database administrators (DBAs) who must manage and monitor database activity. Utilities
help automate data loading and database backup. RDBMSes manage log files that track system performance based on
selected operational parameters. This enables measurement of database usage, capacity and performance, particularly
query performance. RDBMSes provide graphical interfaces that help DBAs visualize database activity.

While not limited solely to the RDBMS, ACID compliance is an attribute of relational technology that has proved important in
enterprise computing. These capabilities have particularly suited RDBMSes for handling business transactions.

As RDBMSes have matured, they have achieved increasingly higher levels of query optimization, and they have become
key parts of reporting, analytics and data warehousing applications for businesses as well. RDBMSes are intrinsic to
operations of a variety of enterprise applications and are at the center of most master data management systems.

How RDBMS works


As mentioned before, an RDBMS will store data in the form of a table. Each system will have varying numbers of tables with
each table possessing its own unique primary key. The primary key is then used to identify each table.

Within the table are rows and columns. The rows are known as records or horizontal entities; they contain the information for
the individual entry. The columns are known as vertical entities and possess information about the specific field.

Before creating these tables, the RDBMS must check the following constraints:

● Primary keys -- this identifies each row in the table. One table can only contain one primary key. The key must be unique
and without null values.
● Foreign keys -- this is used to link two tables. The foreign key is kept in one table and refers to the primary key
associated with another table.
● Not null -- this ensures that every column does not have a null value, such as an empty cell.
● Check -- this confirms that each entry in a column or row satisfies a precise condition and that every column holds unique
data.
● Data integrity -- the integrity of the data must be confirmed before the data is created.

Assuring the integrity of data includes several specific tests, including entity, domain, referential and user-defined integrity.
Entity integrity confirms that the rows are not duplicated in the table. Domain integrity makes sure that data is entered into
the table based on specific conditions, such as file format or range of values. Referential integrity ensures that any row that
is re-linked to a different table cannot be deleted. Finally, user-defined integrity confirms that the table will satisfy all
user-defined conditions.

Advantages of relational database management system


The use of an RDBMS can be beneficial to most organizations; the systematic view of raw data helps companies better
understand and execute the information while enhancing the decision-making process. The use of tables to store data also
improves the security of information stored in the databases. Users are able to customize access and set barriers to limit the
content that is made available. This feature makes the RDBMS particularly useful to companies in which the manager
decides what data is provided to employees and customers.
Furthermore, RDBMSes make it easy to add new data to the system or alter existing tables while ensuring consistency with
the previously available content.

Other advantages of the RDBMS include:

● Flexibility -- updating data is more efficient since the changes only need to be made in one place.
● Maintenance -- database administrators can easily maintain, control and update data in the database. Backups also
become easier since automation tools included in the RDBMS automate these tasks.
● Data structure -- the table format used in RDBMSes is easy to understand and provides an organized and structural
manner through which entries are matched by firing queries.

On the other hand, relational database management systems do not come without their disadvantages. For example, in
order to implement an RDBMS, special software must be purchased. This introduces an additional cost for execution. Once
the software is obtained, the setup process can be tedious since it requires millions of lines of content to be transferred into
the RDBMS tables. This process may require the additional help of a programmer or a team of data entry specialists.
Special attention must be paid to the data during entry to ensure sensitive information is not placed into the wrong hands.

Some other drawbacks of the RDBMS include the character limit placed on certain fields in the tables and the inability to fully
understand new forms of data -- such as complex numbers, designs and images.

Furthermore, while isolated databases can be created using an RDBMS, the process requires large chunks of information to
be separated from each other. Connecting these large amounts of data to form the isolated database can be very
complicated.

Uses of RDBMS
Relational database management systems are frequently used in disciplines such as manufacturing, human resources and
banking. The system is also useful for airlines that need to store ticket service and passenger documentation information as
well as universities maintaining student databases.

Some examples of specific systems that use RDBMS include IBM, Oracle, MySQL, Microsoft SQLServer and PostgreSQL.

RDBMS product history


Many vying relational database management systems arose as news spread in the early 1970s of the relational data model.
This and related methods were originally theorized by IBM researcher E.F. Codd, who proposed a database schema, or
logical organization, that was not directly associated with physical organization, as was common at the time.

Codd's work was based around a concept of data normalization, which saved file space on storage disk drives at a time
when such machinery could be prohibitively expensive for businesses.

File systems and database management systems preceded what could be called the RDBMS era. Such systems ran
primarily on mainframe computers. While RDBMSes also ran on mainframes -- IBM's DB2 being a pointed example -- much
of their ascendance in the enterprise was in UNIX midrange computer deployments. The RDBMS was a linchpin in the
distributed architecture of client-server computing, which connected pools of stand-alone personal computers to file and
database servers.

Numerous RDBMSes arose along with the use of client-server computing. Among the competitors were Oracle, Ingres,
Informix, Sybase, Unify, Progress and others. Over time, three RDBMSes came to dominate in commercial implementations.
Oracle, IBM's DB2 and Microsoft's SQL Server, which was based on a design originally licensed from Sybase, found
considerable favor throughout the client-server computing era, despite repeated challenges by competing technologies.

As the 20th century drew to an end, lower-cost, open source versions of RDBMSes began to find use, particularly in web
applications.
Eventually, as distributed computing took greater hold, and as cloud architecture became more prominently employed,
RDBMSes met competition in the form of NoSQL systems. Such systems were often specifically designed for massive
distribution and high scalability in the cloud, sometimes forgoing SQL-style full consistency for so-called eventual
consistency of data. But, even in the most diverse and complex cloud systems, the need for some guaranteed data
consistency requires RDBMSes to appear in some way, shape or form. Moreover, versions of RDBMSes have been
significantly restructured for cloud parallelization and replication.

RDBMS terminologies
RDMS Terminologies include Database, Table, Columns, etc. Let us see them one by one −

Database
Database is a collection of tables like <Student>, <Professors>, etc.

Table
A table is a collection of rows and columns , for example,

StudentId StudentName StudentRank

052 Tom 1

035 David 2

077 John 3

Column
Column is in a table −

Row
Row is also called a tuple in RDBMS.
A relation in a database has rows and columns.

Primary Key
Every table has one Primary key and cannot have null values.
For example, ProjectID is a primary key in Project Table, since it uniquely identifies the project:

ProjectID ProjectName

P01 Cluster Grouping System

P02 Hospital Management System


Foreign Key
If you want to link two tables, use Foreign Key.
For example, Employee table has DEPT_ID that is a foreign key, which is linked to Department table.
The Department table has primary key DEPT_ID.

What are Integrity Constraints in DBMS?


Integrity constraints are rules that help to maintain the accuracy and consistency of data in a database.
They can be used to enforce business rules or to ensure that data is entered correctly. For example, a
simple integrity constraint in DBMS might state that all customers must have a valid email address. This
would prevent someone from accidentally entering an invalid email address into the database. Integrity
constraints can also be used to enforce relationships between tables.

For example, if a customer can only have one shipping address, then an integrity constraint can be used
to ensure that only one shipping address is entered for each customer. Enforcing integrity constraints in
SQL can help prevent data inconsistencies and errors, making it easier to manage and query the data.

What is the Purpose of Integrity Constraints?


Integrity constraints are an important part of maintaining database correctness. They ensure that the data
in the database adheres to a set of rules, which can help prevent errors and inconsistencies. In some
cases, integrity constraints can be used to enforce business rules, such as ensuring that a customer's
balance remains within a certain limit.

In other cases, they can be used to enforce data integrity, such as ensuring that all values in a column are
unique. Integrity constraints in SQL can be either enforced by the database system or by application
code. Enforcing them at the database level can help ensure that the rules are always followed, even if the
application code is changed. However, enforcing them at the application level can give the developer
more flexibility in how the rules are enforced.

Types of Integrity Constraints

Integrity constraints in DBMS are used to ensure that data is consistent and accurate. There are four
main types of integrity constraints: domain, entity, referential, and key. Here, we'll take a closer look &
explain the types of integrity constraints along with some examples.
1. Domain Constraint

A domain constraint is a restriction on the values that can be stored in a column. For example, if you have
a column for "age," domain integrity constraints in DBMS would ensure that only values between 1 and
120 can be entered into that column. This ensures that only valid data is entered into the database.

2. Entity Integrity Constraint

An entity integrity constraint is a restriction on null values. Null values are values that are unknown or not
applicable, and they can be problematic because they can lead to inaccurate results. Entity integrity
constraints would ensure that null values are not entered into any required columns. For example, if you
have a column for "first name," an entity integrity constraint in DBMS would ensure that this column
cannot contain any null values.

3. Referential Integrity Constraint

A referential integrity constraint is a restriction on how foreign keys can be used. A foreign key is a
column in one table that references a primary key in another table. For example, let's say you have a
table of employees and a table of department managers. The "employee ID" column in the employee's
table would be a foreign key that references the "manager ID" column in the manager's table.

Referential integrity constraints in DBMS would ensure that every manager ID in the manager's table has
at least one corresponding employee ID in the employee's table. In other words, it would prevent you from
assigning an employee to a manager who doesn't exist.

4. Key Constraint

Key constraints in DBMS are a restriction on duplicate values. A key is composed of one or more columns
whose values uniquely identify each row in the table. For example, let's say you have a table of products
with columns for "product ID" and "product name." The combination of these two values would be the key
for each product, and a key constraint would ensure that no two products have the same combination of
product ID and product name.

Types of Key Constraints

Within databases, a key constraint is a rule that defines how data in a column(s) can be stored in a table.
There are several different types of key constraints in DBMS, each with its own specific purpose. Now,
we'll take a high-level look at the five most common types of key constraints: primary key constraints,
unique key constraints, foreign key constraints, NOT NULL constraints, and check constraints.
1. Primary Key Constraints

A primary key constraint (also known as a "primary key") is a type of key constraint that requires every
value in a given column to be unique. In other words, no two rows in a table can have the same value for
their primary key column(s). A primary key can either be a single column or multiple columns (known as a
"composite" primary key). The null value is not allowed in the primary key column(s).

2. Unique Key Constraints

A unique key constraint is a column or set of columns that ensures that the values stored in the column
are unique. A table can have more than one unique key constraint, unlike the primary key. A unique key
column can contain NULL values. Like primary keys, unique keys can be made up of a single column or
multiple columns.

3. Foreign Key Constraints

A foreign key constraint defines a relationship between two tables. A foreign key in one table references a
primary key in another table. Foreign keys prevent invalid data from being inserted into the foreign key
column. Foreign keys can reference a single column or multiple columns.

4. NOT NULL Constraints

A NOT NULL constraint is used to ensure that no row can be inserted into the table without a value being
specified for the column(s) with this type of constraint. Thus, every row must have a non-NULL value for
these columns.

5. Check Constraints

A check constraint enforces data integrity by allowing you to specify conditions that must be met for data
to be inserted into a column. For example, you could use a check constraint to ensure that only positive
integer values are inserted into a particular column. Check constraints are usually used in combination
with other constraints (such as NOT NULL constraints) to enforce more complex rules.

There are several different types of key constraints in DBMS that you can use in SQL databases. Each
type of constraint has its own specific use cases and benefits. By understanding when to use each type of
constraint, you can ensure that your database is both reliable and consistent. For in-depth knowledge of
the types of integrity constraints, you can go for the MongoDB Administration certification & expand
your knowledge and develop a stronger outlook.

Advantages of Integrity Constraints


Integrity constraints in DBMS can be used to enforce rules at the database level, which means that they
are applied to all users and applications that access the database. There are several advantages to using
integrity constraints in SQL, which will be outlined in more detail below.

1. Declarative Ease

One of the advantages of integrity constraints is that they can be declared easily. Integrity constraints are
written in a declarative language, which means that they can be specified without having to write code.
This makes it easy for even non-technical users to understand and specify rules.

2. Centralized Rules

Another advantage of integrity constraints is that they provide a centralized way to specify rules.
Therefore, rules only have to be specified once and then they can be enforced across the entire
database. This is much more efficient than having to specify rules individually for each application or user.
3. Flexibility When Loading Data

Integrity constraints also provide flexibility when loading data into the database. When data is loaded into
the database, the integrity constraints are checked automatically. In other words, if there are any
problems with the data, they can be detected and corrected immediately.

4. Maximum Application Development Productivity

Using integrity constraints can also help to maximize application development productivity. This is
because developers do not have to write code to enforce rules; they can simply specify the rules using an
integrity constraint language. This saves time and effort during development and makes it easier to create
consistent and reliable applications.

5. Immediate User Feedback

Finally, using integrity constraints in DBMS provides immediate feedback to users when they attempt to
violate a rule. For example, if a user tries to insert an invalid value into a database column, the database
will reject the attempted insertion and return an error message to the user instead. This provides a clear
indication to the user that their input is incorrect and needs to be corrected.

Why are Integrity Constraints Important?


Integrity constraints are important for several reasons. First, they help to ensure the accuracy of data by
preventing invalid data from being entered into the database. Second, they help to maintain the
consistency of data by ensuring that data is consistent across different tables and fields. Third, they help
to prevent unauthorized access to data by ensuring that only authorized users can access specific data.

Finally, they help to optimize performance by ensuring that only valid data is accessed and processed. By
enforcing integrity constraints, databases can maintain a high level of accuracy and consistency while
also preventing unauthorized access and optimizing performance.

What is Functional Dependency


Functional dependency in DBMS, as the name suggests is a relationship between attributes of a table dependent on each other. Introduced
by E. F. Codd, it helps in preventing data redundancy and gets to know about bad designs.
To understand the concept thoroughly, let us consider P is a relation with attributes A and B. Functional Dependency is represented
by -> (arrow sign)
Then the following will represent the functional dependency between attributes with an arrow sign −

A -> B
Above suggests the following:
Example
The following is an example that would make it easier to understand functional dependency −
We have a <Department> table with two attributes − DeptId and DeptName.

DeptId = Department IDDeptName = Department Name


The DeptId is our primary key. Here, DeptId uniquely identifies the DeptName attribute. This is because if you want to know the department
name, then at first you need to have the DeptId.

DeptId DeptName

001 Finance

002 Marketing

003 HR
Therefore, the above functional dependency between DeptId and DeptName can be determined as DeptId is functionally dependent
on DeptName −

DeptId -> DeptName

Types of Functional Dependency


Functional Dependency has three forms −
● Trivial Functional Dependency
● Non-Trivial Functional Dependency
● Completely Non-Trivial Functional Dependency
Let us begin with Trivial Functional Dependency −

Trivial Functional Dependency


It occurs when B is a subset of A in −

A ->B
Example
We are considering the same <Department> table with two attributes to understand the concept of trivial dependency.
The following is a trivial functional dependency since DeptId is a subset of DeptId and DeptName

{ DeptId, DeptName } -> Dept Id

Non –Trivial Functional Dependency


It occurs when B is not a subset of A in −
A ->B
Example

DeptId -> DeptName


The above is a non-trivial functional dependency since DeptName is a not a subset of DeptId.

Completely Non - Trivial Functional Dependency


It occurs when A intersection B is null in −

A ->B

Armstrong’s Axioms Property of Functional Dependency


Armstrong’s Axioms property was developed by William Armstrong in 1974 to reason about functional dependencies.
The property suggests rules that hold true if the following are satisfied:
● TransitivityIf A->B and B->C, then A->C i.e. a transitive relation.
● ReflexivityA-> B, if B is a subset of A.
● AugmentationThe last rule suggests: AC->BC, if A->B

Normalization
A large database defined as a single relation may result in data duplication. This repetition of data may result in:

o Making relations very large.


o It isn't easy to maintain and update data as it would involve searching many records in relation.
o Wastage and poor utilization of disk space and resources.
o The likelihood of errors and inconsistencies increases.
So to handle these problems, we should analyze and decompose the relations with redundant data into smaller, simpler, and well-structured
relations that are satisfy desirable properties. Normalization is a process of decomposing the relations into relations with fewer attributes.

What is Normalization?

o Normalization is the process of organizing the data in the database.


o Normalization is used to minimize the redundancy from a relation or set of relations. It is also used to eliminate undesirable
characteristics like Insertion, Update, and Deletion Anomalies.
o Normalization divides the larger table into smaller and links them using relationships.
o The normal form is used to reduce redundancy from the database table.

Why do we need Normalization?

The main reason for normalizing the relations is removing these anomalies. Failure to eliminate anomalies leads to data redundancy and can
cause data integrity and other problems as the database grows. Normalization consists of a series of guidelines that helps to guide you in creating
a good database structure.

Data modification anomalies can be categorized into three types:

o Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new tuple into a relationship due to lack of data.
o Deletion Anomaly: The delete anomaly refers to the situation where the deletion of data results in the unintended loss of some other
important data.
o Updatation Anomaly: The update anomaly is when an update of a single data value requires multiple rows of data to be updated.

Types of Normal Forms:

Normalization works through a series of stages called Normal forms. The normal forms apply to individual relations. The relation is said to be in
particular normal form if it satisfies constraints.

Following are the various types of Normal forms:

Normal Description
Form

1NF A relation is in 1NF if it contains an atomic value.

2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are fully functional
dependent on the primary key.
3NF A relation will be in 3NF if it is in 2NF and no transition dependency exists.

BCNF A stronger definition of 3NF is known as Boyce Codd's normal form.

4NF A relation will be in 4NF if it is in Boyce Codd's normal form and has no multi-valued
dependency.

5NF A relation is in 5NF. If it is in 4NF and does not contain any join dependency, joining
should be lossless.

Advantages of Normalization

o Normalization helps to minimize data redundancy.


o Greater overall database organization.
o Data consistency within the database.
o Much more flexible database design.
o Enforces the concept of relational integrity.

Disadvantages of Normalization

o You cannot start building the database before knowing what the user needs.
o The performance degrades when normalizing the relations to higher normal forms, i.e., 4NF, 5NF.
o It is very time-consuming and difficult to normalize relations of a higher degree.
o Careless decomposition may lead to a bad database design, leading to serious problems.

First Normal Form (1NF)


o A relation will be 1NF if it contains an atomic value.
o It states that an attribute of a table cannot hold multiple values. It must hold only single-valued attribute.
o First normal form disallows the multi-valued attribute, composite attribute, and their combinations.

Example: Relation EMPLOYEE is not in 1NF because of multi-valued attribute EMP_PHONE.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar

12 Sam 7390372389, Punjab


8589830302

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE


14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar

12 Sam 7390372389 Punjab

12 Sam 8589830302 Punjab

Second Normal Form (2NF)


o In the 2NF, relational must be in 1NF.
o In the second normal form, all non-key attributes are fully functional dependent on the primary key

Example: Let's assume, a school can store the data of teachers and the subjects they teach. In a school, a teacher can teach more than one
subject.

TEACHER table

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30

25 Biology 30

47 English 35

83 Math 38

83 Computer 38

In the given table, non-prime attribute TEACHER_AGE is dependent on TEACHER_ID which is a proper subset of a candidate key. That's why it
violates the rule for 2NF.

To convert the given table into 2NF, we decompose it into two tables:

TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE

25 30

47 35

83 38

TEACHER_SUBJECT table:

TEACHER_ID SUBJECT
25 Chemistry

25 Biology

47 English

83 Math

83 Computer

Third Normal Form (3NF)


o A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
o 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
o If there is no transitive dependency for non-prime attributes, then the relation must be in third normal form.

A relation is in third normal form if it holds atleast one of the following conditions for every non-trivial function dependency X → Y.

1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.

Example:

EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 UP Noida

333 Stephan 02228 US Boston

444 Lan 60007 US Chicago

555 Katharine 06389 UK Norwich

666 John 462007 MP Bhopal

Super key in the table above:

1. {EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP}....so on


Candidate key: {EMP_ID}

Non-prime attributes: In the given table, all attributes except EMP_ID are non-prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent on EMP_ID. The non-prime attributes (EMP_STATE,
EMP_CITY) transitively dependent on super key(EMP_ID). It violates the rule of third normal form.

That's why we need to move the EMP_CITY and EMP_STATE to the new <EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_ZIP


222 Harry 201010

333 Stephan 02228

444 Lan 60007

555 Katharine 06389

666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 UP Noida

02228 US Boston

60007 US Chicago

06389 UK Norwich

462007 MP Bhopal

Boyce Codd normal form (BCNF)


o BCNF is the advance version of 3NF. It is stricter than 3NF.
o A table is in BCNF if every functional dependency X → Y, X is the super key of the table.
o For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

Example: Let's assume there is a company where employees work in more than one department.

EMPLOYEE table:

EMP_ID EMP_COUNTRY EMP_DEPT DEPT_TYPE EMP_DEPT_NO

264 India Designing D394 283

264 India Testing D394 300

364 UK Stores D283 232

364 UK Developing D283 549

In the above table Functional dependencies are as follows:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Candidate key: {EMP-ID, EMP-DEPT}

The table is not in BCNF because neither EMP_DEPT nor EMP_ID alone are keys.

To convert the given table into BCNF, we decompose it into three tables:

EMP_COUNTRY table:

EMP_ID EMP_COUNTRY

264 India

264 India

EMP_DEPT table:

EMP_DEPT DEPT_TYPE EMP_DEPT_NO

Designing D394 283

Testing D394 300

Stores D283 232

Developing D283 549

EMP_DEPT_MAPPING table:

EMP_ID EMP_DEPT

D394 283

D394 300

D283 232

D283 549

Functional dependencies:

1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Candidate keys:

For the first table: EMP_ID


For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}

Now, this is in BCNF because left side part of both the functional dependencies is a key.

Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
● SQL stands for Structured Query Language
● SQL lets you access and manipulate databases
● SQL became a standard of the American National Standards Institute (ANSI) in
1986, and of the International Organization for Standardization (ISO) in 1987

What Can SQL do?


● SQL can execute queries against a database
● SQL can retrieve data from a database
● SQL can insert records in a database
● SQL can update records in a database
● SQL can delete records from a database
● SQL can create new databases
● SQL can create new tables in a database
● SQL can create stored procedures in a database
● SQL can create views in a database
● SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the major commands (such
as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar mann

Using SQL in Your Web Site


To build a web site that shows data from a database, you will need:

● An RDBMS database program (i.e. MS Access, SQL Server, MySQL)


● To use a server-side scripting language, like PHP or ASP
● To use SQL to get the data you want
● To use HTML / CSS to style the page

RDBMS
RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.

The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of
columns and rows.
What are the advantages and disadvantages of SQL
The followings are the advantages and disadvantages of SQL:

Advantages Disadvantages

Efficient data retrieval Complexity

Data integrity Security risks

Scalability Performance issues

Standardization Cost

Flexibility Lack of flexibility

Advantages of SQL
1. Efficient data retrieval – SQL allows for fast and efficient retrieval of specific data from large databases, making
it easier for businesses to find the information they need quickly.
2. Data integrity – SQL helps ensure the accuracy and consistency of data by enforcing constraints and rules that
prevent errors or invalid data from being added to the database.
3. Scalability – SQL is scalable, meaning it can be used to manage databases of any size, from small business
databases to large enterprise databases.
4. Standardization – SQL is a standardized language, which means that it can be used across different database
management systems and platforms.
5. Flexibility – SQL can be used for a variety of tasks, from simple data retrieval to complex data analysis and
management.

SQL Data Types


An SQL developer must aware of what type of data will be stored inside each column while creating a table. The data type
guideline for SQL is to understand what type of data is expected inside each column and it also identifies how SQL will interact with
the stored data.
SQL (Structured Query Language) is a language used to interact with relational databases. SQL data types define the type of data
that can be stored in a database column or variable. Here are the most common SQL data types:
Data Type Properties

These are used to store numeric values. Examples include INT,


Numeric data types BIGINT
, DECIMAL, and FLOAT.

Character data These are used to store character strings. Examples include CHAR,
types VARCHAR, and TEXT.

These are used to store date and time values. Examples include
DATE
Date and time data
, TIME, and
types
TIMESTAMP
.

These are used to store binary data, such as images or audio files.
Binary data types
Examples include BLOB and BYTEA.
Data Type Properties

This data type is used to store logical values. The only possible values
Boolean data type
are TRUE and FALSE.

These are used to store intervals of time. Examples include INTERVAL


Interval data types
YEAR, INTERVAL MONTH, and INTERVAL DAY.

These are used to store arrays of values. Examples include ARRAY


Array data types
and JSON.

XML data type This data type is used to store XML data.

These are used to store geometric or geographic data. Examples


Spatial data types
include POINT, LINE, and POLYGON.
Different databases may have different variations of these data types, or they may have additional data types not listed here.
Understanding SQL data types are important for creating tables and working with data in a database, as it affects how data is stored
and processed.
Like in other programming languages, SQL also has certain datatypes available. A brief idea of all the datatypes is discussed below.

Binary Datatypes
There are four subtypes of this datatype which are given below:
Data Type Description

Binary The maximum length of 8000 bytes(Fixed-Length binary data)

varbinary The maximum length of 8000 bytes(Variable Length binary data)

The maximum length of 231 bytes(SQL Server 2005 only).(Variable


varbinary(max)
Length binary data)

Maximum Length of 2,147,483,647 bytes(Variable Length binary


image
data)
Exact Numeric Datatype
There are nine subtypes which are given below in the table. The table contains the range of data in a particular type.
Data Type From To

-263 (-9,223,372,036,854,775,80 263 -1


BigInt
8) (9,223,372,036,854,775,807)

Int -231 (-2,147,483,648) 231-1 (2,147,483,647)

smallint -215 (-32,768) 215-1 (32,767)

tinyint 0 28-1 (255)


Data Type From To

bit 0 1

decimal -1038+1 1038-1

numeric -1038+1 1038-1

money -922,337,203,685,477.5808 922,337,203,685,477.5807

smallmoney -214,748.3648 214,748.3647


Approximate Numeric Datatype
The subtypes of this datatype are given in the table with the range.
Data Type From To

Float -1.79E+308 1.79E+308

Real -3.40E+38 3.40E+38


Character String Datatype
The subtypes are given in below table –

Data Type Description

The maximum length of 8000 characters.(Fixed-Length non-Unicode


char
Characters)

The maximum length of 8000 characters.(Variable-Length


varchar
non-Unicode Characters)

The maximum length of 231 characters(SQL Server 2005


varchar(max)
only).(Variable Length non-Unicode data)

The maximum length of 2,127,483,647 characters(Variable Length


text
non-Unicode data)
Unicode Character String Datatype
The details are given in below table –
Data Type Description

The maximum length of 4000 characters(Fixed-Length Unicode


nchar
Characters)

The maximum length of 4000 characters.(Variable-Length Unicode


Nvarchar
Characters)
Data Type Description

The maximum length of 231 characters(SQL Server 2005


nvarchar(max)
only).(Variable Length Unicode data)
Date and Time Datatype
The details are given in the below table.

Data Type Description

DATE A data type is used to store the data of date in a record

TIME A data type is used to store the data of time in a record

DATETIME A data type is used to store both the data,date, and time in the record.
XML Datatype
XML data type allows storage of XML documents and fragments in a SQL Server database
DataType Description

XML Datatype A Datatype used to store data in the format of XML datatype
Spatial Dataype
A datatype is used for storing planar spatial data, such as points, lines, and polygons, in a database table.
DataType Description

A datatype is used for storing planar spatial data, such as points, lines,
Geometry
and polygons, in a database table.
Array Datatype
SQL Server does not have a built-in array datatype. However, it is possible to simulate arrays using tables or XML data types.

SQL Literals
There are four kinds of literal values supported in SQL. They are : Character string, Bit string, Exact numeric, and
Approximate numeric. These are explained as following below.
1. Character string :
Character strings are written as a sequence of characters enveloped in single quotes. the only quote character is
delineate at intervals a personality string by 2 single quotes. Some example of character strings are :
● ‘My String’
● ‘I love GeeksForGeeks’
● ‘16378’
2. Bit string :
A bit string is written either as a sequence of 0s and 1s enveloped in single quotes and preceded by the letter ‘B’
or as a sequence of positional representation system digits enveloped in single quotes and preceded by the letter
X’ some examples are given below :
● B’10001011′
● B’1′
● B’0′
● X’C 5′
● X’0′
3. Exact numeric :
These literals ar written as a signed or unsigned decimal variety probably with mathematical notation.
Samples of actual numeric literals are given below :
4. Approximate numeric :
Approximate numeric literals are written as actual numeric literals followed by the letter ‘E’, followed by
a signed or unsigned number. Some example are :
● 6E6
● 66.6E6
● +66E-6
● 0.66E
● -6.66E-8

How can you create a table with SQL?


Steps to Create a Table in SQL Server
1. Step 1: Create a database. If you haven't already done so, create a database where the table will be stored. ...
2. Step 2: Create a table. Next, create a table under your database. ...
3. Step 3: Insert values into the table. ...
4. Step 4: Verify that the values were inserted into the table.

How to Create a Table in SQL Server


In this tutorial, you’ll see the complete steps to create a table in SQL Server. An example is also reviewed for demonstration
purposes.

Steps to Create a Table in SQL Server


Step 1: Create a database

If you haven’t already done so, create a database where the table will be stored. For example, you may use the following query to
create a database called the test_database:

CREATE DATABASE test_database

Step 2: Create a table

Next, create a table under your database.

For instance, let’s create a table called ‘products‘ which contains 2 columns:
● product_name
● price
The table should store the following data:

product_name price

Desktop Computer 800

Laptop 1200

Tablet 200

Monitor 350

Printer 150
Where the data type for the ‘product_name‘ column would be nvarchar(50), while the data type for the ‘price‘ column would
be int (for integers).
You can then create the table using the following CREATE TABLE query under your database:

CREATE TABLE products (

product_name nvarchar(50),

price int

Step 3: Insert values into the table

Let’s now add the following values into the ‘products’ table:

product_name price

Desktop Computer 800

Laptop 1200

Tablet 200

Monitor 350

Printer 150

You can insert values into the table using an INSERT INTO query:

INSERT INTO products (product_name, price)

VALUES

('Desktop Computer',800),

('Laptop',1200),

('Tablet',200),

('Monitor',350),
('Printer',150)

Step 4: Verify that the values were inserted into the table

Finally, run the following SELECT query to verify that the values were inserted into the table:

SELECT * FROM products

You should then get the results below:

product_name price

Desktop Computer 800

Laptop 1200

Tablet 200

Monitor 350

Printer 150

Create a Table in SQL Server with Primary Key and Identity Column
A Primary Key uniquely identifies each record (i.e., row) in your table, while an Identity Column ensures that an auto-increment is
applied to your column whenever a new record is inserted into the table.
Let’s say that you want to create a table with a Primary Key and Identity Column.

For example, suppose that you want to recreate the ‘products‘ table with the following 3 columns:
● product_id
● product_name
● price
Where the product_id column will be selected as the Primary Key as well as the Identity Column.
This is how the new ‘products‘ table should look like:
product_id product_name price

1 Desktop Computer 800

2 Laptop 1200

3 Tablet 200

4 Monitor 350

5 Printer 150

Let’s now recreate this table with the use of queries.


To begin, drop the ‘products’ table in order to start from scratch. You can drop the ‘products’ table using the query below:

DROP TABLE products

Then, recreate the table using the CREATE TABLE query:

CREATE TABLE products (

product_id int identity(1,1) primary key,

product_name nvarchar(50),

price int

You can then add records to the table by running this INSERT INTO query:

INSERT INTO products (product_name, price)

VALUES

('Desktop Computer',800),

('Laptop',1200),

('Tablet',200),

('Monitor',350),

('Printer',150)

5 new records will be inserted into the table (notice that it wasn’t necessary to populate the product_id column using the insert query.
This was taken care by setting the product_id column as the Identity Column).

Rerun the SELECT query to see the final results:

SELECT * FROM products


As you can see, all the records are now present in the ‘products’ table (where the product_id column was added with an
auto-increment):
product_id product_name price

1 Desktop Computer 800

2 Laptop 1200

3 Tablet 200

4 Monitor 350

5 Printer 150

Deleting and uploading Records

In the SQL server, the SQL DELETE & UPDATE keywords are more frequently used after the SQL SELECT keyword.

What is the UPDATE keyword?


The UPDATE command is used to modify the records in the table. Upon executing this command the record values are
modified based on values passed in the query. Along with WHERE clause you can update the specific records from the
table.

SQL UPDATE Syntax:


Let’s see the basic syntax of DELETE command:

?
UPDATE Table_Name

SET ‘Column_Name’ = ‘New_value’

[WHERE CONDITION];

So here we see what use of each object:

● [UPDATE Table_Name] – This command is used to tell the database to modify the records from specified
Table_Name.
● [SET ‘Column_Name’ = ‘New_value’] – ‘Column_Name’ is the name the column for which you have to modify the
value & ‘New_value’ are the actual value which you have to set. While setting up the new values you have to enter
the new values based on the column’s data type, which means if the column value is Full_Name with data type
varchar then you have to specify the values in the single quotes. Similarly, for the date data type, you have to enter
date values single quotes. Numeric values you have to specify the values without quotes.
● [WHERE CONDITION] – This Clause used to filter out the result data set based on “condition”. You can specify
any condition using the WHERE clause.
Let’s go ahead & learn to update queries with practical examples. In the Employee table, each record has a Phone & one
Employee wants to change the phone number in the employee record & the second employee wants to update the Full
name. So let’s see how to update the Phone number using the UPDATE query.

?
SELECT * FROM Employee WHERE Employee_Id IN
(1,2);

Full_Nam Gende
Employee_Id Date_Of_Birth Phone
e r

1 Tanya 912345678
Female 1982-09-30
Smith 9

2 Janet 987654321
Female 1980-07-10
Tampi 0

3 911223344
Nilsen Phil Male NULL
5

4 Nilsen 998877665
Male 1983-09-17
Jones 5

5 Pettersen 994455229
Male 1980-07-12
Willams 9

6 Angels 995556661
Male 1981-02-10
David 1

The Employee “Tanya Smith” wants to change phone number from “9123456789” to “9198657777” & “Janet Tampi” want to
update the Full name to “Janet Tampi – Simson” & Date of birth to “1980-07-10”, so you can use the following update
queries to modify the records.

?
UPDATE Employee

SET Phone = ‘9198657777’

WHERE Employee_Id&amp;amp;amp;nbsp; = 1;

?
UPDATE Employee

SET Full_Name = ‘Janet Tampi - Simson’, Date_Of_Birth =


‘1980-08-10’
WHERE Employee_Id&amp;amp;amp;nbsp; = 2;

Note: If you want to update the multiple values in the same condition then you can use the comma operator in the “SET” &
pass the multiple values.

Executing the above script the values in the Employee table are updated based on the values specified in the update query.

?
SELECT * FROM Employee WHERE Employee_Id IN
(1,2);

Full_Nam Gende
Employee_Id Date_Of_Birth Phone
e r

1 Tanya 919865777
Female 1982-09-30
Smith 7

Janet
2 987654321
Tampi – Female 1980-07-10
0
Simson

3 911223344
Nilsen Phil Male NULL
5

4 Nilsen 998877665
Male 1983-09-17
Jones 5

5 Pettersen 994455229
Male 1980-07-12
Willams 9

6 Angels 995556661
Male 1981-02-10
David 1

What is the SQL DELETE keyword?

As it name suggests that the DELETE keyword is used to delete the record(s) from the database when they are no longer be
used. Using the DELETE keyword you can delete single or multiple records from the database. So this command is used
more powerfully with WHERE keyword while removing the unnecessary records from the database.
Upon executing this command the deleted data cannot be recovered, so prior to executing this command you should make
sure with where condition in the query is correct. To be on the safer side, take the backups of the database or tables from
where you are executing the delete query, so it will help you to compare the records after executing the query.

SQL DELETE Syntax


Let’s see the basic syntax of DELETE command:

?
DELETE from Table_Name

[WHERE CONDITION];

In the above case, we have specified WHERE condition, so the records will be deleted from the table based on the criteria
you specified.

You can also use the following command to delete all the data from the table, so the only difference is don’t specify
the WHERE condition:
?
DELETE from Table_Name;

So here we see what use of each object:

● [DELETE from Table_Name] – This command is used to tell the database to delete the records from specified
Table_Name.
● [WHERE CONDITION] – This Clause used to filter out the result data set based on “condition”. You can specify
any condition using the WHERE clause.
Let’s see upon executing following query on Employee table resulting following list:

?
SELECT&amp;amp;amp;nbsp;*&amp;amp;amp;nbsp;FROM&amp;amp;amp;nbsp;Employee

Following is the result after executing the above SQL query:

Full_Nam Gende
Employee_Id Date_Of_Birth Phone
e r

1 Tanya 912345678
Female 1982-09-30
Smith 9

2 Janet 987654321
Female 1980-07-10
Tampi 0

3 911223344
Nilsen Phil Male NULL
5
4 Nilsen 998877665
Male 1983-09-17
Jones 5

5 Pettersen 994455229
Male 1980-07-12
Willams 9

6 Angels 995556661
Male 1981-02-10
David 1

Let take an example of Employee where the “Nilsen Jones” employee left the company and they want to remove the
employee record from the database. Its Employee_Id is 4, so we can write down the delete query on Employee table where
pass the Employee_Id in the WHERE condition to delete the specific employee record.

?
DELETE FROM Employee WHERE Employee_Id = 4;

Once we execute the above script then the “Nilsen Jones” record will be deleted from Employee list and Employee table will
look like as follows:

Gende
Employee_Id Full_Name Date_Of_Birth Phone
r

1 912345678
Tanya Smith Female 1982-09-30
9

2 987654321
Janet Tampi Female 1980-07-10
0

3 911223344
Nilsen Phil Male NULL
5

5 994455229
Pettersen Willams Male 1980-07-12
9

6 995556661
Angels David Male 1981-02-10
1

If we check the employee id record 4, then this record is deleted from the Employee table & not returned in the result set.
Also, keep in mind the column can be deleted using delete command, the entire row will be deleted.
If you want to delete multiple records from the table then this can be accomplished using IN wildcard. Only you have to
provide the list of record which you want to delete in WHERE clause.

?
DELETE FROM Employee WHERE Employee_Id IN (3,5);

Once we execute the above query then the employee IDs 3 & 5 entries from the employee table will be removed.

SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also used to perform specific tasks, functions, and queries of
data.
o SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set permission for users.

Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently save all the changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);


Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);


b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE table_name;


Example

1. DROP TABLE EMPLOYEE;


c. ALTER: It is used to alter the structure of the database. This change could be either to modify the characteristics of an existing attribute or probably to add
a new attribute.

Syntax:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;


To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);


EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.

Syntax:

1. TRUNCATE TABLE table_name;


Example:

1. TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all form of changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);
Or

1. INSERT INTO TABLE_NAME


2. VALUES (value1, value2, value3, .... valueN);
For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");


b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]


For example:

1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a table.

Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";

3. Data Control Language


DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;


b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language


TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used while creating tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;
Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.

Syntax:

1. ROLLBACK;
Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;

5. Data Query Language


DQL is used to fetch the data from the database.

It uses only one command:

o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute based on the condition described by WHERE
clause.

Syntax:

1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:

1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;

SQL Operator
There are various types of SQL operator:

SQL Arithmetic Operators

Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.

Operator Description Example

+ It adds the value of both operands. a+b will give


30

- It is used to subtract the right-hand operand from the left-hand operand. a-b will give
10

* It is used to multiply the value of both operands. a*b will give


200

/ It is used to divide the left-hand operand by the right-hand operand. a/b will give 2

% It is used to divide the left-hand operand by the right-hand operand and a%b will give
returns reminder. 0
SQL Comparison Operators:

Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20 and 'b' contains 10.

Operator Description Example

= It checks if two operands values are equal or not, if the values are queal (a=b) is not
then condition becomes true. true

!= It checks if two operands values are equal or not, if values are not equal, (a!=b) is true
then condition becomes true.

<> It checks if two operands values are equal or not, if values are not equal (a<>b) is true
then condition becomes true.

> It checks if the left operand value is greater than right operand value, if yes (a>b) is not
then condition becomes true. true

< It checks if the left operand value is less than right operand value, if yes (a<b) is true
then condition becomes true.

>= It checks if the left operand value is greater than or equal to the right (a>=b) is not
operand value, if yes then condition becomes true. true

<= It checks if the left operand value is less than or equal to the right operand (a<=b) is true
value, if yes then condition becomes true.

!< It checks if the left operand value is not less than the right operand value, if (a!=b) is not
yes then condition becomes true. true

!> It checks if the left operand value is not greater than the right operand (a!>b) is true
value, if yes then condition becomes true.

SQL Logical Operators

There is the list of logical operator used in SQL:

Operator Description

ALL It compares a value to all values in another value set.

AND It allows the existence of multiple conditions in an SQL statement.

ANY It compares the values in the list according to the condition.

BETWEEN It is used to search for values that are within a set of values.

IN It compares a value to that specified list value.


NOT It reverses the meaning of any logical operator.

OR It combines multiple conditions in SQL statements.

EXISTS It is used to search for the presence of a row in a specified table.

LIKE It compares a value to similar values using wildcard operator.

MySQL | Operator precedence:


Operator precedence specifies the order in which operators are evaluated when two or more operators with different precedence are
adjacent in an expression.
For example, 1+2/3 gives the different result as compared to (1+2)/3. Just like all other programming languages C, C++, Java etc. MySQL
also has a precedence rule.
The following table describes operator precedence in MySQL, from highest to lowest. Operators which are in the same group have the equal
precedence.

Operator Description

INTERVAL Return the index of the argument that is less than the first argument

BINARY This is a type that stores binary byte strings


COLLATE This clause override whatever the default collation is for comparison

! Negate values

– It change the sign of the operand


~ It inverts the bits of operand

^ Bitwise XOR

* Multiplication operator
/ Division operator
DIV Integer Division (discard the fractional part of division)
%, MOD Modulo operator

– Minus operator
+ Addition operator

<< Shift a (BIGINT) number or binary string to left


>> Shift a (BIGINT) number or binary string to right

& Bitwise AND

| Bitwise OR

= Comparison operator
<=> NULL-safe equal to operator
>=, > Greater than/Greater than or equal to
<=, < Less than/Less than or equal to
<>, != Not Equal to operator
IS Test a value against a boolean value
Operator Description

LIKE Pattern matching operator


REGEXP Matches the string expression with the regular expression
IN Check whether a value is present in list or not

BETWEEN
Check whether a value is within a range of values
CASE WHEN
Case operator
THEN ELSE

NOT Negates Value

AND, && Logical AND

XOR Logical XOR

OR, || Logical OR

= Assign a value (as part of a SET statement/SET clause in an UPDATE statement)


:= Assign a value
These operator precedence rule greatly affects our MySQL queries.Without knowledge of operator precedence we can get unexpected
result. To, understand this consider the following table Student.
id name marks

1 Payal 12

2 Utkarsh 9

3 Reeta 19

4 Sunny 15

5 Shanu 5

6 Punit 7
From the above table we want the result of those students having marks greater than 10 and whose name starts with either ‘p’ or ‘s’. So, it’s
query can be written as-
mysql>select *
from student
where marks>10 and name like 'p%'
or name like 's%';
Result:
It will produce the desired result:
id name marks

1 Payal 12

4 Sunny 15
id name marks

6 Punit 7
This result set is not as expected from the query. As it is giving the result of a student ‘Punit’ having marks less than 10 which is not required.
Due to higher precedence of operator AND as compare to OR, the above query give result of all those students having marks greater than
10 and name starting with ‘s’, in addition to those the result of those student having name starting with ‘p’ is also given in output. So, here
come role of parentheses. The above-stated query can be written as,

mysql>select *
from student
where marks>10 and (name like 'p%'
or name like 's%');
Result:
It will produce the desired result:
id name marks

1 Payal 12

4 Sunny 15

Hence, this precedence of the operator can be overridden by making use of parenthesis.

SQL Sub Query


A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule:

o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to perform the same function as ORDER BY
command.

1. Subqueries with the Select Statement

SQL subqueries are most frequently used with the Select statement.

Syntax

1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );
Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00


3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);
This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

2. Subqueries with the INSERT Statement

o SQL subquery can also be used with the Insert statement. In the insert statement, data returned from the subquery is used to insert into another
table.
o In the subquery, the selected data can be modified with any of the character, date functions.

Syntax:

1. INSERT INTO table_name (column1, column2, column3....)


2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR
Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.

1. INSERT INTO EMPLOYEE_BKP


2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement

The subquery of SQL can be used in conjunction with the Update statement. When a subquery is used with the Update statement, then either single or
multiple columns in a table can be updated.

Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example updates the SALARY by .25 times in the
EMPLOYEE table for all employee whose AGE is greater than or equal to 29.

1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

4. Subqueries with the DELETE Statement

The subquery of SQL can be used in conjunction with the Delete statement just like any other statements mentioned above.

Syntax

1. DELETE FROM TABLE_NAME


2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME
5. WHERE condition);
Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table. The given example deletes the records from the EMPLOYEE
table for all EMPLOYEE whose AGE is greater than or equal to 29.

1. DELETE FROM EMPLOYEE


2. WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
3. WHERE AGE >= 29 );
This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

Built-In functions
Built-In functions are used in SQL SELECT expressions to calculate values and manipulate data. These functions can
be used anywhere expressions are allowed. Common uses of functions include changing a name to all upper case.
What are Built-In Functions?
In SQL a built-in function is a piece for programming that takes zero or more inputs and returns a value. An example of a built-in function is ABS(),
which when given a value calculates the absolute (non-negative) value of the number.
Some functions, such as ABS() are used to perform calculations, others such as GETDATE() are used to obtain a system value, such as the current
data, or others, like LEFT(), are used to manipulate textual data.

Here is a simple query using the absolute value function.


SELECT Name,

ABS(500 - ReorderPoint) ReorderPointDeviation

FROM production.Product

WHERE ABS(500 - ReorderPoint) > 200

In this query we first calculate the difference between 500 and a product’s reorder point. The ABS function is then used to return the result as a
positive number.
There are several things to note regarding functions.

1. The inputs to a function are called parameters. Not all function has parameters, and some functions have more than one.
2. Parameters are enclosed in parenthesis.
3. We use functions in the SELECT clause as well as the WHERE filter condition. A function can be used anywhere in a SELECT
statement that you can use an expression.
4. Functions are reserved words. I would avoid using them as column or table names. If you do, then expect to qualify your names with
brackets [].

Built-in Functions in SQL


Numberic Functions
Function Input Argument Value Returned

ABS ( m ) m = value Absolute value of m

MOD ( m, n ) m = value, n = divisor Remainder of m divided by n

POWER ( m, n ) m = value, n = exponent m raised to the nth power

ROUND ( m [, n ] ) m = value, n = number of decimal places, default 0 m rounded to the nth decimal place
TRUNC ( m [, n ] ) m = value, n = number of decimal places, default 0 m truncated to the nth decimal place

SIN ( n ) n = angle expressed in radians sine (n)

COS ( n ) n = angle expressed in radians cosine (n)

TAN ( n ) n = angle expressed in radians tan (n)

ASIN ( n ) n is in the range -1 to +1 arc sine of n in the range -π/2 to +π/2

ACOS ( n ) n is in the range -1 to +1 arc cosine of n in the range 0 to π

arc tangent of n in the range -π/2 to +


ATAN ( n ) n is unbounded
π/2

SINH ( n ) n = value hyperbolic sine of n

COSH ( n ) n = value hyperbolic cosine of n

TANH ( n ) n = value hyperbolic tangent of n

SQRT ( n ) n = value positive square root of n

EXP ( n ) n = value e raised to the power n

LN ( n ) n>0 natural logarithm of n

base n2 any positive value other than 0 or 1, n1 any


LOG ( n2, n1 ) logarithm of n1, base n2
positive value

smallest integer greater than or equal


CEIL ( n ) n = value
to n

greatest integer smaller than or equal


FLOOR ( n ) n = value
to n

SIGN ( n ) n = value -1 if n < 0, 0 if n = 0, and 1 if n > 0

Here are some examples of the use of some of these numeric functions:
select round (83.28749, 2) from dual;

select sqrt (3.67) from dual;

select power (2.512, 5) from dual;


String Functions
Function Input Argument Value Returned

First letter of each word is changed to uppercase and


INITCAP ( s ) s = character string
all other letters are in lower case.

LOWER ( s ) s = character string All letters are changed to lowercase.

UPPER ( s ) s = character string All letters are changed to uppercase.

CONCAT ( s1, s2 ) s1 and s2 are character strings Concatenation of s1 and s2. Equivalent to s1 || s2

s1 and s2 are character strings and n is Returns s1 right justified and padded left with n
LPAD ( s1, n [, s2] )
an integer value characters from s2; s2 defaults to space.

s1 and s2 are character strings and n is Returns s1 left justified and padded right with n
RPAD ( s1, n [, s2] )
an integer value characters from s2; s2 defaults to space.

s is a character string and set is a set of Returns s with characters removed up to the first
LTRIM ( s [, set ] )
characters character not in set; defaults to space

s is a character string and set is a set of Returns s with final characters removed after the last
RTRIM ( s [, set ] )
characters character not in set; defaults to space

REPLACE ( s,
s = character string, search_s = target Returns s with every occurrence of search_s in s
search_s [,
string, replace_s = replacement string replaced by replace_s; default removes search_s
replace_s ] )

SUBSTR ( s, m [, n ] s = character string, m = beginning Returns a substring from s, beginning in position m and
) position, n = number of characters n characters long; default returns to end of s.

LENGTH ( s ) s = character string Returns the number of characters in s.

s1 and s2 are character strings, m =


INSTR ( s1, s2 [, m Returns the position of the nth occurrence of s2 in s1,
beginning position, n = occurrence of s2
[, n ] ] ) beginning at position m, both m and n default to 1.
in s1

Here are some examples of the use of String functions:

select concat ('Alan', 'Turing') as "NAME" from dual;

select 'Alan' || 'Turing' as "NAME" from dual;

select initcap ("now is the time for all good men to come to the aid of the
party") as "SLOGAN" from dual;
select substr ('Alan Turing', 1, 4) as "FIRST" from dual;

String / Number Conversion Functions


Function Input Argument Value Returned

NANVL ( n2, n1 ) n1, n2 = value if (n2 = NaN) returns n1 else returns n2

TO_CHAR ( m [, fmt ] m = numeric value, fmt =


Number m converted to character string as specified by the format
) format

TO_NUMBER ( s [, s = character string, fmt =


Character string s converted to a number as specified by the format
fmt ] ) format

Formats for TO_CHAR Function


Symbol Explanation

9 Each 9 represents one digit in the result

0 Represents a leading zero to be displayed

Floating dollar sign printed to the left of


$
number

L Any local floating currency symbol

. Prints the decimal point

, Prints the comma to represent thousands

Group Functions
Function Input Argument Value Returned

AVG ( [ DISTINCT | ALL ]


col = column name The average value of that column
col )

COUNT ( * ) none Number of rows returned including duplicates and NULLs

COUNT ( [ DISTINCT | ALL


col = column name Number of rows where the value of the column is not NULL
] col )

MAX ( [ DISTINCT | ALL ]


col = column name Maximum value in the column
col )
MIN ( [ DISTINCT | ALL ]
col = column name Minimum value in the column
col )

SUM ( [ DISTINCT | ALL ]


col = column name Sum of the values in the column
col )

e1 and e2 are column Correlation coefficient between the two columns after
CORR ( e1, e2 )
names eliminating nulls

MEDIAN ( col ) col = column name Middle value in the sorted column, interpolating if necessary

STDDEV ( [ DISTINCT |
col = column name Standard deviation of the column ignoring NULL values
ALL ] col )

VARIANCE ( [ DISTINCT |
col = column name Variance of the column ignoring NULL values
ALL ] col )

Date and Time Functions


Function Input Argument Value Returned

ADD_MONTHS ( d, n ) d = date, n = number of months Date d plus n months

LAST_DAY ( d ) d = date Date of the last day of the month containing d

MONTHS_BETWEEN ( d,
d and e are dates Number of months by which e precedes d
e)

d = date, a = time zone (char), b The date and time in time zone b when date d is for
NEW_TIME ( d, a, b )
= time zone (char) time zone a

NEXT_DAY ( d, day ) d = date, day = day of the week Date of the first day of the week after d

SYSDATE none Current date and time

GREATEST ( d1, d2, ...,


d1 ... dn = list of dates Latest of the given dates
dn )

LEAST ( d1, d2, ..., dn ) d1 ... dn = list of dates Earliest of the given dates

Date Conversion Functions


Function Input Argument Value Returned
TO_CHAR ( d [, fmt d = date value, fmt = format for
The date d converted to a string in the given format
]) string

TO_DATE ( s [, fmt ] s = character string, fmt = format


String s converted to a date value
) for date

ROUND ( d [, fmt ] d = date value, fmt = format for


Date d rounded as specified by the format
) string

d = date value, fmt = format for


TRUNC ( d [, fmt ] ) Date d truncated as specified by the format
string

Date Formats
Format
Description Range of Values
Code

DD Day of the month 1 - 31

Name of the day in 3


DY SUN, ..., SAT
uppercase letters

Complete name of the day in


DAY uppercase, padded to 9 SUNDAY, ..., SATURDAY
characters

MM Number of the month 1 - 12

Name of the month in 3


MON JAN, ..., DEC
uppercase letters

Name of the month in


MONTH uppercase padded to a JANUARY, ..., DECEMBER
length of 9 characters

Roman numeral for the


RM I, ..., XII
month

YY or YYYY Two or four digit year 71 or 1971

HH:MI:SS Hours : Minutes : Seconds 10:28:53

HH 12 or Hour displayed in 12 or 24
1 - 12 or 1 - 24
HH 24 hour format
MI Minutes of the hour 0 - 59

SS Seconds of the minute 0 - 59

AM or PM Meridian indicator AM or PM

A suffix that forces the


SP e.g. TWO THOUSAND NINE
number to be spelled out.

A suffix meaning that the


TH ordinal number is to be e.g. 1st, 2nd, 3rd, ...
added

Prefix to DAY or MONTH or


FM e.g. MONDAY with no extra spaces at the end
YEAR to suppress padding

Here are some examples of the use of the Date functions:

select to_char ( sysdate, 'MON DD, YYYY' ) from dual;

select to_char ( sysdate, 'HH12:MI:SS AM' ) from dual;

select to_char ( new_time ( sysdate, 'CDT', 'GMT'), 'HH24:MI' ) from dual;

select greatest ( to_date ( 'JAN 19, 2000', 'MON DD, YYYY' ),


to_date ( 'SEP 27, 1999', 'MON DD, YYYY' ),
to_date ( '13-Mar-2009', 'DD-Mon-YYYY' ) )
from dual;

select next_day ( sysdate, 'FRIDAY' ) from dual;

select last_day ( add_months ( sysdate, 1 ) ) from dual;

What is an aggregate query in SQL?


An aggregate query is a method of deriving group and subgroup data by analysis of a set of individual data entries. The term is frequently used by
database developers and database administrators.

SQL Aggregate Functions: Explore 5 Types of Functions


An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL provides many aggregate functions that
include avg, count, sum, min, max, etc. An aggregate function ignores NULL values when it performs the calculation, except for the count function.

What is an Aggregate Function in SQL?


An aggregate function in SQL returns one value after calculating multiple values of a column. We often use aggregate functions with the GROUP
BY and HAVING clauses of the SELECT statement.

There are 5 types of SQL aggregate functions:

● Count()

● Sum()

● Avg()

● Min()
● Max()

COUNT() Function
The COUNT() function returns the number of rows in a database table.

Syntax:

COUNT(*)

or

COUNT( [ALL|DISTINCT] expression )

Example:

We will use the ‘products’ table from the sample database for our demonstration.

The following SQL statement fetches the number of products in the table.

This will produce the following result.

The below-given command will display those product ids where the unit price is greater than 4.

This will display the following result.


Let's look at how we can use GROUP BY and HAVING functions with the COUNT function.

Consider the following dataset:

The SQL command given below will list the number of customers in each city.

This will produce the following results:

SUM() Function

The SUM() function returns the total sum of a numeric column.


Syntax:

SUM()

or

SUM( [ALL|DISTINCT] expression )

Example:

The following SQL statement finds the sum of the "unit price" fields in the "products" table:

This will produce the following result.

Let’s look at how we can use GROUP BY and HAVING functions with the SUM function.

Consider the following dataset:

The SQL command below will list the number of customers in each city, having a sum of points greater
than 3000.

This will produce the following result:


AVG() Function

The AVG() function calculates the average of a set of values.

Syntax:

AVG()

or
AVG( [ALL|DISTINCT] expression )

Example:

The following SQL command calculates the average quantity in stock.

This will produce the following result.

MIN() Function

The MIN() aggregate function returns the lowest value (minimum) in a set of non-NULL values.

Syntax:

MIN()

or

MIN( [ALL|DISTINCT] expression )


Example:

The above code will give us the minimum quantity in stock in the products table.

Also Read: How to Aggregate Data Using Group By in SQL?

MAX() Function

The MAX() aggregate function returns the highest value (maximum) in a set of non-NULL values.

Syntax:

AVG()

or
AVG( [ALL|DISTINCT] expression )

Example:

The code depicted below will give us the maximum quantity in stock in the products table.

This will produce the following result.

What is join operator in SQL?


Table join operators create a data set from the columns of two or more related tables. An SQL join
operation matches rows from two or more related tables according to a condition and creates a single
data set with columns selected from across the multiple tables.
Table join operators
Table join operators create a data set from the columns of two or more related tables.

An SQL join operation matches rows from two or more related tables according to a condition and creates
a single data set with columns selected from across the multiple tables. Typically, the condition matches
keys from the two tables by an equality predicate. Join operators perform the same function in a data flow,
and support inner joins, outer joins, and cross-joins of multiple input data sets.

With a join operator, you can perform the following types of joins:

Inner

Rows that are not common to all of the tables being joined are dropped from the result table.

Left outer

Returns all the rows that would be returned by an inner join, plus all the rows from the left (or
first-listed) table that do not match any row from the right table.

Right outer

Returns all the inner-join rows, plus all the rows from the right (or second-listed) table that do not
match any row from the left table.

Full outer

Retains all rows from the joined tables, regardless of matches.

Cross

Produces the Cartesian product of all the rows in both tables. (This type of join occurs when you
do not specify a condition.)

How to use join operator in SQL?


SQL Server JOINS
1. Choose columns from each table that should be used in the join. A join condition indicates a foreign key from one table and its corresponding key in the
other table.
2. Specify the logical operator to compare values from the columns like =, <, or >.

What does join () mean?


The join() method takes all items in an iterable and joins them into one string. A string must be
specified as the separator.

Frontend and Backend


The frontend uses HTML, CSS, JavaScript, and frontend frameworks. The backend uses programming
languages like Java, Python, Ruby, APIs, and database management systems. Each user has their own
copy of an application, so the frontend does not have to handle concurrency issues.

What’s the Difference Between Frontend and Backend in Application Development?


Frontend and backend are two critical aspects of any application. The frontend is what your users see
and includes visual elements like buttons, checkboxes, graphics, and text messages. It allows your users
to interact with your application. The backend is the data and infrastructure that make your application
work. It stores and processes application data for your users.

How does the frontend of an application work?


The term frontend refers to the graphical user interface (GUI) that your users can directly interact with,
such as navigation menus, design elements, buttons, images, and graphs. In technical terms, a page or
screen that your user sees with several UI components is called a document object model (DOM).
Three primary computer languages affect how your users interact with your frontend:

● HTML defines the frontend structure and the different DOM elements
● Cascading Style Sheets (CSS) defines the style of a web application, including layout, fonts, colors, and
visual style
● JavaScript adds a layer of dynamic functionality by manipulating the DOM
JavaScript can trigger changes on a page and display new information. This means the frontend can
handle fundamental user interactions (or requests), like displaying a calendar or checking if your user has
entered a valid email address. The frontend passes on more complex requests to the backend.

How does the backend of an application work?


Sometimes called the server side, the backend of your application manages your web application's
overall functionality. When your user interacts with the frontend, the interaction sends a request to the
backend in HTTP format. The backend processes the request and returns a response.
When your backend processes a request, it usually interacts with the following:

● Database servers to retrieve or modify relevant data


● Microservices that perform a subset of the tasks your user requested
● Third-party APIs to gather additional information or perform additional functions
The backend uses several communication protocols and technologies to complete a request.
Additionally, it handles thousands of distinct requests simultaneously. The backend combines
concurrency and parallelism techniques, like distributing requests across many servers, caching, and
data duplication.
Key differences: frontend vs. backend
Frontend and backend are broad terms that logically group any application's different technologies and
software layers. The frontend focuses on those aspects your users can see. Conversely, the backend is
everything that makes your application function.
You can think of the frontend as the exterior of a car and the backend as all the machinery inside. A
beautifully designed car will only run optimally if the internal machinery works properly. However, certain
aspects of exterior design also contribute to speed and performance. Similarly, your application's
frontend and backend have to be designed cohesively for the best results.
Next, we discuss other key differences between frontend and backend.
Development goals
Full-stack development aims to create responsive, efficient, and functional applications. Frontend and backend developers have different goals to create the final application.

Frontend developers aim to develop a positive user experience, optimize the application for accessibility and performance, and create responsive designs. Their main
development goals are to ensure the frontend is easy to interact with, well designed, and fully responsive on different platforms and devices.

Backend developers build and then maintain the server-side operations of an application. Their main development goals are to create reliable architecture that performs
application functions accurately and efficiently. They aim to meet user requirements while fulfilling all security and cost considerations.

Technologies
Frontend development touches upon the user-facing side of a website. These technologies include computer languages like JavaScript, CSS, and HTML. Frontend software
development also uses frontend frameworks to speed up production efficiency.

Backend development uses programming languages like Ruby, Java, and Python to write server-side logic. Backend developers also use databases, storage technologies,
and API technologies so applications and systems communicate with each other.

You might also like