Introduction To SQL Database
Introduction To SQL Database
What Is a Database?
A database is a well-organized collection of data that is stored in an electronic format. To be
more specific, a SQL database is an electronic system that allows users to easily access,
manipulate, and update the data.
What Is a Database Management System?
Consider a School SQL Database which has a record of the present students and the previously
studied students in the Student Details table. Similarly, it may contain Faculty Details,
Management Details, Staff Details, and many more depending on the schools requirement. As
the data is in huge amounts, to manage it we need a database management system.
Almost all modern databases are managed by a Database Management System (DBMS).
Basically, it is a system software used for creating data in a systematic way and managing
databases.
Want to get certified in SQL? Learn all about SQL Server Certification!
How Does SQL Database Manage Data?
DBMS provides, for both users and programmers, a fundamental way to create, retrieve, update,
and manage data.
Consider a scenario where a student XYZ wants to change his address. The DBMS searches the
details of XYZ in the table Student Detailsfrom the database School Databaseand displays it for
the user, and then the user edits it.
Watch this SQL Full Course Tutorial
Now, we have a clear picture of a database and its managing system. Lets move on.
Types of Database Architecture
We have two types of database architecture:
File Server
Client-Server
Still have queries? Come to Intellipaats SQL Community, clarify all your doubts, and excel in
your career!
File Server Architecture
In the file server architecture, files are located on the local system. It is useful for sharing
information across a network. The client sends a request for a file over the network, and the file
server forwards the file to the client. This is considered to be the most primitive type of data
service used for exchanging information over a network. The file server provides access to
remote server processors too.
Here is an example to understand the implementation of the file server.
Suppose, you have an Excel file, and one of your friends requests you to send that file for some
information. So, you send a copy to your friend. Now when you make any changes in your
original Excel file, those changes would not be reflected in the file which is with your friend.
In this example, you are a file server and your friend is the device requesting the information.
We can conclude on the file server architecture by quoting that the server acts as a sorting device
and only one person at a time can have access to it.
Client-Server Architecture
In the client-server architecture, the database is the server and any application that uses the data
is a client.
Here is an example to explain the working of this server. Consider three OLE DB components or
client systems accessing the database at the same time. The systems have logged into the IRCTC
website to know the number of trains running from X destination to Y destination.
The client system sends the request to the network server. The network server sends the same
request to the database and the final result is sent to the client system. This process is conducted
when one system sends the request. But in real-time, there will be n number of systems and there
can be multiple requests that are sent at a time for the same data. The database server will have to
process all the requests simultaneously and send back the requested data to the client systems.
Types of Databases
The databases are classified into various databases depending upon the usage requirements.
Centralized database.
Distributed database.
Personal database.
End-user database.
Commercial database.
NoSQL database.
Operational database.
Relational database.
Cloud database.
Object-oriented database.
Graph database.
Features of SQL
Now we are good to go with SQL! As discussed before SQL full form is a structured query
language, it helps you to communicate with the database by commands. Here are some of the
features of SQL Database:
History of SQL
IBM Corporation, Inc. created the language Structured English Query Language (SEQUEL) to
implement Codds model. Later, SEQUEL was renamed SQL (still pronounced sequel). The first
commercially available implementation of SQL was released in 1979 by Relational Software,
Inc. (now Oracle). SQL is now widely recognised as the standard RDBMS language.
Why SQL
Since SQL can work with any database, it is the most widely used language for database access.
The databases in which you interact are programs that allow clients to logically store and manage
information. With SQL, we can have the following advantages.
SQL Process
When you want to run SQL Queries on any DBMS system, you must first decide the best method
for carrying out your request, and the SQL engine will determine how to interpret that task.
The following are some important components of the SQL process:
Query Dispatcher: The dispatchers task is to send the query request to either CQE or SQE,
depending on the querys attributes. The dispatcher is in charge of handling all inquiries. It
cant be avoided.
Optimization Engines: After considering several factors related to the objects referenced
and the conditions defined in the query, including the Optimizer Goal, the Query optimizer
determines the most efficient way to execute a SQL expression.
Classic Query Engine: For any fields that are empty, CQE will use default values to map
data into the record buffer. For fields that arent empty, SQE just maps data to the record
buffer.
SQL Query Engine: To access data in relational structures, a SQL query engine interprets
SQL commands and language. Many people use SQL query engines to perform CRUD
(create, read, update, and delete) operations and implement data policies that are required by
relational data models and database management systems.
Enroll now in SQL course in Bangalore to learn more about SQL concepts.
Types of SQL Statements
SQL statements are mainly classified into the following.
SQL Standards
SQL is a database management language. It entails database formation, deletion, row retrieval,
and modification, among other things. SQL is accepted as the standard language for relational
databases by both ANSI and the ISO/IEC. There are many sections of the SQL specifications.
The formal names of this standard are:
1
2
3
4
5 ANSI/ISO/IEC 9075:2003, "Database Language SQL",
Parts
6 1 ("SQL/Framework"),
7 2 ("SQL/Foundation"),
8 3 ("SQL/CLI"),
9 4 ("SQL/Persistent Stored Modules"),
1 9 ("SQL/Management of External Data"),
10 ("SQL/Object Language Binding"),
0 11 ("SQL/Schemata"),
1 13 ("SQL/Java Routines and Types"),
1 14 ("SQL/XML") and(SQL/MDA)
Database structures
Creating a database with SQL
SQL statements and clauses
SQL database management
MySQL and PostgreSQL
Master PHP
With these in-demand SQL skills you can land in positions as follows:
Database administrators(DBA)
Database Migration engineer
Data scientist
Big data architect
Features of SQL
SQL is one of the most demanding skills in the current world. Every day a huge amount of data
is collected and one has to deal with these databases to create insightful information. Hence, it is
important for us to learn SQL as it is a special-purpose database programming language that
helps in generating useful strategies from a database and can easily interact with large and
massive databases, no matter what the size is. These features of SQL make SQL the most
powerful tool. Hence, here are some of the major SQL features which makes it a successful
database programming language:
Data Definition Language (DDL) – DDL contains commands that define data
create – Creates a table
For example:
create table
tablex(attribute1 datatype…..attribute datatype);
drop – Deletes the table along with all the attributes
For example:
drop table tablex;
alter – Modifies the tables structures
For example:
alter table
tablex add(new row1 datatype……new rown datatype);
rename – Changes the name of a table.
For example:
rename tablex to tabley;
Data Manipulation Language (DML): DML contains commands that manipulate data
insert – Used after the create command to insert values in the table
For example:
insert into tabley values(attribute1 datatype);
:
:
:
insert into tabley values(attributen datatype);
delete – Deletes particular rows, tuples, or cardinality from the table
For example:
delete from tabley where condition;
update – Updates the tuples in the table
For example:
update tabley set tuplename=attributename;
Triggers – Performed when particular conditions are met on data. It has three parts.
Event – The change that activates the trigger
Condition – The test or query that is executed after the trigger is activated
Action – The procedure that is executed after the condition is met true
Client-server execution and remote database access – SQL commands can control how a
client application is allowed to access the database remotely.
Security and authentication – SQL can make sure that only specific details of the database
are visible to the user while the entire database is secured by DBMS.
Embedded SQL – SQL can embed languages like COBOL, C, Java, etc. to query at
runtime
Transaction Control Language – TCL is used to control the transactions with commands
like:
commit – Saves the database when its inconsistent
commit;
rollback – Rolls back to the previous transaction
rollback;
savepoint – Goes back to the previous transaction without going through the entire
transaction
savepoint;
Characteristics of SQL
High Performance
SQL provides high-performance programming capability for highly transactional, heavy
workload, and high usage database systems. SQL programming gives various ways to
describe the data more analytically.
High Availability
SQL is compatible with databases like MS Access, Microsoft SQL Server, MySQL, Oracle
Database, SAP HANA, SAP Adaptive Server, etc. All of these relational database
management systems support SQL and it is easy to create an application extension for
procedural programming and various other SQL functions which are additional features thus
converting SQL into a powerful tool.
All these features of SQL make it a robust and primary language for many organizations to
manage their large databases.
INSTALLING MS SQL SERVER – LAB 1
where CREATE DATABASE is the keyword and databasename is the name of the database,
followed by a semicolon.
Here are the steps how to Create a Database in SQL
Open the SQL software and create a new query by clicking on New Query
Type the syntax and give a name for your database (Here, we are creating a database happy)
1 CREATEDATABASEhappy;
Then hit You will see that your commands are executed successfully, and your table is
created.
Click on Refresh [ ] and you will find a database happy created in Object Explorer
Wish to get certified in SQL! Learn from our SQL expert and do excel in your career with
Intellipaats SQL certification.
How do we Use a SQL Database?
To Select and use a Database in SQL
Syntax:
1 USE databasename;
where USE is the keyword, and databasename is the name that we want to use (select it from
the existing database names), followed by a semicolon.
Once the database is selected, it remains default until another USE statement with a different
database is used. To check which database youre using, place your mouse pointer over the file
where youre executing the query.
Enroll now in SQL course in Bangalore to learn SQL concepts from experts.
How to Select a Database?
Here in the above image, the default database is the previously selected as SPARATA
To select the happydatabase, give the command
1 USE happy;
where DROP DATABASE is the keyword and databasename is the name of the database we
want to delete, followed by semicolon.
Delete a SQL Database
Here, we are deleting the igneous database; hence give the following command:
1 DROPDATABASEigneous;
Then hit Execute and Click on Refresh [ ], and the igneous database would not be
displayed on Object Explorer
This bring us to the end of this SQL Database tutorial part. Now youre ready to get started with
creating and modifying your database! Now you know how to create a database in SQL.
Meanwhile, there is a lot more you can do using SQL Database which we will see in the next
tutorial sections.
Overview of Tables in SQL
Tables are the fundamental way to store data in a relational database management system. It
contains a header row at the top of the table, which gives the list of column names, followed by
rows that contain data. We will discuss the basic operations performed on a database by using
important SQL operators.
What Is a Table in SQL?
A table is a database object which is composed of rows and columns in SQL. In simple terms, its
a collection of related data held in a table format.
Numerous tables may be present in a database. The table will list the number of columns but not
the number of rows because the latter is arbitrary.
Lets select the Student Details table from the school database used as the previous example. Any
number of student information can be placed into the Student Details table, however, the
columns should all be confined to and related to one another, such as Student_Name,
Student_ID, Age, BOD, Address, and Percentage of Marks.
The snapshot displays a table from an Employee Database, which contains employee details.
Records and Fields in SQL
In a table, there are rows and columns, with rows referred to as records and columns referred to
as fields. A column consists of data values of a specific type, such as numbers or alphabets, with
each row in the database having one value for that column.
Examples of columns include Age, Student_ID, or Student_Name. On the other hand, a row
represents a singular data item within a table, and all rows in the table have the same structure.
For instance, Shaze in the Student_Name column or 007 in the Student_ID column.
Let us understand fields and records in detail.
Records and Fields in SQL
In a table, there are rows and columns, with rows referred to as records and columns referred to
as fields. A column consists of data values of a specific type, such as numbers or alphabets, with
each row in the database having one value for that column.
Examples of columns include Age, Student_ID, or Student_Name. On the other hand, a row
represents a singular data item within a table, and all rows in the table have the same structure.
For instance, Shaze in the Student_Name column or 007 in the Student_ID column.
Let us understand fields and records in detail.
Curious about how data is stored and manipulated? Want to learn about it? Here is
the Database Course provided by Intellipaat.
Fields in SQL
Fields are basically columns in a table with specific information about the data.
Consider the snapshot below. There is an e_salary field in the table that provides information
about the salaries of different employees. Similarly, the e_age field provides information about
the age of different employees.
Read on: SQL constraints to enhance your knowledge!
Records in SQL
A record is basically an individual entry that exists in a table. Records give complete information
about a single entry or entity. Consider the snapshot below. One row is selected, i.e., Anne. This
row gives complete information about the particular employee, Anne.
So, now we know that a collection of records and fields makes a table, and a collection of tables
makes a database.
Data Types in SQL
SQL Data types inform a compiler or interpreter about the characteristics of the data used in a
program. In simple words, a data type is a particular kind of data item which helps define the
operations that can be performed on the data. There are different data types available like
character data type for the letters in the alphabet or Boolean data type for true or false values.
What Are SQL Data Types?
Data type in SQL basically defines the kind of data that will go into a particular column. All
entries of one particular column will be of the same data type.
Consider the salary table from an employee database. Lets take the e_salary column, for
example. The first value in this column is of an integer type; the second is also of the integer type
and, similarly, all the other entries of the e_salary column are of integer type. Now, consider
another column e_dept from the same table, all values entered in this column are of a character
type.
These data types contain constraints and integrity. Constraints are the limitations on data. They
can either be implemented to a column or to the table. When there is a violation between the data
action and the constraint, then the action is aborted. There are different types of constraints like
primary key, unique key, etc.
Different Data Types in SQL
SQL Data types are divided into three major categories, namely, numeric, character, and date and
time.
Go for this in-depth job-oriented SQL certification training now!
Numeric Data Types in SQL
Numeric data types store all numerical values or integer values.
Date data type in SQL helps us specify the date in a format. Lets say, if we want to store the
date, 2 January 2019, then first we will give the year which would be 2 0 1 9, then the
month which would be 0 1, and finally, the day which would be 0 2.
Time data type helps us specify the time represented in a format. Lets say, we want to store
the time 8:30:23 a.m. So, first well specify the hour which would be 0 8, then the minutes
which would be 3 0, and finally the seconds which would be 2 3.
Year data type holds year values such as 1995 or 2011
where CREATE TABLE is the keyword, tablename is the name of the table name, columns1 to
columnN are the set of columns, and PRIMARY KEY is a constraint followed by a semicolon
Lets create an employee table
1
Createthe table,
2 employee(
3 e_id intnotnull,
4 e_name varchar(20),
5 e_salary int,
6 e_age int,
e_gender varchar(20),
7 e_dept varchar(20),
8 primarykey(e_id)
9 );
Not null is the constraint used to signify that all cells of this column must have a value
Varchar stands for variable length character, and the value passed is the maximum length of
the character
Primary key constraints help uniquely identify all records from the table, and a table cannot
have more than one primary key
After writing the query, click on the execute button to check for errors
Once the query is executed, a message appears like Commands completed successfully
where DROP TABLE is the keyword and tablename is the name of the table followed by a
semicolon
1 DROPTABLEtest;
After writing the query, click on the execute button to check for errors
Once the query is executed, a message appears like Commands completed successfully.
SQL INSERT INTO Query
The INSERT statement is used to insert records in a table. The table selected to insert
data must have the same number of columns and values. In this tutorial section, we will
discuss on the Insert statement syntax with an example.
Only values:
Value of the data to be inserted is specified with the column names.
We are using the only values method in this tutorial section. In only values, the values entered
must be in an order according to the column.
Syntax
1 INSERTINTOtablename VALUES(value1, value2,….valueN);
where INSERT INTO and VALUES are the keywords and tablename is the name of the table;
value1 to valueN are the set of values, followed by a semicolon.
Values are given for each of the columns, respectively. Whenever a variable length character
appears, then the values are entered in a single quote. And when an integer appears, it is written
just like that.
Interested in learning SQL? Enroll in our SQL training now!
After writing the query, click on the execute button to check for errors
Once the query is executed, a message appears like Commands completed successfully
Repeat the procedure and create 5 more sets of entries. Once you enter the records, the
employee table will be displayed as follows:
Finally, our table is ready with the values. We have inserted six records and, this is the way
Insert query in SQL works. In the next tutorial section, we will learn how to select individual
records from a table.
SELECT Statement in SQL
The Select statement in SQL is the most commonly query-used statement in SQL. It is used to
either fetch data according to some specified rule or display an entire table in SQL. The data
displayed after the query execution is stored in a result table.
In this tutorial section, we will discuss on:
Wish to get certified in SQL! Learn SQL from top SQL experts and excel in your career with
intellipaats SQL certification.
A Brief on the SELECT Query in SQL
The Select query in SQL is one of the most important commands in SQL, and it is used to get
data from a table.
Syntax
1 SELECTcolumn1, column2, columnN
2 FROMtablename;
where SELECT and FROM are the keywords; column1 to columnN are a set of columns, and
tablename is the name of the table followed by a semicolon.
How to Select Data from a Table?
Lets display the name and age of an employee from the employee table
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
1 Select* fromemployee;
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
where SELECT DISTINCT and FROM are the keywords, column1 to columnN are a set of
columns, and tablename is the name of the table, followed by a semicolon.
How to Select Distinct Data from a Table?
Lets select some distinct values from our employee table. If we have a glance at the gender
column, we can see that two values are being repeated, male and female.
selectdistincte_gender
1 fromemployee;
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
When the distinct keyword was removed, all values got displayed., which gives us a clear picture
of the Select Distinct statement; it gets only the values which are different.
If you have any doubts or queries related to SQL, get them clarified from the SQL experts on
our SQL Community!
This bring us to the end of this Select Query in SQL. Here, we learned to use Select Command in
SQL and Select Distinct command in SQL .
What Is Where Clause in SQL?
The WHERE clause is a very powerful tool that can be used to filter data from a database. It can
be used to select specific rows, columns, and values from a table. The WHERE clause is used in
conjunction with the SELECT statement to specify the conditions that the rows in the result set
must meet.
The syntax for the WHERE clause is as follows:
WHERE <condition>
The WHERE clause can be used to perform complex filtering operations. For example, you
could use the WHERE clause to select all rows where the name column is equal to John and the
age column is greater than 21. You could also use the WHERE clause to select all rows where
the country column is in the list of countries USA, Canada, and UK, and the date_of_birth
column is between 1990-01-01 and 2000-01-01.
The WHERE clause is a powerful tool that can be used to filter data from a database. By
understanding how to use the WHERE clause, you can query your database more effectively and
efficiently.
Here are some additional tips for using the WHERE clause:
Use the LIKE operator to match patterns in strings. For example, you could use
the LIKE operator to select all rows where the name column contains the letter J.
Use the IN operator to match a value against a list of values. For example, you could use
the IN operator to select all rows where the country column is equal to USA, Canada, or UK.
Use the BETWEEN operator to match a value between two other values. For example, you
could use the BETWEEN operator to select all rows where the date_of_birth column is
between 1990-01-01 and 2000-01-01.
By following these tips, you can use the WHERE clause to filter data from your database more
effectively and efficiently.
Here is an example of how to use the WHERE clause to select all rows where the name column is
equal to John:
SELECT * FROM customers
WHERE name = 'John';
This query will return all rows from the customers the table where the value in the name the
column is equal to John.
Here is another example of how to use the WHERE clause to select all rows where the age column
is greater than 21:
SELECT * FROM customers
WHERE age >21;
This query will return all rows from the customers table where the value in the age column is
greater than 21.
Operators in SQL
These SQL operators are considered as a set of reserved words used in SQL Where clause. They
specify the condition and also serve as a conjunction for multiple conditions in a statement. In
this tutorial, we will discuss on:
where SELECT, FROM, WHERE, and AND are the keywords; column1 to columnN are a set of
columns; tablename is the name of the table, and condition1 to conditionN are a set of conditions
followed by a semicolon.
Lets display all employees whose age is below 30 and who belong to the operations
department from the employee table
Select e_name, e_age, e_salary From employee where e_age<30 and e_dept=operation;
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
The AND operator imposes a condition or multiple conditions in which the conditions must be
true, i.e., it must satisfy all the conditions.
Want to learn more about SQL check out our course on SQL Certification in Dublin.
OR operator in SQL and its syntax
The OR operator displays records for any condition separated by OR which is evaluated to true.
For example, if we have to filter out a software engineer or a doctor, then we use the OR
operator.
Syntax
SELECT column1, column2, … columnN
FROM tablename
WHERE [condition1], …, OR [conditionN];
where SELECT, FROM, WHERE, and OR are the keywords; column1 to columnN are a set of
columns; tablename is the name of the table, and condition1 to conditionN are a set of conditions
followed by a semicolon.
Lets display all employees who are from either the sales department or the operations
department from the employee table
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
The OR operator imposes a condition or multiple conditions in which either of the conditions
must be true.
NOT operator in SQL and its syntax
The NOT operator displays a record if the condition is not true. For example, if we have to
extract all records where the occupation of a person is not a software engineer, then the Not
operator is used.
Syntax
SELECT column1, column2, … columnN
FROM tablename
WHERE NOT [condition1];
where SELECT, FROM, WHERE, and NOT are the keywords; column1 to columnN are a set of
columns; tablename is the name of the table, and there is a condition followed by a semicolon.
Check out the SQL Interview Questions For Experienced list to prepare for your upcoming
interviews.
Lets display all employees whose gender is not equal to female from the employee table
After writing the query, click on the execute button to check for errors
Once the query is executed, the table appears
Well, this brings us to the end of this SQL Operates tutorial section. Now, youre ready to get
started with creating a table and conducting basic operations of filtering and imposing
conditions! While there is a lot more you can do with the data using SQL queries which we will
see in the following tutorial sections.
The BETWEEN operator in SQL serves as a tool for refining result sets by focusing on values
within a predefined range in a particular column. It facilitates the extraction of rows whose
column values lie within a specified range, encompassing both the lower and upper limits. SQL
queries frequently employ the BETWEEN operator to streamline the retrieval of data that
adheres to specific conditions.
SQL BETWEEN Syntax:
SELECTcolumn1,
column2, ...
1 FROMtable_name
2 WHEREcolumn_name
3 BETWEENvalue1 ANDvalue2;
column1, column2, ...: The columns you want to retrieve in the result set.
table_name: The name of the table you are querying.
column_name: The name of the column you want to apply the BETWEEN operator to.
value1 and value2: The lower and upper bounds of the range you want to filter on.
Usage Example: Suppose you have a table named employees with a column called, and you want
to retrieve all employees with salaries between $40,000 and $60,000:
SELECTfirst_name, last_name,
1 salary
2 FROMemployees
3 WHEREsalary BETWEEN40000 AND60000;
This SQL query will return all rows from the employees table where the salary falls within the
specified range.
Read on:- SQL Tutorial to enhance your knowledge!
Things to Note while using SQL BETWEEN Operator
1. Inclusive Range: The BETWEEN operator is inclusive, meaning it includes rows where the
column value is equal to the lower and upper bounds. In the example above, employees with
salaries of $40,000 and $60,000 would be included in the result.
2. Data Types: The values used with the BETWEEN operator must be of compatible data types
with the column being compared. For example, if youre comparing dates, the values should
be in a date format that the database can recognize.
3. Negation with NOT: You can also use NOT BETWEEN to retrieve rows that do not fall
within the specified range.
4. Complex Conditions: You can combine BETWEEN with other SQL operators and conditions
(e.g., AND, OR) to create more complex filtering criteria.
The SQL BETWEEN operator simplifies the process of selecting rows within a specific range of
values, making it a valuable tool for querying databases and retrieving relevant data for analysis
or reporting purposes.
Check the UPDATE Query in SQL blog!
Heres a step-by-step guide with SQL code for creating a database, or table, inserting data, and
using the BETWEEN operator:
Step 1: Create a Simple New Database in SQL
To create a new database in SQL, you can use the following code:
1 CREATEDATABASEMyDatabase;
CREATETABLEEmplo
yees (
1 EmployeeID
2 INTPRIMARYKEY,
3 FirstName
4 VARCHAR(50),
5 LastName
VARCHAR(50),
6 Salary
7 DECIMAL(10, 2)
8 );
This code creates a table named Employeeswith columns for EmployeeID, FirstName,
LastName, and Salary.
Step 3: Insert Data into the Table in SQL
Now, lets insert some sample data into the Employeestable:
1 INSERTINTOEmployees (EmployeeID, FirstName, LastName, Salary)
2 VALUES
3
(1, 'John', 'Doe', 50000.00),
4 (2, 'Jane', 'Smith', 60000.00),
5 (3, 'Alice', 'Johnson', 45000.00),
6 (4, 'Bob', 'Brown', 55000.00);
This SQL query will display all the records in the Employeestable.
Step 5: Use the BETWEEN Operator in SQL
Now, lets use the BETWEEN operator to retrieve employees with salaries between $45,000 and
$55,000:
SELECT* FROMEmployees
WHERESalary
1 BETWEEN45000.00
2 AND55000.00;
This SQL query will return the employees whose salaries fall within the specified range.
These steps demonstrate how to create a database, create a table, insert data, and use the
BETWEEN operator in SQL.
Here are the topics we are about to discuss in this blog:
where UPDATE, SET, and WHERE are the keywords, table_name is the name of the table you
want the update, col1, col2, … are the columns considered to be updated, val1, val2, … assign
new values, and the condition section is where the condition is given, followed by a semicolon.
Lets update some records of the employee table using the Update command in SQL
1 UPDATEemployee
2 SETe_age=42
3 WHEREe_name=sam;
Once the query is executed, a message appears like Commands completed successfully
Lets check the update
Now you can check out the updated data in the table.
Also, Check our blog on Replace in SQL: Usage and Implementation of REPLACE()
Function.
SQL Update Multiple Columns
Here is an example for updating multiple columns in SQL.
1 UPDATEEMPLOYEE
2 SETLast_Name='KAPADIA',First_Name='MANISH'
3 WHEREEmployee_ID=7369
After writing the query, click on the execute button to check for errors
Once the query is executed, a message appears like 1 row affected .
Now you can check out the updated data in the table.
Do you still have queries? Come to Intellipaats SQL Community, clarify all your doubts, and
excel in your career!
SQL Update Multiple Rows
UPDATEEmployee
1 SETMiddle_Name
2 =
3 CASEEmployee_ID
4 WHEN7369 THEN'A'
5 WHEN7499 THEN'B'
ELSEMiddle_Name
6 END
7 WHEREEmployee_ID
8 IN(7369,7499);
After writing the query, click on the execute button to check for errors
Once the query is executed, a message appears like 1 row affected .
Know the most common methods for executing function in sql by exploring our blog on how
to run function in SQL!
DELETE FROM: This part of the query indicates that you want to delete rows from a specific
table.
table_name: Replace this with the actual name of the table from which you want to delete
data.
WHERE condition: This is an optional part of the query that specifies the condition that must
be met for a row to be deleted. If you omit this part, all rows in the table will be deleted.
For example, consider a table named Employeeswith columns
EmployeeID,FirstName,LastName,and Salary.If you want to delete an employee with a specific
ID, the query might look like this:
1 DELETEFROMEmployees
2 WHEREEmployeeID = 101;
Its important to be cautious while using DELETE queries, especially without a specific
condition, as they can lead to unintended data loss. To avoid accidents, its recommended to
perform the following steps:
1. Backup: Before running DELETE queries, make sure you have a backup of your data. This
ensures that you can recover the data if something goes wrong.
2. Use SELECT First: If youre unsure about the records that will be deleted, you can first run
a SELECT query with the same condition to preview the data that will be affected.
3. Transaction: Wrap the DELETE query within a transaction if possible. This way, you can
roll back the transaction if something unexpected occurs.
4. Restrict Permissions: Limit DELETE permissions to authorized users only. This prevents
accidental or malicious deletion of data.
5. Test in Development: Always test DELETE queries in a development or testing
environment before applying them to production data.
This query will delete all rows where the stock quantity is less than 10.
Example 2: DELETE with Specific Condition Consider a table named Orderswith columns
OrderID,CustomerID,and OrderDate.You want to delete an order with a specific ID:
1 DELETEFROMOrders
2 WHEREOrderID = 12345;
This query will delete the customer with CustomerID 789 and all orders associated with that
customer.
Example 5: DELETE with Subquery Suppose you have a table named Employeesand you
want to delete employees who have not placed any orders in the Orderstable:
DELETEFROMEmployees
WHEREEmployeeID
1 NOTIN(SELECTDISTINCTEm
2 ployeeID FROMOrders);
This query will delete employees who do not have a corresponding entry in the Orderstable.
TRUNCATE TABLE: This part of the command indicates that you want to remove all rows from the
specified table.
table_name: Replace this with the name of the table you want to truncate.
Keep in mind the following points when using the TRUNCATE command:
1. Data Deletion: TRUNCATE deletes all rows from the table, and the operation is not reversible.
Its a quicker alternative to DELETE for removing all data.
2. Auto-commit: TRUNCATE is typically an auto-commit operation, meaning its immediately
committed to the database without needing an explicit transaction.
3. Table Structure: TRUNCATE retains the table structure, constraints, and indexes. Its like
starting with an empty table that has the same schema.
4. Permissions: TRUNCATE requires appropriate permissions on the table. Users must have at
least the ALTER privilege on the table.
5. Referential Integrity: If the table is referenced by foreign keys in other tables, you might need
to temporarily disable or drop these constraints before using TRUNCATE.
6. Cannot Be Rolled Back: Unlike transactions, TRUNCATE cannot be rolled back. Once the
command is executed, the data is permanently removed.
Prepare yourself for the industry by going through this Top SQL Interview Questions and
Answers!
Examples of SQL Truncate
Example 1: Basic TRUNCATE Suppose you have a table named Orderswith columns
OrderID,CustomerID,and OrderDate.You want to quickly remove all rows from the table:
1 TRUNCATETABLEOrders;
This command will remove all rows from the Orderstable while keeping its structure intact.
Example 2: TRUNCATE with Constraints If the table youre trying to truncate is referenced by
foreign keys in other tables, you might need to temporarily drop or disable the constraints:
-- Drop foreign key
constraints
ALTERTABLEOtherTable
DROPCONSTRAINTFK_ConstraintNa
1 me;
2
-- Truncate the main table
3 TRUNCATETABLEMainTable;
4
5 -- Recreate the foreign key
6 constraints
7 ALTERTABLEOtherTable
8 ADDCONSTRAINTFK_ConstraintNam
e
9 FOREIGNKEY(ForeignKeyColumn)
1 REFERENCESMainTable
0 (PrimaryKeyColumn);
In this example, you need to drop the foreign key constraints before truncating the main table and
then recreate them afterward.
Example 3: TRUNCATE with Identity Columns If your table has an identity column (auto-
incrementing), the identity value will be reset after truncating the table:
TRUNCATETABLEMyTable;
1 DBCC CHECKIDENT
2 ('MyTable', RESEED, 0);
After truncating, the identity columns value will start from 1 again.
Example 4: TRUNCATE with Log Space Reclamation TRUNCATE can help in freeing up the log
space used by the transactions. This can be beneficial when your transaction log becomes large due to
many DELETE operations:
1 BACKUP LOG YourDatabaseName TODISK = 'C:BackupYourDatabaseLogBackup.bak';
2 TRUNCATETABLEYourTable;
In this example, you back up the transaction log and then truncate the table to release the log space.
Example 5: TRUNCATE with WHERE Condition While TRUNCATE doesnt support a WHERE
clause like DELETE does, you can use a temporary table to achieve a similar result:
1
2 SELECT*
3 INTO#TempTable
4 FROMYourTable
5 WHERESomeConditi
on;
6
7 TRUNCATETABLEYou
8 rTable;
9
1 INSERTINTOYourTa
0 ble
SELECT*
1 FROM#TempTable;
1
1 DROPTABLE#TempTa
2 ble;
n this scenario, you first select the rows you want to keep into a temporary table, then truncate the
main table, and finally re-insert the selected rows back into the main table.
Remember, the TRUNCATE command is a powerful tool for quickly removing all rows from a table.
However, due to its irreversible nature, ensure that you have a backup of your data and understand the
potential impacts before using it, especially in production environments.
SQL training in Bangalore lets you learn about SQL concepts from expert. Enroll now!
SQL Delete vs SQL Truncate
Well, this how we work with Delete query in SQL and where to use Truncate command in SQL. The
table below gives a quick difference between these two commands.
Example:
Sort all the students in ascending order in SQL by the markscolumn.
1 SELECTName
2 FROMStudent_details
3 ORDERBYRoll_no ASC;
GROUP By in SQL:
It is used to arrange similar data into groups. The GROUP BY clause follows the WHERE clause
comes before the ORDER BY clause.
The GROUP BY statement is utilized to group rows with similar values into summary rows,
such as finding out the total number of Apples in each store. It is commonly combined with
aggregate functions like COUNT(), MAX(), MIN(), SUM(), and AVG() to group the result set
based on one or more columns.
Syntax of GROUP By in SQL:
1
2 SELECTcolumn1, column2…
FROMtable_name
3 WHERE[condition]
4 GROUPBYcolumn1, column2
5 ORDERBYcolumn1, column2;
Example:
If we want to know the total marks of each student, then GROUP BY is used as follows:
1 SELECTName, Sum(marks)
2 FROMStudent_details
3 GROUPBYName;
This query will return the number 10, which is the number of unique students in the students
table.
Examples in SQL DISTINCT
Here are some other examples of how to use the DISTINCT keyword in SQL:
To get a list of all of the unique cities in a country, we could use the following query:
To filter out duplicate rows from a list of products, we could use the following query:
SELECT DISTINCT product_name, product_price
FROM products;
Syntax:
SELECT column1, column2….
FROM table_name
WHERE column1 LIKE %XXX;
OR
SELECT column1, column2….
FROM table_name
WHERE column1 LIKE %XXX%;
OR
Dropping Columns
To remove a column from a table, you can use the DROP COLUMN clause in the ALTER
TABLE statement. Suppose you decide to remove the Phone_Numbercolumn from the
Customerstable.
1 ALTERTABLECustomers
2 DROPCOLUMNPhone_Number;
3. Managing Constraints
Adding Constraints
Constraints ensure data integrity. You can use the ALTER TABLE statement to add constraints
like primary keys, foreign keys, and unique constraints. For example, lets add a unique constraint
to the Emailcolumn in the Customerstable.
1 ALTERTABLECustomers
2 ADDCONSTRAINTUQ_Email UNIQUE(Email);
Dropping Constraints
To remove a constraint, use the DROP CONSTRAINT clause in the ALTER TABLE statement.
If you wish to drop the unique constraint on the Emailcolumn:
1 ALTERTABLECustomers
2 DROPCONSTRAINTUQ_Email;
4. Renaming Tables
The ALTER command allows you to rename a table easily. Suppose you want to rename the
Customerstable to Clients.
1 ALTERTABLECustomers
2 RENAME TOClients;
6. Real-world Examples
Adding Columns for Enhanced Data Tracking
Consider a scenario where an Orderstable lacks a Timestampcolumn for order placement. You
can use ALTER to rectify this.
1 ALTERTABLEOrders
2 ADDTimestampDATETIME;
Conclusion
Mastering the SQL ALTER command empowers you to adapt your database structures to
changing requirements without compromising data integrity. Whether youre adding columns,
altering data types, or managing constraints, the ALTER command is a versatile tool in your
database administration arsenal. Armed with the knowledge and practical examples provided in
this guide, youre now ready to navigate the world of SQL alterations with confidence.
How does SQL UNION work?
SQL UNION combines the results of two or more SELECT queries into a single result set. Its
important to note that UNION only returns distinct rows in the final result, automatically
eliminating any duplicate entries. To use UNION, the SELECT statements being combined must
have the same number of columns, and the columns must have compatible data types.
The syntax for a basic SQL UNION operation is as follows:
1 SELECTcolumn_name(s)
2 FROMtable1
3 UNION
4 SELECTcolumn_name(s)
5 FROMtable2;
In this example, we are combining the results of two SELECT queries, one from table1 and one
from table2. The column_name(s) keywords specify the columns that we want to include in the
final result set.
Practical Examples of SQL UNION
Conclusion
SQL UNION opens up a world of possibilities for combining and analyzing data from various
sources. Whether youre working with customer data, time-series records, or different types of
reports, UNION allows you to create a cohesive dataset for enhanced insights. By understanding
the syntax, use cases, and best practices of SQL UNION, youll be equipped to harness its
potential and take your data analysis skills to the next level.
LIKE and BETWEEN in SQL
LIKE and BETWEEN operators in SQL are used to compare values in a database. In this tutorial
section, we will discuss on:
Here are the examples of how we use the LIKE operator using wildcard
Like Operator Description
WHERE EmployeeName LIKE e Finds values that start with e
%
WHERE EmployeeName LIKE Finds values that end with e
%e
WHERE EmployeeName LIKE Finds values that have enat any position
%en%
WHERE EmployeeName LIKE _e Finds values that have eonly in the second position
%
WHERE EmployeeName LIKE Finds values that start with eand are at least 3 characters in
e__% length
WHERE EmployeeName LIKE e Finds values that start with eand end with 0
%0
where SELECT, FROM, WHERE, and LIKE are the keywords, column_list is the list of
columns, tablename is the name of the table, column_N is the column name, and there is
a pattern followed by a semicolon.
Let us take an example to understand this better, imagine that we want to extract a
persons name from the employee table below.
Demo Database
e_id e_name e_salary e_age e_gender e_dept
1 john 30000 25 male operations
2 julia 540000 27 female operations
3 anna 125000 27 female analytics
4 bob 50000 24 male support
5 max 540000 29 male operations
Lets do some operations with the LIKE query in SQL. Extract all records where the
employee name starts with the letter J
1 Select* fromemployee wheree_name LIKE'j%';
After writing the query, click on the execute button to check for errors. Once the SQL
query is executed, a message appears like Commands completed successfully. As we can
see in the result, we got only two rows in which the names start with the letter j.
Now, lets take another example in which we extract all records from the database where
the employee age is in the twenties.
Select* fromemployee wheree_age
1 LIKE'2_';
where SELECT, FROM, WHERE, BETWEEN, and AND are the keywords, column_list is a list
of columns, tablename is the name of the table, column_N is the column name, val1 is the
minimum value of the range, and val2 is the maximum value of the range, followed by a
semicolon. Lets, now, display employees aged between 25 and 35 from the above employee
table.
1 Select* Fromemployee wheree_age BETWEEN25 AND35;
Visit our SQL Community to get answers to all your queries!
After writing the query, click on the execute button to check for errors. Once the query is
executed, the table appears.
Lets display the salaries of employees between $60,000 and $120,000 from the employee table.
1 Select* Fromemployee wheree_salary BETWEEN60000 AND1200000;
After writing the query, click on the execute button to check for errors. Once the query is
executed, the table appears.
Well, this brings us to the end of this tutorial section. Now, youre ready to get started with using
LIKE in SQL and BETWEEN in SQL for comparing the values in your database.
What is Constraint in SQL?
Constraints are rules that are applied to the data columns of a table. They are used to ensure the
accuracy and consistency of the data in a table. If a constraint is violated, the action that is trying
to be performed is aborted.
SQL constraints can be specified when the table is created or after the table is created. They can
be column-level or table-level. Column-level constraints are applied to only one column, while
table-level constraints are applied to the whole table.
Here are some examples of SQL constraints:
NOT NULL constraint: This constraint ensures that the column cannot have a NULL
value.
UNIQUE constraint: This constraint ensures that each row in the table has a unique value
in the specified column.
CHECK constraint: This constraint ensures that the value in the column meets certain
criteria. For example, you could use a CHECK constraint to ensure that the value in a
column is between 1 and 100.
FOREIGN KEY constraint: This constraint ensures that the value in one column refers to
a valid value in another column. For example, you could use a FOREIGN KEY constraint to
ensure that the customer_id column in the orders table refers to a valid value in the
customers table.
Constraints are an important part of data integrity. By using constraints, you can ensure that
the data in your tables is accurate and consistent. This can help to prevent errors and
improve the quality of your data.
Constraints in SQL
Some of the commonly used Constraints in SQL are:
UNIQUE:
It ensures that all the values in the column are unique.
PRIMARY KEY:
It is a key which helps you to find the data from the table. It must be unique and not null.
FOREGIN KEY
A foreign key is a field in a relational table that matches the primary key column of another
table.
CHECK
It checks whether all values meets the specific condition or not.
DEFAULT
Itprovides the default value when the value is not specified.
Syntax:
CREATE TABLE table_name
(
Column1 datatype (size) constraint_name,
Column2 datatype (size) constraint_name,
Column3 datatype (size) constraint_name,
……….
);
Here, the column_name – Tells about the ground where formatting is required. And the format –
Defines the layout
For Example Table: Shopping
MerchandiseName Cost Date
–Where date is a suitable date and Format tells about the layout to be represented.
SQL Date Format Functions
In SQL, when working with a database, the format of the date in the table must be similar to the
input date. There are some default date formatfunctions present in SQL. Following are some of
the:
smalldatetimen 1 minute 4 no no
date time 0.00333 second 8 no no
datetime2 100 nanoseconds 6 to 8 yes no
datetimeoffset 100 nanoseconds 8 to 10 yes yes
Now, by giving the following syntax, the two tables are JOINed together to form a new table that
shows the name of the student, his/her city, marks obtained, and phone number.
SELECTName, City, Marks, Phone_no
FROMStudent_detail,
1 Personal_detail
2 WHEREStudent_details.Name=Persona
3 l_detail.Name;
Syntax:
1 SELECTColumn_list
2 FROMTABLE1
INNERJOINTABLE2
3 ONTable1.ColName = Table2.ColName
4
Example:
SELECTstudents_data.RollNo, students_data.Name, students_data.Address,
1 students_mark.Marks, students_mark.Grade
2 FROMstudents_data
3 INNERJOINstudents_mark ONstudents_data.RollNo = students_mark.RollNo;
Syntax:
1
SELECTcolumn_name
2 FROMtable1
3 LEFTJOINtable2
4 ONtable1.column_name=table2.column_name;
Example:
SELECTStudent_details.Name, Address,
1 Roll_no, Email_id
FROMStudent_details
2 LEFTJOINPersonal_details
3 ONStudent_details.Name=
4 Personal_details.Name;
Roll No. Address Email Id
Name
Akshay 1 Jaipur Akshay21@gmail.com
Charu 2 NULL NULL
Disha 3 Bombay Disha@gmail.com
Eva 4 NULL NULL
Himanshu 5 NULL NULL
Jitesh 6 Banglore Jitesh1990@gmail.com
Example:
SELECTPersonal_details.Name, Address, Roll_no,
1 Email_id
2 FROMStudent_details
3 RIGHTJOINPersonal_details
Akshay 1 Jaipur
Charu 2 NULL
Disha 3 Bombay
Eva 4 NULL
Himanshu 5 NULL
Jitesh 6 Banglore
where SELECT, LEFT JOIN, and ON are the keywords, columns are the list of columns, table1
is the first table and table2 is the second table, and column_x and column_y are the columns for
performing the LEFT JOIN, followed by a semicolon.
SQL LEFT JOIN Example
Lets apply LEFT JOIN to two tables, the employee table, and the department table
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 LEFTJOINdepartment
3 ONemployee.e_dept = department.d_name;
After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully
What is RIGHT JOIN in SQL?
RIGHT JOIN is a keyword, which is used to select all rows from the right table and also the
matched values between the two tables.
RIGHT JOIN in SQL
The RIGHT JOIN basically returns all records from the right table and the matched records from
the left table. For example, lets say, we have two tables, Table A and Table B, when the left join
is applied to these two tables, it would give all records from Table B and only the matched
records from Table A.
where SELECT, RIGHT JOIN, and ON are the keywords, columns is the list of
columns, table1 is the first table and table2 is the second table, and column_x and column_y are
the columns for performing the RIGHT JOIN, followed by a semicolon.
SQL RIGHT JOIN Example
Lets apply SQL RIGHT JOIN to two tables, the employee table, and the department table:
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 RIGHTJOINdepartment
3 ONemployee.e_dept = department.d_name;
After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully.
where SELECT, INNER JOIN, and ON are the keywords, columns are the list of columns,
table1 is the first table, table2 is the second table, and column_x and column_y are the columns
for performing the INNER JOIN, followed by a semicolon.
SQL INNER JOIN Example
Lets apply SQL INNER JOIN to two tables, the employee table, and the department table
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 INNERJOINdepartment
3 ONemployee.e_dept = department.d_name;
After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully.
This brings us to the end of this INNER JOIN in SQL tutorial section. Go ahead and link the
tables from your database to get a better insight into your data.
What is FULL JOIN in SQL?
Under SQL joins, FULL JOIN is a keyword, which is used to select all records from the right
table and also from the left table
FULL JOIN in SQL
The FULL JOIN basically returns all records from the left table and also from the right table. For
example, lets say, we have two tables, Table A and Table B. When FULL JOIN is applied on
these two tables, it returns us all records from both Table A and Table B. If the condition is not
met, then the null value is displayed instead.
where SELECT, FULL JOIN, and ON are the keywords, columns are the list of columns, table1
is the first table, table2 is the second table, and column_x and column_y are the columns for
performing Left Join, followed by a semicolon.
SQL FULL JOIN Example
Lets apply FULL JOIN to two tables, the employee table, and the department table
Selectemployee.e_name, employee.e_dept, department.d_name,
1 department.d_location fromemployee
2 FULLJOINdepartment
3 ONemployee.e_dept = department.d_name;
After writing the query, click on the execute button to check for errors. Once the query is
executed, a message appears like Commands completed successfully.
This brings us to the end of this tutorial section on JOIN operators.
What is RDBMS?
RDBMS stands for Relational Database Management System. It is an information management
system that is oriented on a data model. Here all the information is properly stored as tables.
RDBMS Example systems are SQL Server, Oracle, MySQL, MariaDB, and SQLite.
Basic Features of RDBMS:
Offers information to be saved in the tables
Numerous users can access it together which is managed by a single user
Virtual tables are available for storing the insightful data
In order to exclusively find out the rows, the primary key is used
The data are always saved in rows and columns
To retrieve the information the indexes are used
Columns are being shared between tables using the keys
RDBMS CONCEPTS
Relation in the RDBMS is the deposit of tuples having similar characteristics. A relation in
RDBMS means the set of the entities and data contained in them. The entities are different
instances and their relation is organized in different rows and columns in the data table. The
related information is of identical domains and constraints. By deleting old data and by inserting
new data, relations are altered in the database model.
Domain in RDBMS
The domain describes probable terms collected jointly that always have the same characteristics
and also constraints. A domain can be involved in a feature but only if the feature is a factor of a
particular set.
RDBMS Database
A relational database is a structured repository of data that arranges information in
predetermined connections. It stores data in tables consisting of columns and rows, enabling
clear visualization and comprehension of the relationships between various data elements.
The RDBMS speaks about relations between different entities present in the database.
Normal databases assist only the tables while RDBS along with the tables tells their connections
too. Normal databases give consistent methods but databases of RDBMS do not offer any
methodologies but instead give connections that connect one single object with another.
The stored database is called executable code. The database collects and saves data and that
particular procedure is called the stored procedure. During this, the codes are also stored which
are used for encapsulation, deleting, etc. The programmers are able to add extensions of the
syntaxes of SQL due to the applications of the APIs in the stored processes.
Constraints
Constraints are sort of limitations functional to the database. They make available the way to
employ the trade logic and the regulations in the database. In the database, it can be applied in
the type of confirming limits that verify the set of laws that the developer has missed. The
constraint is also restricting the facts that can be saved in the relations. They are applied to verify
the provinces performance and to keep it protected.
The Main Principles Of The RDBMS Model are:
Entity integrity: Entity integrity says that in a database, all the data should be organized
having a single key. The uniqueness of all the data is maintained by this principle.
Referential integrity: Referential integrity means that in the database all table values stay
true for all foreign keys.
RDBMS Operators
There are several relational operators that perform on the RDBMS. They are:
The union operator mingles the rows of 2 relations and ignores the replacement. It also takes
out the copied ones from the output.
The intersection operator gives a collection of rows that is identical to two relations.
The difference operator gives the result by having 2 relations and gives the difference of
rows from the first that dont exist in the second.
Cartesian product is done on two relations. It works as a cross-join operator.
First normal form (1NF): this table represents a relation of unique groups.
Second normal form (2NF): Is not practically charged on the division of any contender key.
Third normal form (3NF): every non-prime feature is non-transitively charged on every
contender key
Elementary key normal form: This key dependency modifies the practical dependency in a
table.
Advantages of Normalization
Data Integrity: Normalization reduces data redundancy, minimizing the risk of inconsistencies
and ensuring data integrity.
Flexibility: Normalized databases are more flexible and adaptable to changes in data
requirements.
Efficient Data Retrieval: Normalization improves query performance by reducing the size of
tables and eliminating unnecessary data repetition.
Simplified Updates: With normalized databases, updates are more straightforward and require
modifying data in fewer places.
Disadvantages of Normalization
Increased Complexity: The process of normalization can introduce complexity in designing and
maintaining the database structure.
Join Operations: Normalization often leads to the need for join operations to retrieve data from
multiple tables, which can impact query performance.
Overnormalization: Overnormalization, where excessive normalization is applied, can result in
unnecessary complexity and reduced performance.
Normalization:
Normalization is a technique which is used to organize the data in the database. It is a systematic
approach to remove the data redundancy. Normalization is mainly used for two purpose,
Without normalization 3 anomalies occurred and it becomes difficult to handle and update data.
To understand these anomalies lets take an Student table
ID Name Address Subject
201 Akshay Jaipur Maths
202 Charu Bombay Bio
203 Disha Banglore Physics
204 Eva Noida Maths
Updation Anamoly – To update address of a student who occurs twice or more than twice in
a table, we will have to updateAddress column in all the rows, else data will become
inconsistent.
Insertion Anamoly – Suppose for a new admission, we have a Student id, name and address
of a student but if student has not opted for any subject yet then we have to
insertNULL there, leading to Insertion Anamoly.
Deletion Anamoly – If id 401 has only one subject and temporarily he drops it, when we
delete that row, entire student record will be deleted along with id.
Normalization Form:
Normalization Rules are divided into 4 normal forms.
Charu 14 Biology
Disha 17 Maths
Akshay 15 Maths
Akshay 15 Physics
Charu 14 Biology
Disha 17 Maths
Using the First Normal Form, data redundancy increases, as there will be many columns with the
same data in multiple rows but each row as a whole will be unique.
Second Normal Form:
As per the Second Normal Form there must not be any partial dependency of any column on
primary key. It means that for a table that has concatenated primary key, each column in the
table that is not part of the primary key must depend upon the entire concatenated key for its
existence.
Meet all the requirements of the first normal form.
Remove subsets of data that apply to multiple rows of a table and place them in separate
tables.
Create relationships between these new tables and their predecessors through the use of
foreign keys.
For example:
New student table following 2NF will be:
Student Age
Akshay 15
Charu 14
Disha 17
In Student Table the candidate key will be Student column, because all other column i.e Age is
dependent on it.
Student Subject
Akshay Maths
Akshay Physics
Charu Biology
Disha Maths
In Subject Table the candidate key will be {Student, Subject} column. Now, both the above
tables qualifies for Second Normal Form and will never suffer from Update Anomalies.
Third Normal Form:
A relation is in third normal form (3NF) if it is in second normal form and it contains no
transitive dependencies.
Consider relation R containing attributes A, B and C. R(A, B, C)
If A →B and B →C then A →C
Transitive Dependency: Three attributes with the above dependencies.
For example:
Student_details table
ID Name Subject DOB Address Mobile No. City
Data Abstraction
Data abstraction is a fundamental concept in computer science and software development that
involves representing complex data and operations in a simplified and manageable way. It is a
technique that allows us to focus on the essential aspects of data while hiding unnecessary
details.
There are 3 stages of data generalization. And they are:
Physical level:
It is the least possible stage that explains how information is stored in the database.
Logical level:
It is the next senior stage in the ladder that gives the generalization. It tells what information is
stored and also tells the connection among them.
View level:
It is the uppermost stage in the ladder that explains part of the whole database. It enables the
consumer to view the database and do an inquiry.
Cardinality
For arranging and properly organizing the information stored, we use cardinality. This
arrangement tool is utilized in the entity-relationship diagrams representing relationships
between different entities in the table. The cardinality is of different types and they are :
One to one:
This cardinality connects one single object with another single object.
One to many:
This cardinality connects one single object with many single objects.
Many to many:
This cardinality connects many single objects with many other single objects.
Many to one:
This cardinality connects many objects with one single object
RDBMS Advantages
Data is only stored once so multiple documentation changes are not required
Better safety measures
The table arrangement is straightforward and simple for database users to appreciate and
use.
RDBMSs permit numerous database users to admittance a database concurrently.
RDBMS agree with the database manager to limit admission to certified users, and gift
rights to entity users depending on the kinds of database work they do
RDBMSs offer admission to the database via a server daemon, a dedicated software
program that responds to requirements on a set of connections, and enables database users to
connect and make use of the database.
RDBMSs feature safeguarding supply database managers with tools to without difficulty
preserve analysis, revamp, and back up the data centers.
RDBMSs support SQL language.