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

unit-2 DBMS

Uploaded by

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

unit-2 DBMS

Uploaded by

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

UNIT II

CHAPER-1: RELATIONAL MODEL:


1. Introduction to relational model
2. concepts of domain, attribute, tuple, relation
3. importance of null values
4. constraints (Domain, Key constraints, integrity constraints) and their importance
CHAPER-2: BASIC SQL:
1. Simple Database schema
2. data types, table definitions (create, alter)
3. different DML operations (insert, delete, update)
4. basic SQL querying (select and project) using where clause
5. arithmetic & logical operations
6. SQL functions(Date and Time, Numeric, String conversion)
OBJECTIVES: After studying this unit, you will be able to:
 Describe Relational model
 Describe SQL and data types
 Explain the basic structures of SQL queries
 Know how to create tables
 Realise aggregate functions and null values

CHAPER-1:RELATIONAL MODEL:
1. Introduction to relational model
2. concepts of domain, attribute, tuple, relation
3. importance of null values
4. constraints (Domain, Key constraints, integrity constraints) and their importance

1. INTRODUCTION TO RELATIONAL MODEL:


1. The Relational model for data base systems was introduced by Dr.E.F.Codd in 1970 and
proposed 0-12 well defined principles of Relational model .
2. Dr E.F.Codd, also known to the world as the ‘Father of Database Management Systems’.
The Relational model represents Data in the form of TWO dimensional tables.
3. Each table represents some real world entity or thing.
4. The organization of data in Relational tables is known as the Logical view of the database.
Most of the database software such as ORACLE,MICROSOFT SQL SERVER,SYBASE
based on Relational model .
5. The relational model is the conceptual basis of Relational databases. It is a method of
structuring data using relations and most commonly used model.
6. In this, data is organized as two dimensional tables.
7. Each table is called relation.
8. The relational model uses a collection of tables to represent both data and the relationships
among those data. Each table has multiple columns, and each column has a unique name.

1
9. The Relational model is implemented in database where a Relation is represented by a
Table, a Tuple is represented by a Row, and an Attribute is represented by a column of
the table.
Example of Relation: (For Customer)

In RDBMS :-
 A Database is a collection of Tables.
 Each table contains Records, which are called Tuples.
 Each record contains Field values
 A Domain is refers to the possible values that comes in a particular column.
 Each table has a unique identifier called Primary key, which is used to access record in a table.
 Tables are related using Foreign keys.

Properties of Relations

o Name of the relation is distinct from all other relations.


o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
o tuple has no duplicate value
o Order of tuple can have a different sequence

2.CONCEPTS OF DOMAIN, ATTRIBUTE, TUPLE, RELATION


A Relational database stores data in the form of relations (tables).

2
The main highlights of this model are:
 Data is stored in tables called relations.
 Relations can be normalized.
 In normalized relations, values saved are atomic values.
 Each row in a relation contains a unique value.
 Each column in a relation contains values from a same domain.
2.CONCEPTS OF DOMAIN, ATTRIBUTE, TUPLE, RELATION
2.1 CONCEPTS OF DOMAIN:
A Domain is a set of atomic and valid values.
A data type or format is also specified for each domain.
Example:
Domain of percentage: is a set of values in between 0 to 100.
Phone_Numbers: A set of 10-digit phone number is valid data.
Valid Age: 0 to 100 years.
2.2.CONCEPTS OF ATTRIBUTE:
Each column in a Table. Attributes are the properties which define a relation.
e.g., Student Relation : Rollno, NAME,etc.

Degree: The number of attributes in the relation is known as degree.


Ex: The degree of the given STUDENT table is 4.
2.3.CONCEPTS OF TUPLE
Each row in a relation is known as tuple.

Cardinality: The number of tuples are present in the relation is called as its cardinality.
Ex: The Cardinality of the STUDENT table is 4.
3
2.4.CONCEPTS OF RELATION
A relation is defined as a set of tuples and attributes.
 A relation consists of Relation schema and relation instance.
 Relation schema: A relation schema represents the name of the relation with its
attributes.
 Ex: STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is Relation schema
for STUDENT.
 Relation instance: The set of tuples of a relation at a particular instance of a time is called
Relation Instance. Relation instances do not have duplicate tuples.
An instance of ‘Employee’ relation

3.IMPORTANCE OF NULL VALUES


1. The SQL NULL is the term used to represent a missing value. A NULL value in a table is
a value in a field that appears to be blank.
2. Relational databases use a placeholder called NULL to represent unknowns.
3. NULL means that some value , which is Unknown, Missing, or Irrelevant.
4. NULL means that some value , which is Unknown, Missing, or Irrelevant.
5. If a field in a Relation is optional, it is possible to insert a new record or update a value
without adding a value to this field. Then, the field will be saved with a NULL value.
6. NULL value means that no entry has been made into the column.
7. It states that the corresponding value is either unknown or undefined.
8. It is different from zero or " ".
9. They should be avoided to avoid the complexity in SELECT & UPDATE queries and also
because columns which have constraints like Primary or Foreign key constraints cannot
contain a NULL value.
Principles/uses of Null values:
1. Setting a null value is appropriate when the actual value is unknown or When a value would
not be meaningful.
2. A null value is not equivalent to a value of Zero.
3. A null value will evaluate to null in any expression. Ex: null multiplied by 10 is null.
4. When a column name is defined as not null, then that column becomes a mandatory column.It
implies that the user is forced to enter data into that column.
How to Test for NULL Values? :
Remember, comparisons against null always result in null, so queries can't use regular
comparison operators like "=" or "!=". Instead they must use the IS NULL or IS NOT NULL
operators.
4
USING ‘IS NULL’ This will gives the output based on the null values in the specified column.

USING ‘IS NOT NULL ‘ This will gives the output based on the not null values in the specified
column.

4.constraints (Domain, Key constraints, integrity constraints) and their importance


constraints:
On modeling the design of the relational data base, we can put some
rules(conditions) like what values are allowed to be inserted in the relation
➢ Constraints are the rules enforced on the data columns of a table. These are used
to limit the type of data that can go in to a table
➢ This Ensure the accuracy and reliability of the data in the database. Constraints
could be either on a column level on a table level.
The following are the different Constraints used on the Relational model
1. Domain Constraints
2. Key constraints
3. Integrity constraints
1.Domain Constraints :
1. Domain constraints can be defined as the definition of a valid set of values for an attribute.
2. The data type of domain includes string, character, integer, time, date, currency, etc.
3. The value of the attribute must be available in the corresponding domain.
4. In DBMS table is viewed as a combination of rows and columns
5. For example, if you are having a column called month and you want only (jan, feb,
march……) as values allowed to be entered for that particular column which is referred to
as domain for that particular column
5
Definition: Domain constraint ensures two things it makes sure that the data value entered for
that particular column matches with the data type defined by that column.
It shows that the constraints (NOT NULL/UNIQUE/PRIMARY KEY/FOREIGN
KEY/CHECK/DEFAULT)

Domain constraint= data type check for the column +constraints.

2.Key constraints in DBMS:


Constraints are nothing but the rules that are to be followed while entering data into columns of
the database table.
Constraints ensure that the data entered by the user into columns must be within the criteria
specified by the condition. 6 types of key constraints in DBMS
1. Not Null
2. Unique
3. Default
4. Check
5. Primary key
6. Foreign key
7.Super key
8.Alternate key
9.Candidate Key
10.Compound key
11.Surrogate Keys
2.1. Not Null:
• Null represents a record where data may be missing data or data for that record may be
optional.
• Once not null is applied to a particular column, you cannot enter null values to that column.
• A not null constraint cannot be applied at table level.

6
1. In the above example we have applied not null on three columns id, name and age which
means whenever a record is entered using insert statement all three columns should contain a
value other than null.
2. Two other columns address and salary, where not null is not applied which means that you
can leave the row as empty.
2.2.Unique:
 Some times we need to maintain only.
 Unique data in the column of a database table, this is possible by using a Unique
constraint. Unique constraint ensures that all values in a column are Unique.

7
2.3.Default:
 Default in SQL is used to add default data to the columns.
 When a column is specified as default with same value then all the rows will use the same
value i.e., each and every time while entering the data we need not enter that value.
 But default column value can be customised i.e., it can be over ridden when inserting a
data for that row based on the requirement.

 As a result, whenever you insert a new row each time you need not enter a value for this
default column that is entering a column value for a default column is optional.
2.4.Check:
1. Check constraint ensures that the data entered by the user for that column is within the
range of values or possible values specified.
2. All the rows in that column must satisfy this rule.
3. Limits the data values of variables to a specific set, range, or list of values.
4. The constraint can be applied for a single column or a group of columns.

8
As we have used a check constraint as (age>=18) which means value entered by user for this age
column while inserting the data must be less than or equal to 18.
2.5.Primary Key:
A primary key is a constraint in a table which uniquely identifies each row record in a database
table by enabling one or more column in the table as primary key.

Creating a primary key:


A particular column is made as a primary key column by using the primary key keyword
followed by the column name.

 Here we have used the primary key on ID column then ID column must contain unique
values i.e., one ID cannot be used for another student.
 Primary key = Unique key + Not null
2.6. Foreign Key:
1. The foreign key constraint is a column or list of columns which points to the primary key
column of another table.
2. The main purpose of the foreign key is only those values are allowed in the present table
that will match to the primary key column of another table.
3. A referential integrity constraint (foreign key) is specified between two tables.
4. In the referential integrity constraints, if a foreign key column in table 1 refers to the
primary key column of table 2, then every value of the foreign key column in table 1 must
be null or be available in primary key column of table 2.

9
2.7.Super key

2.8.Alternate key

10
2.9.Candidate Key

2.10.Compound key:

11
2.11.SURROGATE KEYS

3. Integrity Constraints in DBMS:


There are two types of integrity constraints
1. Entity Integrity Constraints 2. Referential Integrity Constraints
3.1. Entity Integrity Constraints :
1. These constraints are used to ensure the uniqueness of each record or row in the data table.
2. Entity Integrity constraints says that no primary key can take NULL VALUE, since using
primary key we identify each tuple uniquely in a relation.
3. The entity integrity constraint states that primary key value can't be null.
4. This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
5. A table can contain a null value other than the primary key field.

12
3.2.Referential Integrity Constraints
1. A referential integrity constraint is specified between two tables.
2. The referential integrity constraint is specified between two relations or tables and used to
maintain the consistency among the tuples in two relations.
3. This constraint is enforced through foreign key, when an attribute in the foreign key of
relation R1 have the same domain as primary key of relation R2, then the foreign key of
R1 is said to reference or refer to the primary key of relation R2.
4. The values of the foreign key in a tuple of relation R1 can either take the values of the
primary key for some tuple in Relation R2, or can take NULL values, but can‟t be empty.

13
CHAPER-2: BASIC SQL:
1. Simple Database schema
2. Data Types, Table Definitions (create, alter)
3. Different DML Operations (insert, delete, update)
4. Basic SQL querying (select and project) using where clause
5. Arithmetic & logical operations
6. SQL functions(Date and Time, Numeric, String conversion)

BASIC SQL:
SQL stands for Structure Query Language it is used for storing and managing data in relational
database management system.
It is standard language for relational database system. It enables a user to create, read, update and
delete relational databases and tables.
All the RDBMS like MYSQL, Oracle, MA access and SQL Server use SQL as their standard
database language.
SQL allows users to Query the database in a number of ways using statements like common
English.
Rules: SQL follows following rules
 SQL is not a case sensitive. Generally, keywords are represented in UPPERCASE.
 Using the SQL statements, you can perform most of the actions in a database.
 Statements of SQL are dependent on text lines. We can use a single SQL statement on one or
multiple text line.
SQL Process:
When an SQL command is executing for any RDBMS, then the system figure out the best way to
carry out the request and the sql engine determines that how to interrupt the task.
In the process, various components are included. These components can be optimization engine,
query engine, query dispatcher etc.,
All the non-sql queries are handled by the classic query engine, but sql query engine won‟t
handle logical files.
Characteristics of SQL:
 SQL is easy to learn.
 SQL is used to access data from relational database management system.
 SQL is used to describe the data.
 SQL is used to create and drop the database and table.
 SQL allows users to set permissions on tables, procedures and views.
1. Simple Database schema
1.A database schema is a structure that represents the logical storage of the data in the database.
2. It represents the organization of data and provides information about the relationships
between the tables in a given database.
3. A database schema is the logical representation of a database, which shows how the data is
stored logically in the entire database.
4. It contains list of attributes and instruction that informs the database engine that how the data
is organized and how the elements are related to each other.
14
5. A database schema contains schema objects that may include tables, fields, packages, views,
relationship, primary key, foreign key.
6. In actual, the data is physically stored in files that may be in unstructured form, but to retrieve
it and use it, we need to keep them in a structured manner.
7. To do this a database schema is used. It provides knowledge about how the data is organized
in a database and how it is associated with other data.
8. A database schema object includes the following:
• Consistent formatting for all data entries.
• Database objects and unique keys for all data entries.
• Tables with multiple columns, and each column contains its names and datatypes.
• The given diagram is an example of a database schema it contains three tables, their
data types. This also represents the relationships between the tables and primary keys as
well as foreign keys.

2.DATA TYPES:
SQL data type is used to define the values that a column can contain
Every column is required to have a name and data type in the database table.

15
1.BINARY DATATYPES: There are three types of binary data types which are given below

16
There are five types of SQL statements.
They are:
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Retrieval Language (DRL) Or Data Query Language (DQL)
4. Transactional Control Language (TCL)
5. Data Control Language (DCL)

3.Data Definition Language (DDL):


The Data Definition Language (DDL) is used to create and destroy databases and database
objects.
These commands will primarily be used by database administrators during the setup and removal
phases of a database project.

1. CREATE: SQL create table is used to create a table in the database. To define the table, you
should define the name of the table and also define its column and column‟s data type.
Syntax for creating tables:
Create table tablename(
Column _name datatype(width),
Column _name datatype(width),
Column_ name datatype(width)
);

Example for table creation on student:

SQL>create table student(


Stuid int,
Stuname varchar2(10),Stusection varchar2(5),Dob varchar2(10), Gender varchar2(5)
);

17
Output:

SQL>desc student;

Example:
Select * from student;

2.DROP

3.ALTER

Case1: adding
case2: modify
Case3:drop
18
The alter table command adds, delete or modifies columns in a table
• The alter table command also adds and deletes various constraints in a table
Case1: adding
Syntax for adding a column:
SQL>alter table tablename add(columnname datatype(width));
Example:
SQL>alter table student add phone int;

case2:modify
syntax for modifyind data:
SQL>alter table tablename modify (old columnname datatype(new size));
Example:
SQL>alter table student modify(gender varchar2(10));

Case3:drop
When we want to delete a certain column of a table we need to use drop command.
Syntax:
Alter table tablename drop column columnname;
Example:
Alter table student drop column dob;
19
20
Difference between Truncate & Delete:-
 By using truncate command data will be removed permanently & will not get back whereas by
using delete command data will be removed temporally & get back by using roll back command.
 By using delete command data will be removed based on the condition where as by using
truncate command there is no condition.
 Truncate is a DDL command & delete is a DML command.

4.Different DML operations (insert, delete, update)


DATA MANIPULATION LANGUAGE (DML):
The Data Manipulation Language (DML) is used to retrieve, insert and modify database
information.
These commands will be used by all database users during the routine operation of the database.
The basic DML commands:
1. SELECT
2. INSERT
3. UPDATE
4. DELETE
1. SELECT: SELECT command or statement in SQL is used to fetch data records from the
database table and present it in the form of a result set.

column_name1, column_name2, … : Specify the column_names which have to be fetched or


selected for the final result set.
table_name: Specify the name of the database table from which these results have to be fetched.
condition_expression: Specify the condition expression for filtering records for the final result
set.

21
A Simple Query,

The SQL WHERE clause is used to specify a condition while fetching the data from a single
table or by joining with multiple tables.
If the given condition is satisfied, then only it returns a specific value from the table. You should
use the WHERE clause to filter the records and fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also used in the
UPDATE, DELETE statement, etc.,
condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc.
The basic syntax of the SELECT statement with the WHERE clause is as shown below.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
Example
Consider the CUSTOMERS table having the following records −

The following code is an example which would fetch the ID, Name and Salary fields from the
CUSTOMERS table, where the salary is greater than 2000 −

This would produce the following result −

The following query is an example, which would fetch the ID, Name and Salary fields from the
CUSTOMERS table for a customer with the name Hardik.
22
Here, it is important to note that all the strings should be given inside single quotes (''). Whereas,
numeric values should be given without any quote as in the above example.

The SQL AND & OR operators are used to combine multiple conditions to narrow data in an
SQL statement. These two operators are called as the conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the
same SQL statement.

The AND Operator: The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.

Syntax
The basic syntax of the AND operator with a WHERE clause is as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using the AND operator. For an action to be taken by
the SQL statement, whether it be a transaction or a query, all conditions separated by the AND
must be TRUE.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch the ID, Name and Salary fields from the
CUSTOMERS table, where the salary is greater than 2000 and the age is less than 25 years −
SQL> SELECT ID, NAME, SALARY

23
FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;

This would produce the following result −


+----+-------+----------+
| ID | NAME | SALARY |
+----+-------+----------+
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+-------+----------+

The OR Operator: The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.

Syntax
The basic syntax of the OR operator with a WHERE clause is as follows −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using the OR operator. For an action to be taken by
the SQL statement, whether it be a transaction or query, the only any ONE of the conditions
separated by the OR must be TRUE.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

The following code block hasa query, which would fetch the ID, Name and Salary fields from
the CUSTOMERS table, where the salary is greater than 2000 OR the age is less than 25 years.
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;

This would produce the following result −


+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
24
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

2.INSERT
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns in the table into
which you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding values for
all the columns of the table. But make sure the order of the values is in the same order as the
columns in the table.
The SQL INSERT INTO syntax will be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

You can create a record in the CUSTOMERS table by using the second syntax as shown below.

INSERT INTO CUSTOMERS


VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in the CUSTOMERS table as
shown below.
25
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

3.UPDATE
The SQL UPDATE Query is used to modify the existing records in a table. You can use the
WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows
would be affected.

Syntax

The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using the AND or the OR operators.

Example

Consider the CUSTOMERS table having the following records −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
Now, the CUSTOMERS table would have the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
26
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS
table, you do not need to use the WHERE clause as the UPDATE query would be enough as
shown in the following code block.
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
Now, CUSTOMERS table would have the following records −
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+

27
4.DELETE

The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all
the records would be deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following code has a query, which will DELETE a customer, whose ID is 6.
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
Now, the CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

28
COMMIT;

29
30
31
4.BASIC SQL Querying (select and project) using where clause

32
The following are the various SQL clauses:

1. Group by:
1. SQL group by statement is used to arrange identical data into groups.
2. The group by statement is used with the SQL select statement.
3. The group by statement follows the WHERE clause in a SELECT statement and precedes
the ORDER BY clause.
4. The SQL GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.
5. The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN,SUM, AVG) to group the result-set by one or more columns.
Syntax:
Select column
from table_name
where column group by column, order by column;
33
Example: Select company count (*) from product group by company;

2. Having clause: Having clause is used to specify a search condition for a group or an
aggregate. Having clause is used in a group by clause, if you are not using group by clause then
you can use having function like a where clause.

3. Order by clause: The order by clause sorts the result _set in ascending or descending order

34
5.Arithmetic & Logical Operations
SQL operators:

 SQL statements generally contain some reserved words or characters that


are used to perform operations such as arithmetic and logical operations
etc. Their reserved words are known as operators.
SQL arithmetic operator:

 We can use various arithmetic operators on the data stored in tables.


 Arithmetic operators are:
+ Addition
- Subtraction
/ Division
* Multiplication
% modulus
1. Addition (+): It is used to perform addition operation on data items.
Sample table:
EMP_ID EMP_NAME SALARY

1 Alex 25000
2 John 55000
3 Daniel 52000
4 Sam 12312
 select emp id, emp_name, salary, salary+100 as “salary +100” from
addition;
Output:
EMP_ID EMP_NAME SALARY SALARY+100
1 Alex 25000 25100
2 John 55000 55100
3 Daniel 52000 52100
4 Sam 12312 12412
 Here we have done addition of 100 to each emp‟s salary.

35
2. Subtraction (-): It is used to perform subtraction on the data items.
Example:
Select emp_id, emp_name, salary, salary-100 as “salary-100” from
subtraction;
EMP_ID EMP_NAME SALARY SALARY-100
1 Alex 25000 24900
2 John 55000 54900
3 Daniel 52000 51900
4 Sam 90000 89900
Here we have done subtraction of 100 for each emp‟s salary.

3. Division (/):
 The division function is used to integer division (x is divided by y).an
integer value is returned.
Example:
 Select emp_id, emp_name, salary, salary/100 as
“salary/100” from division;
EMP_ID EMP_NAME SALARY Salary/100
1 Alex 25000 250
2 John 55000 550
3 Daniel 52000 520
4 Sam 90000 900
4.Multiplication (*):
 It is used to perform multiplication of data items.
 Select emp_id, emp_name, salary, salary*100 as “salary*100” frommultiplication;
EMP_ID EMP_NAME SALARY SALARY*100
1 Alex 25000 2,500,000
2 John 55000 5,500,000
3 Daniel 52000 5,200,000
4 Sam 90000 9,000,000
 Here we have done multiplication of 100 to each emp‟s salary.
5.Modulus (%):
 It is used to get remainder when one data is divided by another.
 Select emp_id, emp_name, salary, salary%25000 as “salary%25000” from
modulus;
Output:
EMP_ID EMP_NAME SALARY SALARY%25000
1 Alex 25000 0
2 John 55000 5000
3 Daniel 52000 2000
4 Sam 90000 15000
 Here we have done modulus operation to each emp‟s salary.

36
2.1.Logical operations:
 Logical operations allow you to test for the truth of a condition.
 The following table illustrates the SQL logical operator.
OPERATOR MEANING
ALL Returns true if all comparisons are true
AND Returns true if both expressions are true
ANY Returns true if any one of the comparisons is
true
BETWEEN Return true if the operand is within a range
IN Return true if the operand is equal to one of
the values in a list
EXISTS Return true if the sub query contains any rows
1. AND: The AND operator allows you to construct multiple condition in the WHERE
clause of an SQL statement such as select.
 The following example finds all employees where salaries are greater than the
5000 and less than 7000.
 Select first_name, last_name, salary from
employees where salary>5000 AND salary<7000
order by salary;
Output:
FIRST_NAME LAST_NAME SALARY
John Wesley 6000
Eden Daniel 6000
Luis Popp 6900
Shanta Suji 6500
2.ALL:
The ALL operator compares a value to all values in another value set.
 The following example finds all employees whose salaries are
greater than all salaries of employees.
EX:
select first_name, last_name, salary from employees where
salary>=ALL (select salary from employees where department_id =8)
order by salary DESC;

Output:
FIRST_NAME LAST_NAME SALARY
Steven King 24000
John Russel 17000
Neena Kochhar 14000
3.ANY:
The ANY operator compares a value to any value in a set ascending to condition.
The following example statement finds all employees whose salaries are
greater than the average salary of every department.
EX: select first_ name, last_ name, salary from employees where salary >ANY(select avg (salary)
from employees‟ group by department_ id) order byfirst_ name, last_ name;
37
Output:
FIRST_NAME LAST_NAME SALARY
Alexander Hunold 9000.00
Charles Johnson 6200.00
David Austin 4800.00
Eden Flip 9000.00

4.Between:
 The between operator searches for values that are within a set of values.
 For example, the following statement finds all employees where
salaries are between 9000 and 12000.
EX:

select first_ name, last_ name, salary from employees where salarybetween
9000 AND 12000 order by salary;
Output:
FIRST_NAME LAST_NAME SALARY
Alexander Hunold 9000.00
Den Richards 10000.00
Nancy Prince 12000.00
5.IN:
 The IN operator compares a value to list of specified values. The IN
operator return true if compared value matches at least one value in
the list.
The following statement finds all employees who work in department _id 8 or 9.
EX:

select first_ name, last_ name, department_ id from employees


wheredepartment_ id IN (8,9) order by department_ id;

Output:

FIRST_NAME LAST_NAME DEPARTMENT_I


D
John Russel 8
Jack Livingstone 8
Steven King 9
Neena Kochhar 9
6.Exists:
 The EXISTS operator tests if a sub query contains any rows.
 For example, the following statement finds all employees who have dependents.
 select first_ name, last_ name from employees
where EXISTS (select 1 from dependent d where d.
employee_ id=e.employee _id);

38
FIRST_NAME LAST_NAME
Steven King
Neena Kochhar
Alexander Hunold

6.SQL functions(Date and Time, Numeric, String conversion)

DATE & TIME FUNCTIONS:

1.Sysdate: It generates the system date.

Ex: Select sysdate from dual;


39
Output:

select extract(day from sysdate) as only day from dual;

2. ADD_MONTHS: This function returns a date after adding data with specified no of
months.
EX: Select ADD_MONTHS („2017-02-29‟,1) from dual;
Output: 31-MAR-17.

3.Select add_ months(sysdate,3) from dual;


Output: 05-MAR-22.

4.CURRENT_DATE: This function displays the current date.


Ex: Select CURRENT_DATE from dual;
Output: 05-DEC-2021.

5.NEXT_DAY: This function represents both day and date and returns the day of the next
given day.
EX: Select NEXT_ DAY(SYSDATE,‟MONDAY‟) from dual;
Output: 07-DEC-21.

6. LAST_DAY: This function returns a day corresponding last day of months.


EX: Select LAST_DAY (sysdate) from dual;
40
Output: 31-DEC-21.

7.MONTHS_BETWEEN: It is used to find no of months between two given dates.


EX: Select MONTHS_BETWEEN(‟16-APRIL-2021‟,‟16-AUGUST-2021) from dual;
Output: -4.

8.ROUND: It gives the nearest value or round off value for the argument pass. (or) It returns
a date rounded to a specific unit of measure.
EX: Select ROUND(‟26-NOV-21‟,‟YYYY‟) from dual;
Output: 01-JAN-22.

9.TRUNC: This function returns the date with the time(co-efficient) portion of the date
truncated to the unit specified.
EX: Select TRUNC (sysdate, ‟MM‟) from dual;
Output: 01-DEC-21.

10.TO_DATE: This function converts date which is in the character string to a date value.
EX: Select TO_DATE (‟01 jan 2017‟,‟DD MM YYYY‟) from dual;
Output: 01-JAN-17.

11.TO_CHAR: This function converts DATE or an INTERVAL value to a character string


in a specified format.
EX: Select TO_CHAR (sysdate,‟DD MM YYYY‟) from dual;
Output: 05 12 2021.

12.LEAST: This function displays the oldest date present in the argument list.
EX: Select LEAST(‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟) from dual;
Output: 01-MAR-21.

13.GREATEST: This function displays the latest date present in the argument list.

EX: Select GREATEST (‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟) from dual;


Output: 28-DEC-21.

41
2.1 SQL NUMERIC FUNCTIONS:

Following are some of the Numeric functions

1.ABS (): It returns the absolute value of a number. EX: select ABS (-243.5) from dual;
OUTPUT: 243.5

2.ACOS (): It returns the cosine of a number. EX: select ACOS (0.25) from dual;
OUTPUT: 1.318116071652818

3.ASIN (): It returns the arc sine of a number. EX: select ASIN (0.25) from dual;
OUTPUT: 0.253680255142

4.CEIL (): It returns the smallest integer value that is a greater than or equal to a number.
EX: select CEIL (25.77) from dual;
OUTPUT: 26

5.FLOOR (): It returns the largest integer value that is a less than or equal to a number.
EX: select FLOOR (25.75) from dual;
OUTPUT: 25
42
6.TRUNCATE (): This does not work for SQL server. It returns the truncated to 2 places right
of the decimal point.
EX: select TRUNCATE (7.53635, 2) from dual;
OUTPUT: 7.53
7.MOD (): It returns the remainder when two numbers are divided.
EX: select MOD (55,2) from dual;
OUTPUT: 1.

8.ROUND (): This function rounds the given value to given number of digits of precision.
EX: select ROUND (14.5262,2) from dual;
OUTPUT: 14.53.

9.POWER (): This function gives the value of m raised to the power of n.
EX: select POWER (4,9) from dual;
OUTPUT: 262144.

10.SQRT (): This function gives the square root of the given value n.
EX: Select SQRT (576) from dual;
OUTPUT: 24.

11.LEAST (): This function returns least integer from given set of integers.
EX: select LEAST (1,9,2,4,6,8,22) from dual;
OUTPUT: 1.

12.GREATEST (): This function returns greatest integer from given set of integers.
EX: select GREATEST (1,9,2,4,6,8,22) from dual;
OUTPUT: 22

2.3.STRING CONVERSION FUNCTIONS OF SQL:

43
String Functions are used to perform an operation on input string and return the output
string. Following are the string functions
1.ASCII FUNCTION: It returns the ascii represetation of the first character in the given
string.
SYNTAX: ASCII(‘CHAR’/’STRING’)

EXAMPLE: select ascii(‘apple’) from dual;

Output:

2.CONCAT: Concatenates two or more strings together.

Query syntax:CONCAT(string1,string2)

44
3.LENGTH: Returns the length of the specified string

Query synatx: LENGTH(string)

4.REPLACE: Replaces a sequence of characters in a string with another set of character.

Query syntax: REPLACE(expression, pattern, replacement)

5.To_char: It returns a character having the ASCII equivalent to n.


Syntax: Chr(n)

Example: select chr(67) from dual;


Output:

6.LOWER: All the letters in 'string_value' is converted to lowercase.

Query syntax: LOWER(string_value)

7.UPPER: All the letters in ‘string_value’ is converted to upper case.


45
Query syntax: UPPER(string_value)

8.INITCAP: All the letters in 'string_value' is converted to mixed case.

Query syntax:INITCAP(string_value)

9.LPAD: Returns 'string_value' left-padded with 'pad_value' . length of the whole string will be of 'n' characters.

Query syntax: LPAD(string_value, n, pad_value)

10.RPAD: Returns ‘string_value’ right-padded with ‘pad_value’, length of the whole string will be of ‘n’
characters.

Query syntax: RPAD(string_value,n,pad_value)

11.TRIM:

1) L TRIM: function removes starting character from the given string.


Syntax: select trim(trimcharacter from string) from dual;
Example: select trim(‘H’ from ‘HELLO WORLD’) from dual;

2) RTRIM: This function removes ending character from the given string.
Syntax: select trim(trimcharacter from string) from
dual;Output:

46
47

You might also like