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

DBMS U-1

The document provides an introduction to Database Management Systems (DBMS) and Structured Query Language (SQL), explaining their functions, advantages, and features. It covers data definition commands, data types, creating table structures, and SQL constraints, emphasizing the importance of SQL in managing and manipulating databases. Additionally, it highlights the role of SQL in various applications, including client/server architecture and internet data access.

Uploaded by

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

DBMS U-1

The document provides an introduction to Database Management Systems (DBMS) and Structured Query Language (SQL), explaining their functions, advantages, and features. It covers data definition commands, data types, creating table structures, and SQL constraints, emphasizing the importance of SQL in managing and manipulating databases. Additionally, it highlights the role of SQL in various applications, including client/server architecture and internet data access.

Uploaded by

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

Database Management

System
Introduction to SQL
UNIT 1
What Does a DBMS Do?
• DBMS stands for Database Management System.
• If you have lots of data that you need to store, you don't just want to keep
it anywhere – then there would be no sense of what that huge amount of
data means or can tell you. That's why we use a DBMS.
• A database is basically where we store data that are related to one-
another – that is, inter-related data. This inter-related data is easy to work
with.
• A DBMS is software that manages the database. Some of the commonly
used DBMS (software) are MS ACCESS, MySQL, Oracle, and others.
• Suppose you have some data like different names, grades, and ID numbers
of students. You'd probably prefer to have that data in a nice table where a
particular row consists of students’ names, grades, and ID numbers. And to
help you organize and read that data efficiently, you'll want to use a DBMS.
• Using a DBMS goes hand in hand with SQL. This is because when you store
data and want to access and alter it, you'll use SQL.
Introduction to SQL
• The computer program that controls all the database is called a
DBMS (Database Management System).
• SQL stands for Structured Query Language. SQL is used to create,
remove, alter the database and database objects in a database
management system and to store, retrieve, update the data in a
database.
• SQL is a standard language for creating, accessing, manipulating
database management system.
• SQL works for all modern relational database management systems,
like SQL Server, Oracle, MySQL, etc.
Why SQL?
• SQL is widely popular because it offers the following advantages −
• Allows users to access data in the relational database management
systems.
• Allows users to describe the data.
• Allows users to define the data in a database and manipulate that
data.
• Allows to embed within other languages using SQL modules, libraries
& pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in a
database.
• Allows users to set permissions on tables, procedures and views.
Function of SQL
1. Data definition: SQL lets a user define the structure and organization of
the stored data and relationships among the stored data items.
2. Data retrieval: SQL allows a user or an application program to retrieve
stored data from the database and use it.
3. Data manipulation: SQL allows a user or an application program to
update the database by adding new data, removing old data, and
modifying previously stored data.
4. Access control: SQL can be used to restrict a user's ability to retrieve,
add, and modify data, processing stored data against unauthorized
access.
5. Data sharing: SQL is used to coordinate data sharing by concurrent
users, ensuring that they do not interfere with one another.
6. Data integrity: SQL defines integrity constraints in the database,
protecting it from corruption due to inconsistent updates or system
failures.
Role of SQL
1. SQI. is an interactive query language, Users type SQI. commands into an
interactive SQL. program to retrieve data and display it on the screen,
providing a convenient, easy-to-use tool for ad hoc database queries.
2. SQL. is a database programming language. Programmers embed SQL
commands into their application programs to access the data in a
database. Both user-written programs and database utility programs
(such as report writers and data entry tools) use this technique for
database access.
3. SQL is a database administration language. The database administrator
responsible for managing a minicomputer or mainframe database uses
SQL to define the database structure and control access to the stored
data.
4. SQL is a client/server language. Personal computer programs use SQL to
communicate over a network with database servers that store shared
data. This client/server architecture has become very popular for
enterprise-class applications.
5. SQL is an Internet data access language. Internet web servers that
interact with corporate data and Internet applications servers all
use SQL as a standard language for accessing corporate databases.
6. SQL is a distributed database language. Distributed database
management systems use SQL to help distribute data across many
connected computer systems. The DBMS software on each system
uses SQI. to communicate with the other systems, sending requests
for data access.
7. SQL is a database gateway language. In a computer network with
a mix of different DBMS products, SQI. is often used in a gateway
that allows one brand of DBMS to communicate with another
brand.
SQL Features and benefits
• SQL Standard: First standard for SQL was in 1986 by ANSI (American
National Standards Institute) and ISO (International Standards
Organization) followed in 1987. The latest standard part was made in 2011.
• Portable: SQL runs on mainframes, PCs, laptops, servers, tablets and
smartphones. It runs in local systems, intranet and internet. Databases
using SQL can be moved from device to another without problems.
• Open Source: Free databases from MySQL, MariaDB and Post Gres means,
SQL databases can be used at low cost and with large communities behind
them.
• Used by major DBMS system vendors: SQL is used by all vendors such as
IBM, Oracle and Microsoft who develop DBMS.
• Easy to learn and understand: SQL consists mainly of English statements
and making it easy to learn and write a SQL queries.
• Interactive language: SQL can be used to talk to databases and get
answers to complex questions in seconds.
• Programming language: SQL can be used by programmers writing
applications using databases, for example, shopping applications on
the internet.
• Complete language for a database: SQL is used to create databases,
manage security of a database. While its main use is for updating,
retrieving and sharing data with multiple users.
• Multiple data views: Different users of the database can by SQL be
given different views of the structure and content of the database.
• Client/Server language: SQL is used to connect front end computers
(clients) and back end databases (servers). Thus, supporting the
client-server architecture.
• Internet usage: SQL can be used in three tiered Internet architecture.
The architecture includes a client, application server and a database.
• SQL a highly desirable skill: Many jobs including IT support, web
development and business data analysis require skills in SQL.
Data definition commands
• DDL (Data Definition Language) is a standard subset of SQL that is
used to define tables(database structure), and other metadata
related things.
• DDL changes the structure of the table like creating a table, deleting a
table, altering a table, etc.
• 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:
• CREATE
• ALTER
• DROP
• TRUNCATE
1. CREATE:
It is used to create a new table in the database.
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE
);
2. DROP:
It is used to delete both the structure and record stored in the table.
Syntax
DROP TABLE table_name;
Example
DROP TABLE EMPLOYEE;
3. 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:
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
ALTER TABLE table_name MODIFY(column_definitions....);
EXAMPLE:
ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));
ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
4.TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
Syntax:
• TRUNCATE TABLE table_name;
Example:
• TRUNCATE TABLE EMPLOYEE;
Data Types
• Data types are used to represent the nature of the data that can be
stored in the database table.
• For example, in a particular column of a table, if we want to store a
string type of data then we will have to declare a string data type of
this column.
Data types mainly classified into three categories for every database.
• String Data types
• Numeric Data types
• Date and time Data types
char(n) It is a fixed width character string
Character data type. Its size can be up to
String Data 8000 characters.
Types
varchar(n) It is a variable width character
string data type. Its size can be up
to 8000 characters.

varchar(max) It is a variable width character


string data types. Its size can be
up to 1,073,741,824 characters.

text It is a variable width character


string data type. Its size can be up
to 2GB of text data.
nchar It is a fixed width Unicode string data
Unicode Character type. Its size can be up to 4000
String Data Types characters.
nvarchar It is a variable width Unicode string
data type. Its size can be up to 4000
characters.
ntext It is a variable width Unicode string
data type. Its size can be up to 2GB of
text data.
binary(n) It is a fixed width Binary string data
type. Its size can be up to 8000 bytes.

varbinary It is a variable width Binary string data


type. Its size can be up to 8000 bytes.

image It is also a variable width Binary string


data type. Its size can be up to 2GB.
bit It is an integer that can be 0, 1 or null.

tinyint It allows whole numbers from 0 to 255.


SQL Numeric
Smallint It allows whole numbers between -32,768 and 32,767.
Data Types
Int It allows whole numbers between -2,147,483,648 and
2,147,483,647.

bigint It allows whole numbers between -


9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

float(n) It is used to specify floating precision number data from -


1.79E+308 to 1.79E+308. The n parameter indicates whether
the field should hold the 4 or 8 bytes. Default value of n is 53.

real It is a floating precision number data from -3.40E+38 to


3.40E+38.

money It is used to specify monetary data from -


922,337,233,685,477.5808 to 922,337,203,685,477.5807.
datetime It is used to specify date and time combination. It
supports range from January 1, 1753, to December
SQL Date and 31, 9999 with an accuracy of 3.33 milliseconds.
Time Data
Types datetime2 It is used to specify date and time combination. It
supports range from January 1, 0001 to December
31, 9999 with an accuracy of 100 nanoseconds

date It is used to store date only. It supports range from


January 1, 0001 to December 31, 9999
time It stores time only to an accuracy of 100
nanoseconds
Sql_variant It is used for various data types
Misc Data except for text, timestamp, and
Types: ntext. It stores up to 8000 bytes of
data.
XML It stores XML formatted data.
Maximum 2GB.
cursor It stores a reference to a cursor
used for database operations.
In SQL, we have different datatypes
that will not come under string
datatypes, binary data types, date
table It stores result set for later
and time and numeric processing.
datatypes those will be called
miscellaneous(Misc) or other data uniqueidentifie It stores GUID (Globally unique
types.
r identifier).
Creating Table Structures
• Tables are used to store data in the database. Tables are uniquely named
within a database and schema.
• Each table contains one or more columns. And each column has an
associated data type that defines the kind of data it can store e.g.,
numbers, strings, or temporal data.
To create a new table, you use the CREATE TABLE statement as follows:
CREATE TABLE [database_name.][schema_name.]table_name (
pk_column data_type PRIMARY KEY,
column_1 data_type NOT NULL,
column_2 data_type,
...,
table_constraints
);
The following CREATE TABLE statement creates the Employee table.

CREATE TABLE Employee


(
EmployeeID int,
FirstName nvarchar(50) NOT NULL,
LastName nvarchar(50) NOT NULL,
Email nvarchar(50),
Phone varchar(15),
HireDate date,
Salary Money
);
• First, specify the name of the database in which the table is created.
The database_name must be the name of an existing database. If
you don’t specify it, the database_name defaults to the current
database.
• Second, specify the schema to which the new table belongs.
• Third, specify the name of the new table.
• Fourth, each table should have a primary key which consists of one or
more columns. Typically, you list the primary key columns first and
then other columns. If the primary key contains only one column, you
can use the PRIMARY KEY keywords after the column name. If the
primary key consists of two or more columns, you need to specify
the PRIMARY KEY constraint as a table constraint. Each column has
an associated data type specified after its name in the statement. A
column may have one or more column constraints such as NOT
NULL and UNIQUE.
SQL Constraints
• Constraints in SQL means we are applying certain conditions or restrictions
on the database.
• This further means that before inserting data into the database, we are
checking for some conditions.
• If the condition we have applied to the database holds true for the data
which is to be inserted, then only the data will be inserted into the
database tables.
Constraints available in SQL are:
▪ NOT NULL
▪ UNIQUE
▪ PRIMARY KEY
▪ FOREIGN KEY
▪ CHECK
▪ DEFAULT
1. NOT NULL:
• NULL means empty, i.e., the value is not available.
• Whenever a table's column is declared as NOT NULL, then the
value for that column cannot be empty for any of the table's
records.
• There must exist a value in the column to which the NOT NULL
constraint is applied.
• NOTE: NULL does not mean zero. NULL means empty column,
not even zero.
Syntax to apply the NOT NULL constraint during table creation:
CREATE TABLE TableName (ColumnName1 datatype NOT NULL,
ColumnName2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply a NOT NULL constraint on one of the
table's column while creating a table.
CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(
20), Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), St
udent_Email_ID VARCHAR(40));
Example to apply the NOT NULL constraint on an existing table's column:
ALTER TABLE student CHANGE StudentID StudentID INT NOT NULL;
To verify that the not null constraint is applied to the student table's column, we
will execute the following query:
DESC student;
2. UNIQUE:
• Duplicate values are not allowed in the columns to which the UNIQUE
constraint is applied.
• The column with the unique constraint will always contain a unique
value.
• This constraint can be applied to one or more than one column of a
table, which means more than one unique constraint can exist on a
single table.
• Using the UNIQUE constraint, you can also modify the already
created tables.
Syntax to apply the UNIQUE constraint on a single column:
CREATE TABLE TableName (ColumnName1 datatype UNIQUE, Column
Name2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply a UNIQUE constraint on one of the table's
column while creating a table.
• CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(
20), Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20),
Student_Email_ID VARCHAR(40));
Example to apply the UNIQUE constraint on more than one column:
• CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Stud
ent_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_
Email_ID VARCHAR(40), UNIQUE(StudentID, Student_PhoneNumber));
Example apply the UNIQUE constraint on an existing table's column:
• ALTER TABLE student ADD UNIQUE (StudentID);
To verify that the unique constraint is applied to the table's column and the
student table is created successfully, we will execute the following query:
• DESC student;
3. PRIMARY KEY:
• PRIMARY KEY Constraint is a combination of NOT NULL and Unique
constraints.
• NOT NULL constraint and a UNIQUE constraint together forms a
PRIMARY constraint.
• The column to which we have applied the primary constraint will
always contain a unique value and will not allow null values.

Syntax of primary key constraint during table creation:


• CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, C
olumnName2 datatype,…., ColumnNameN datatype);
Example:
• Create a student table and apply the PRIMARY KEY constraint
while creating a table.
• CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstNa
me VARCHAR(20), Student_LastName VARCHAR(20), Student_Phone
Number VARCHAR(20), Student_Email_ID VARCHAR(40));

Example to apply the primary key constraint on an existing table's


column:
• ALTER TABLE student ADD PRIMARY KEY (StudentID);
4. FOREIGN KEY:
• A foreign key is used for referential integrity.
• When we have two tables, and one table takes reference from
another table, i.e., the same column is present in both the tables and
that column acts as a primary key in one table. That particular column
will act as a foreign key in another table.
Syntax to apply a foreign key constraint during table creation:
• CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY K
EY, ColumnNameN Datatype(SIZE), FOREIGN KEY( ColumnName ) REF
ERENCES PARENT_TABLE_NAME(Primary_Key_ColumnName));
Example:
Create an employee table and apply the FOREIGN KEY constraint while
creating a table.
To create a foreign key on any table, first, we need to create a primary
key on a table.
• CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp
_Name VARCHAR (40), Emp_Salary VARCHAR (40));
Now, we will write a query to apply a foreign key on the department
table referring to the primary key of the employee table, i.e., Emp_ID.
• CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, De
pt_Name VARCHAR(40), Emp_ID INT NOT NULL, FOREIGN KEY(Emp_I
D) REFERENCES employee(Emp_ID));
Example to apply the foreign key constraint on an existing
table's column:
• ALTER TABLE department ADD FOREIGN KEY (Emp_ID) REFERENCES
employee (Emp_ID);
5. CHECK:
• Whenever a check constraint is applied to the table's column, and the
user wants to insert the value in it, then the value will first be
checked for certain conditions before inserting the value into that
column.
• For example: if we have an age column in a table, then the user will
insert any value of his choice. The user will also enter even a negative
value or any other invalid value. But, if the user has applied check
constraint on the age column with the condition age greater than 18.
Then in such cases, even if a user tries to insert an invalid value such
as zero or any other value less than 18, then the age column will not
accept that value and will not allow the user to insert it due to the
application of check constraint on the age column.
Syntax to apply check constraint on a single column:
• CREATE TABLE TableName (ColumnName1 datatype CHECK (Column
Name1 Condition), ColumnName2 datatype,…., ColumnNameN datat
Example:
Create a student table and apply CHECK constraint to check for the age
less than or equal to 15 while creating a table.
• CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(
20), Student_LastName VARCHAR(20), Student_PhoneNumber VARC
HAR(20), Student_Email_ID VARCHAR(40), Age INT CHECK( Age <= 15
));
To apply check constraint on multiple columns:
• CREATE TABLE student(StudentID INT, Student_FirstName VARCHA
R(20), Student_LastName VARCHAR(20), Student_PhoneNumber V
ARCHAR(20), Student_Email_ID VARCHAR(40), Age INT, Percentage
INT, CHECK( Age <= 15 AND Percentage > 85));
To apply check constraint on an existing table's column:
• ALTER TABLE student ADD CHECK ( Age <=15 );
6. DEFAULT:
Whenever a default constraint is applied to the table's column, and the
user has not specified the value to be inserted in it, then the default
value which was specified while applying the default constraint will be
inserted into that particular column.

Syntax to apply default constraint during table creation:


• CREATE TABLE TableName (ColumnName1 datatype DEFAULT Valu
e, ColumnName2 datatype,…., ColumnNameN datatype);
Example:
• Create a student table and apply the default constraint while
creating a table.
• CREATE TABLE student(StudentID INT, Student_FirstName VARCHA
R(20), Student_LastName VARCHAR(20), Student_PhoneNumber V
ARCHAR(20), Student_Email_ID VARCHAR(40) DEFAULT "anuja.k8
@gmail.com");

To apply default constraint on an existing table's column:


• ALTER TABLE student ALTER Student_Email_ID SET DEFAULT "anuja.k
[email protected]";
Data Manipulation Commands
DML is the short name for Data Manipulation Language which deals
with data manipulation and includes most common SQL statements
such SELECT, INSERT, UPDATE, DELETE, etc., and it is used to store,
modify, retrieve, delete and update data in a database.
Data Manipulation Commands :
• SELECT Command
• INSERT Command
• UPDATE Command
• DELETE Command
Example:
• SELECT * FROM Student;
shows all the values of a specific column from the table.
• SELECT Emp_Id, Emp_Salary FROM Employee;
If you want to access all the records of those students whose marks is
80 from the above table, then you have to write the following DML
command in SQL:
• SELECT * FROM Student WHERE Stu_Marks = 80;
SELECT
SELECT is the most important data manipulation command in
Structured Query Language. The SELECT command shows the records
of the specified table. It also shows the particular record of a particular
column by using the WHERE clause.
Syntax:
• SELECT column_Name_1, column_Name_2, ….., column_Name_N FR
OM Name_of_table;
Here, column_Name_1, column_Name_2, ….., column_Name_N are
the names of those columns whose data we want to retrieve from the
table.
If we want to retrieve the data from all the columns of the table, we
have to use the following SELECT command:
• SELECT * FROM table_name;
INSERT:
INSERT is another most important data manipulation command in
Structured Query Language, which allows users to insert data in
database tables.

Syntax :
INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 , colum
n_Name3 , .... column_NameN ) VALUES (value_1, value_2, value_3, ...
. value_N )

Example:
INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUES
(104, Anmol, 89, 19);
UPDATE:
UPDATE is another most important data manipulation command in
Structured Query Language, which allows users to update or modify
the existing data in database tables.
Syntax:
UPDATE Table_name SET [column_name1= value_1, ….., column_nam
eN = value_N] WHERE CONDITION;
Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords.
Example:
1.how to update the value of a single field.
Suppose, you want to update the Product_Price of the product whose
Product_Id is P102. To do this, you have to write the following DML
UPDATE command:
• UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102' ;
2. how to update the value of multiple fields of the database table.
Suppose, you want to update Stu_Marks and Stu_Age of that student
whose Stu_Id is 103 and 202. To do this, you have to write the
following DML Update command:
• UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id =
103 AND Stu_Id = 202;
DELETE :
DELETE is a DML command which allows SQL users to remove single or
multiple existing records from the database tables.
This command of Data Manipulation Language does not delete the
stored data permanently from the database. We use the WHERE clause
with the DELETE command to select specific rows from the table.
Syntax:
• DELETE FROM Table_Name WHERE condition;
Example:
1. how to delete a single record from the table.
Suppose, you want to delete that product from the Product table
whose Product_Id is P203. To do this, you have to write the following
DML DELETE command:
• DELETE FROM Product WHERE Product_Id = 'P202' ;
how to delete the multiple records or rows from the database table.
Suppose, you want to delete the record of those students whose
Marks is greater than 70. To do this, you have to write the following
DML Update command:
• DELETE FROM Student WHERE Stu_Marks > 70 ;
COMMIT AND ROLLBACK:
• Commit and rollback are the transaction control commands in SQL.
• If you want to save all the commands which are executed in a transaction,
then just after completing the transaction, you have to execute
the commit command.
• This command will save all the commands which are executed on a table.
All these changes made to the table will be saved to the disk permanently.
• Whenever the commit command is executed in SQL, all the updations
which we have carried on the table will be uploaded to the server, and
hence our work will be saved.
• The rollback command is used to get back to the previous permanent
status of the table, which is saved by the commit command.
• Suppose, we have started editing a table and later thought that the
changes that we have recently carried out on a table are not required.
Then, in that case, we can roll back our transaction, which simply means to
get back to the previous permanent status of the table, which is saved by
the commit command.
Note: One thing to note about the rollback command is that if you
have already committed your recent changes, you cannot rollback your
transaction. In that case, you can only roll to the last permanent
change.
Syntax:
• We will commit our transaction to save all the changes
permanently to the disk. [COMMIT;]
• Now, turn off the auto-commit by setting the value of auto-commit
as 0. [SET autocommit = 0;]
SQL Arithmetic Operators:
In Structured Query Language, the arithmetic operators are used to perform
mathematical operations on the numerical values stored in the database
tables.
We can use these operators with the SELECT statement in SQL. We can also
use the WHERE clause in the SELECT statement for performing operations on
particular rows.
These types of operators are used between two numerical operands for
performing addition, subtraction, multiplication, and division operations.

The arithmetic operators in SQL are categorized into the following five
types:
• SQL Addition Operator (+)
• SQL Subtraction Operator (-)
• SQL Multiplication Operator (*)
• SQL Division Operator (/)
• SQL Modulus Operator (%)
SQL Addition Operator (+):
The SQL Addition Operator performs the addition on the numerical columns in the
table.
If you want to add the values of two numerical columns in the table, then you have
to specify both columns as the first and second operand. You can also add the new
integer value in the value of the integer column.
Syntax:
• SELECT Column_Name_1 Addition_Operator Column_Name2 FROM Table_Name
WHERE Condition;
Example:
• SELECT Emp_Salary + Emp_Bonus AS Emp_Total_Salary FROM Employee;
The following query adds 15000 to the salary of each employee in the Emp_Salary
column of the Employee table:
• SELECT Emp_Salary + 15000 AS Emp_Updated_Salary FROM Employee;
The following query performs the addition operation on the above Employee table
with the WHERE clause:
• SELECT Emp_Salary + Emp_Bonus AS Emp_Total_Salary FROM Employee WHERE
Emp_Salary > 25000;
It shows only records of those employees whose Emp_Salary is greater than
25000.
SQL Subtraction Operator (-):
The SQL Subtraction Operator performs the subtraction on the
numerical columns in the table.
If we want to subtract the values of one numerical column from the
values of another numerical column, then we have to specify both
columns as the first and second operand. We can also subtract the
integer value from the values of the integer column.
Syntax:
• SELECT Column_Name_1 Subtraction_Operator Column_Name2 FRO
M Table_Name;
Syntax with WHERE clause:
• SELECT Column_Name_1 Subtraction_Operator Column_Name2 FR
OM Table_Name WHERE Condition;
Example:
• The following query subtracts the values of the Emp_Panelty column
from the Emp_Salary column of the Employee table using the
subtraction operator:
• SELECT Emp_Salary - Emp_Panelty AS Emp_Total_Salary FROM
Employee;
• The following query performs the subtraction operation on the above
Employee table with the WHERE clause:
• SELECT Emp_Panelty - Emp_Salary AS Emp_Total_Salary FROM
Employee WHERE Employee_ID = 104;
• The following query subtracts 10000 from the salary of each
employee of the Employee table:
• SELECT Emp_Salary - 10000 AS Emp_Updated_Salary FROM
Employee;
SQL Multiplication Operator (*):
The SQL Multiplication Operator performs the multiplication on the
numerical columns in the table.
If you want to multiply the values of two numerical columns, then you
have to specify both columns as the first and second operand. You can
also multiply the integer value with the values of an integer column.
Syntax of SQL Multiplication Operator:
• SELECT Column_Name_1 Multiplication_Operator Column_Name2 FR
OM Table_Name;
using the WHERE clause with the multiplication operator is given
below:
• SELECT Column_Name_1 Multilplication_Operator Column_Name2 F
ROM Table_Name WHERE Condition;
Example:
• The following query multiplies the
values of the Car_Amount column
with the Car_Price column of the
Cars table using the Multiplication
operator:
• SELECT Car_Amount * Car_Price AS
Car_Total_Price FROM Cars;
• The following query performs the
multiplication operation on the
above Cars table with the WHERE
clause:
• SELECT Car_Amount * Car_Price AS
Car_Total_Price FROM Cars WHERE
Car_Price >= 1000000;
SQL Division Operator (/):
The SQL Division operator divides the numerical values of one
column by the numerical values of another column.
Syntax of SQL Division Operator:
• SELECT Column_Name_1 Division_Operator Column_Name2
FROM Table_Name;
using the WHERE clause with the division operator is given
below:
• SELECT Column_Name_1 Division_Operator Column_Name
2 FROM Table_Name <strong>WHERE Condition;
Example:
The following query divides the values of
the Car_Price column by the Car_Amount column of
the Cars table using the Multiplication operator:
• SELECT Car_Price / Car_Amount AS One_Car_Price FROM Ca
rs;

with the WHERE clause:


• SELECT Car_Price / Car_Amount AS One_Car_Price FROM Ca
rs WHERE Car_Number = 9258;
SQL Modulus Operator (%):
The SQL Modulus Operator provides the remainder when the
numerical values of one column are divided by the numerical values of
another column.
Syntax of Modulus Operator in SQL:
• SELECT Column_Name_1 Modulus_Operator Column_Name2 FROM
Table_Name;
Example:
The following query divides the marks Student_English column by
Marks of Student_Maths of each student in the Student table:
• SELECT Student_English % Student_Maths AS Remainder FROM Stud
ent;
Comparison Operators:
Index Comparison Operator Description

1) = It specifies equal symbol.

2) <> It specifies not equal symbol.

3) != It specifies not equal symbol.

4) > It specifies greater than symbol.

5) >= It specifies greater than or equal symbol.

6) < It specifies less than symbol.

7) <= It specifies less than or equal symbol.

8) !> It specifies not greater than symbol.

9) !< It specifies not less than symbol.


Example:
1.Equality Operator:
SELECT *
FROM suppliers
WHERE supplier_name = 'Microsoft';
2.Inequality Operator:
SELECT *
FROM suppliers
WHERE supplier_name <> 'Microsoft';
OR enter this next SQL statement to use the != operator:
SELECT *
FROM suppliers
WHERE supplier_name != 'Microsoft';

https://www.techonthenet.com/sql/comparison_operators.php
SQL LOGICAL OPERATORS:
The Logical Operator is nothing but which returns the result in one form, i.e.,
either it will display the query is true, or the query is false. The results
displayed to combine or merge more than one true or false data.
The Logical Operators in SQL are as follows:
• SQL AND OPERATOR
• SQL OR OPERATOR
• SQL NOT OPERATOR
• SQL BETWEEN OPERATOR
• SQL IN OPERATOR
• SQL LIKE OPERATOR
Example:
AND:
SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;
OR:
SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;
Special Operators:
The different special operators in SQL are as follows −
ALL operator
ANY Operator
BETWEEN Operator
EXISTS Operator
IN Operator
LIKE Operator
Example:
IN():
SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
LIKE operator:
Select * from Employee
Where Emp_Name LIKE “A%”
BETWEEN operator:
Select * from Employee
Where Emp_Salary BETWEEN 20000 AND 60000;
Advanced Data Definition Commands
Changing a Column's Data Type:
To change the data type of a column in a table, you can use the ALTER
TABLE command with the MODIFY or CHANGE keyword. The basic
syntax for modifying a column's data type is:
Syntax:
ALTER TABLE table_name
MODIFY column_name new_data_type;
For example, if you want to change the data type of the price column
in the products table from INT to DECIMAL, you can use the following
statement:
ALTER TABLE products
MODIFY price DECIMAL(10,2);
Changing a Column’s Data Characteristic:
Use ALTER to change data characteristics
If column to be changed already contains data, changes in column
characteristics are permitted if those changes do not alter the d type
For example if you want to increase the width of the P Price column to
nine digits use the following command.
Example:
ALTER TABLE Product
Modify(P_PriceDecimal(9,2));

Dropping a column:
We use the following SQL statement:
ALTER TABLE Persons
DROP COLUMN DateOfBirth;
Advanced Data Update:
To make changes in the columns of existing rows, Use the Up command. Update
command changes the rows that already exist.
For example: to enter the P Salecode value '2' in the fourth row, u use Update
command together with primary key P Code '1546-QQ7. In the value by using the
following command sequence
Update Product
Set P Salecode='2' Where P Code 1546-QQZ';
Subsequent data can be entered the same way, defining each entry by primary key
(P Code) and its column location (P Salecode). For example: if you want to enter
the P Salecode value '1' for the P Co values '2232/QWE' and '2232/QTY' you can
use
Update Product
Set P Salecode='1' Where P Code IN (2232/QWI, 2232/QIY');
The arithmetic operators are particularly useful in data updates. For example the
quantity on hand has dropped below the minimum desirable value, you will order
more of the product. Suppose, for example you have ordered 20 units of product
'2232/QWI. When they arrive, you want to add them to the inventory using the
following command
Update Product
Set P QOIP QO11 +20 Where P Code='2232/QWE';
Copying Parts of Table:
SQL permits copying contents of selected table columns so that the
data need not be reentered manually into newly created table(s)
Copying data from an existing table to a new one is very useful in some
cases such as backing up data and replicating production data for
testing.
In order to copy data from a table to a new table, you can use the
following statement:
1 CREATETABLinew table
2 SELECT FROMexisting, table;
First, MySQL creates a new table with name as indicated after CREATE
TABLE statement. Then it will select data from the existing table and fill
the new table with all the selected data.
To copy a part of data from an existing table, you use WHERE clause
in the SQL SELECT statement as follows:
1 CREATETABLEnew table
2 SELECT FROMexisting table
3 WHERE conditions;

It is very important to check whether the table you want to create exists or not
before you creating it. In order to do so you should use IF NOT EXIST after CREATE
TABLE statement.
The full SQL. command of copying data from an existing table to the new one is as
follows:
1 CREATETABLEIF NOTEXISIS new table
2 SELECT FROMexisting table
3 WHERE conditions;
Here is the example of using copying data command. We have office
table. Now we copy data from this table into a new one by using the
following statement:
1 CREATETABLE IF NOTEXISTS offices bk;
2 SELECT FROMoffices;
If you need only copy all offices in US, we can use WHERE condition for
it as follows:
1 CREATHTABLEIF NOTEXISTS offices usa
2 SELECT* FROMoffices
3 WHEREcountry = 'USA';
Adding Primary and Foreign Key Designations:
Example:
ALTER TABLE customers
ADD PRIMARY KEY (customer_id);
For Foreign key:
ALTER TABLE orders
ADD FOREIGN KEY (customer_id) REFERENCES customers(customer_id);
Even composite primary keys and multiple foreign keycan be designated in a single SQL
statement.
CREATE TABLE orders (
order_ida INT PRIMARY KEY,
customer_id INT,
product_name VARCHAR(255),
quantity INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

You might also like