You are on page 1of 32

lOMoARcPSD|36793593

DBMS UNIT 2 notes

COMPUTER SCIENCE ENGINEERING (Jawaharlal Nehru Technological University,


Kakinada)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by SCS ascasc (powam69667@bitofee.com)
lOMoARcPSD|36793593

UNIT - 2
Relational Model: Introduction to relational model, concepts of domain, attribute, tuple,
relation, importance of null values, constraints (Domain, Key constraints, integrity
constraints) and their importance

BASIC SQL: Simple Database schema, data types, table definitions (create, alter), different
DML operations (insert, delete, update), basic SQL querying (select and project) using
where clause, arithmetic & logical operations, SQL functions(Date and Time, Numeric,
String conversion).

-----------------------------------------------------------------------------------------------------------------------------------2.1
Introduction to relational model
Relational Model (RM) represents the database as a collection of relations. A relation is
nothing but a table of values. Every row in the table represents a collection of related data
values. These rows in the table denote a real-world entity or relationship.

Relational Model was proposed by E.F. Codd to model data in the form of relations or
tables. After designing the conceptual model of Database using ER diagram, we need to
convert the conceptual model in the relational model which can be implemented using
any RDBMS languages like Oracle SQL, MySQL etc.
-------------------------------------------X----------------------------------------
2.2 concepts of domain, attribute, tuple, relation

Relational Model terminology:

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


 Concept of Relation : A Relation is defined as a set of Tuples that have the same
Attributes. A tuple usually represents an object and information about that object.
Objects are typically physical objects or logical concepts.
A Relation is usually described as a Table, which is organizedinto Rows and
Columns. All the data referenced by an attribute are in the same domain and
conformto the same constraints.
In Relational model of a database, all data is represented in terms of tuples ,
grouped into relations.Simply, A relation is a File , each file contains only one record
type. The records have no particularorder. Every field is Single-Valued. The records
have a unique indentifying field or composite fieldis called the Primary key.

 Consider a relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE and
AGE shown in below.
STUDENT
ROLL_NO NAME ADDRESS PHONE AGE
1 ram delhi 9455123451 18
2 ramesh gurgaon 9652431543 18
3 sujit rohtak 9156253131 20
4 suresh delhi 18

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

 Concept of DOMAIN:
o A domain describes the set of possible values for a given attribute, and can be
considered a constraint on the value of the attribute.
(or)
o A Domain is a set of atomic and valid values. Every attribute has some pre-defined
value scope, known as Attribute Domain. It is a named set of values, all of the same
type.
o Examples:
1. AGE attribute in the STUDENT relation.
Domain of AGE = { 18, 19, 20, 21, 22, 23, 24, 25}
Which means the student age must be in the range of 18 to 25.
2. Domain of PHONE ={all possible integer values of the length 10}
3. Domain of NAME = {character strings that represents person’s name }
 Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME
 Relation Schema: A relation schema is used to describea relation. A relation
schema represents name of the relation with its attributes.
Denoted by R(A1, A2, … , An), where R is a relation name, Ai is the name of the
attribute and domain of attribute denoted by dom(Ai).
e.g.; STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is relation schema for
STUDENT. If a schema has more than 1 relation, it is called Relational Schema.
 Tuple: Each row in the relation is known as tuple. The above relation contains 4
tuples, one of which is shown as:
1 ram delhi 9455123451 18

 Relation Instance: The set of tuples of a relation at a particular instance of time is


called as relation instance. STUDENT table shows the relation instance of STUDENT
at a particular time. It can change whenever there is insertion, deletion or updation in
the database.
 Degree or arity: The number of attributes in the relation is known as degree of the
relation. The STUDENT relation defined above has degree 5.
 Cardinality: The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.
 Column: Column represents the set of values for a particular attribute.
The column ROLL_NO is extracted from relation STUDENT.

ROLL_NO
1
2
3
4
 NULL Values: The value which is not known or unavailable is called NULL value. It is
represented by blank space.
e.g.; PHONE of STUDENT having ROLL_NO 4 is NULL.

------------------------------x------------------------------

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

2.3 Importance of null values

NULL values: NULL values are used to represent the values ofattributes that may be
unknown or may not apply to a tuple. A special value, calledNULL, is used in these cases.
For example, the Apartment_number attribute of an address applies only to address that
are in apartment buildings and not to other types of residences.
 It is important to understand that a NULL value is different from zero value.
 A NULL value is used to represent a missing value, but that it usually has one of
three different interpretations:
 Value unknown (value exists but is not known)
 Attribute not applicable (undefined for this tuple)

1. Value Unknown:
For example, some STUDENT tuples haveNULL for their phone because he does not
have a phone.(that isphone value is unknown).

ROLL_NO NAME ADDRESS PHONE AGE


4 suresh delhi 18

For example, some STUDENT tuples have NULL for their height because the height
value is there but, presently it is not available with us.

ROLL_NO NAME ADDRESS PHONE AGE HEIGHT


4 suresh delhi 9876543210 18

2. Attribute does not apply


For example, consider CUSTOMER Relation. The CUSTOMER tuples have NULL for their
Qualification because the customer don’t have any educational qualification (i.e the
Qualification does not apply to these customers)

Customer_ID Name Qualification Phone Age


10101 Ramana 9669696969 20

--------------------------------------x---------------------------------------

2.4 Constraints (Domain, Key constraints, integrity constraints) and their importance

Constraints in DBMS:
• Constraints are the rules enforced on the data columns of a table.
• These are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
• Restrictions on actual values of the database state.
Example:
1. Every student must have a name.
2. Minimum age to take into the college admission is 18.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

3. Age group between 18-45 must be vaccinated.


Types of constraints:
1. Domain constraints
2. Key constraints
3. Integrity constraints

1. Domain Constraints:

 A domain integrity constraint is a set of rules that restricts values a column or


relation can hold in the database table.

 It specifies that the value taken by the attribute must be the atomic value from its
domain.
 Domain constraint ensures two things

o The data value entered for that particular column matches with the data type
defined for that column

o the constraints(such as NOT NULL , UNIQUE, PRIMARY KEY, FOREIGN KEY,


CHECK , DEFAULT) impose on that column fulfilled or not

o Domain Constraint = data type check for the column + Constraints (NOT
NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY / CHECK / DEFAULT)

Example: We can specify if a particular column can hold null values or not, if the values
have to be unique or not, the data type or size of values that can be entered in the column,
the default values for the column, etc.

Example-
Consider the following Student table-

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Implementing domain constraint:

• We want to create a table “student” with “age” field having a value greater than 18,
can create a table like this:

• Creating a studenttable:

create table student (


rollno intPRIMARY KEY,
name varchar(30),
age intcheck(age>=18)
);
2. Key Constraints
 These are called uniqueness constraints since it ensures that every tuple in the
relation should be unique.
 This means that no two tuples can have the same combination of values for all
their attributes.
 A relation can have multiple keys or candidate keys(minimal superkey), out of
which we choose one of the keys as primary key, we don’t have any restriction on
choosing the primary key out of candidate keys, but it is suggested to go with the
candidate key with less number of attributes.
 Null values are not allowed in the primary key, hence Not Null constraint is also a
part of key constraint.
Types of key constraints:
a) Superkey
b) Candidate key
c) Primary key
Example:
Consider Employee table. Attributes: Emp_SSN, Emp_Id, Emp_name, Emp_email

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

a) Superkey

• A superkey is a set of attributes within a table whose values can be used to


uniquely identify a tuple.

• super denotes the superiority of a key- the super key is the super set of all those
attributes that can uniquely identify a table.

• A Super key may have additional attributes that are not needed for unique
identification.

• Sets of super key are able to uniquely identify a row of the employee table.

• If we set Super key on Emp_SSN, it will be able to identify all other tuples of the
table very easily.
• Similarly, if we set the Super key on (Emp_Id, Emp_name}, we can easily get the
value or details of the other remaining attributes of the employee. So, in this way,
we can create and search out the super keys from a table.

b) Candidate key
• A candidate key is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes.
• Candidate key is a minimal super key with no redundant attributes.
• It is a part of the super key.
• The Primary key should be selected from the candidate keys.
• Every table must have at least a single candidate key. A table can have multiple
candidate keys but only a single primary key.
Properties of Candidate key:

• It must contain unique values

• Candidate key may have multiple attributes

• Must not contain null values

• It should contain minimum fields to ensure uniqueness

• Uniquely identify each record in a table

Example:
• Now, from the above mentioned sets of super keys, we can conclude the candidate
keys.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

• In order to pick up the candidate keys, the best way is to analyze and form the
primary keys as much as we can.

• So, we need to identify those sets from the super key sets that alone can
identify the whole table, or we can say the other attributes of the table. Thus,
the result is:

• So, these are the three attributes obtained that can identify the other non-prime
attributes of the table. All these are the candidate keys and from which we can pick
the most appropriate attribute that can easily identify all records of the table, which
will be described as the Primary key.

c) Primary key
• A Primary Key is the minimal set of attributes of a table that is used to uniquely
identify the rows, or the tuples of the given particular table.
• Thus, a row that needs to be uniquely identified, the key constraint is set as the
Primary key to that particular field.
• A primary key can never have a NULL value because the use of the primary key is
to identify a value uniquely, but if no value will be there, how could it sustain.
Thus, the field set with the primary key constraint cannot be NULL.
• Also, it all depends on the user that the user can add or delete the key if applied.

Note:
One table can have only one primary key where it does not matter the table having one or
more columns in it.
Rules for defining Primary key:
• Two rows can't have the same primary key value
• It must for every row to have a primary key value.
• The primary key field cannot be null.
• The value in a primary key column can never be modified or updated if any foreign
key refers to that primary key.
Example:
Primary key : Emp_Id

3. Intregrity constraints
• Integrity constraints are a set of rules. It is used to maintain the quality of
information.
• Integrity constraints ensure that the data insertion, updating, and other processes
have to be performed in such a way that data integrity is not affected.
• Thus, integrity constraint is used to guard against accidental damage to the
database.
Types of Integrity constraints:
a) Entity integrity constraints

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

b) Referential integrity constraints

a)Entity integrity constraint


• The entity integrity constraint states that no primary key value can be NULL.
• This is because the primary key value is used to identify individual tuples in a
relation.
• Having NULL values for the primary key implies that we cannot identify some tuples.
• For example, if two or more tuples had NULL for their primary keys, we may not be
able to distinguish them if we try to reference them from other relations

Explanation:
In the above relation, EID is made primary key, and the primary key can’t take NULL
values but in the third tuple, the primary key is null, so it is a violating Entity Integrity
constraints.
b) Referential integrity constraints
• The Referential integrity constraints is specified between two relations or tables
and used to maintain the consistency among the tuples in two relations.
• This constraint is enforced through foreign key, when an attribute in the foreign
key of relation R1 have the same domain(s) as the primary key of relation R2, then
the foreign key of R1 is said to reference or refer to the primary key of relation R2.
• 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.
Example:

Explanation:
In the above, DNO of the first relation is the foreign key, and DNO in the second relation
is the primary key. DNO = 22 in the foreign key of the first table is not allowed since DNO
= 22
is not defined in the primary key of the second relation. Therefore, Referential integrity
constraints are violated here.

Importance of database Constraints


 A constraint can be defined as the property assigned to a column or the set of
columns in the database table which prevents inconsistent data values to be stored
into the certain columns.
 Constraints are used to ensure the data integrity. This enforce the reliability and
accuracy of the data stored in the database.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

---------------------------------------------------x-------------------------------------------------------------
BASIC SQL
2.5
Simple Database schema, data types, table definitions (create, alter), different DML
operations (insert, delete, update), basic SQL querying (select and project) using where
clause, arithmetic & logical operations, SQL functions(Date and Time, Numeric, String
conversion).

2.5 Simple Database schema

Sample database schema:


Sailors (sid: integer, sname: string, rating: integer, age: real)
Boats (bid: integer, bname: string, color: string)
Reserves (sid: integer, bid: integer, day: date)
---------------------------------------------------x-------------------------------------------------------------

2.6 Data types


SQL Data Types

o SQL Datatype is used to define the values that a column can contain.
o Every column is required to have a name and data type in the database table.

1. Numeric Datatype
Data type Description
Int It is used to specify an integer value.
Smallint It is used to specify small integer value.
Bit It has the number of bits to store.
Decimal It specifies a numeric value that can have a decimal
number.
Numeric It is used to specify a numeric value.

2. String data types


Data type Description
Char It has a maximum length of 8000 characters. It contains Fixed-length non-
unicode characters.
Varchar It has a maximum length of 8000 characters. It contains variable-length non
-unicode characters.
3.Date and time Datatypes
Datatype Description
Date It is used to store the year, month, and days value.
Time It is used to store the hour, minute, and second values.
Timestam It stores the year, month, day, hour, minute, and the second value.
p

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

---------------------------------------------------x-------------------------------------------------------------
2.7Table definitions (create, alter)

DDL(Data Definition Language) :


DDL or Data Definition Language actually consists of the SQL commands that can be
used to define the database schema. It simply deals with descriptions of the database
schema and is used to create and modify the structure of database objects in the
database.

Examples of DDL commands:


 CREATE – is used to create the database or its objects (like table, index, function,
views, store procedure and triggers).
 DROP – is used to delete objects from the database.
 ALTER-is used to alter the structure of the database.
 TRUNCATE–is used to remove all records from a table, including all spaces
allocated for the records are removed.
 COMMENT –is used to add comments to the data dictionary.
 RENAME –is used to rename an object existing in the database.

Create command:

Syntax:

CREATE TABLE tableName


(
column_1 datatype [ NULL | NOT NULL ],
column_2 datatype [ NULL | NOT NULL ],
...
);
Here,
 The parameter tableName denotes the name of the table that you are going to
create.
 The parameters column_1, column_2… denote the columns to be added to the table.
 The datatype parameter specifies the type of data the column can hold (e.g. varchar,
integer, date, etc.).
 A column should be specified as either NULL or NOTNULL.

SQL CREATE TABLE Example


The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
Example:

CREATE TABLE Persons (


PersonID int,
LastName varchar(255),
FirstName varchar(255),

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Address varchar(255),
City varchar(255)
);
• The PersonID column is of type int and will hold an integer.
• The LastName, FirstName, Address, and City columns are of type varchar and will
hold characters, and the maximum length for these fields is 255 characters.
• The empty "Persons" table will now look like this:

PersonID LastName FirstName Address

-------x-------

Alter command:

Alter command is used for altering the table structure, such as,

 to add a column to existing table

 to rename any existing column

 to change datatype of any column or to modify its size.

 to drop a column from the table.

Consider customers table, which consists of cust_id, name and age attributes.

1. ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

Example

ALTER TABLE Customers


ADD Email varchar(20);

2.DROP COLUMN

To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Example

ALTER TABLE Customers


DROP COLUMN Email;

3.MODIFY COLUMN

To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

Example:

ALTER TABLE Persons


MODIFY COLUMN DateOfBirth date;

4. RENAME A TABLE

To rename a teable

ALTER TABLE old_table_name RENAME TO new_table_name;


Example:

ALTER TABLE customers RENAME TO customer;

5. RENAME COLUMN

To rename a column in an existing table

ALTER TABLE table_name

RENAME COLUMN old_name TO new_name;

EXAMPLE:

ALTER TABLE customer

RENAME COLUMN EmailTO Emailid;

---------------------------------------------------x-------------------------------------------------------------

2.8Different DML operations (insert, delete, update)

DML(Data Manipulation Language): The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation
Language and this includes most of the SQL statements.
Examples of DML:
 INSERT – is used to insert data into a table.
 UPDATE – is used to update existing data within a table.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

 DELETE – is used to delete records from a database table.

Consider ‘student’relation

Rollno Name Age Address

1.INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

It is possible to write the INSERT INTO statement in two ways:

Syntax1: Specify both the column names and the values to be inserted:

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


VALUES (value1, value2, value3, ...);

Syntax: 2 Adding all values

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

Example:

INSERT INTO student values(4, ‘abc’, 19, ‘vijayawada’);

2. UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Example:Updating the record of ‘abc’


UPDATE student
SET age = 20
WHERE name = ‘abc’;
3. DELETE Statement

The DELETE statement is used to delete existing records in a table.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Syntax:

DELETE FROM table_name WHERE condition;

Example:Delete the record of ‘abc’

DELETE FROM student WHERE name = ‘abc’;

---------------------------------------------------x-------------------------------------------------------------
2.9Basic SQL querying (select and project) using where clause

SELECT command:

 The SELECT statement is used to select data from a database.

 The data returned is stored in a result table, called the result-set.

Syntax:
SELECT [DISTINCT | UNIQUE] (*, columnname [ AS alias], ……)
FROM tablename(s)
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY columnname ASC|DESC];
FROM clause is used to list the tables

WHERE clause:
WHERE keyword is used for fetching filtered data in a result set.
 It is used to fetch data according to a particular criteria.
 WHERE keyword can also be used to filter data by matching patterns.
 The WHERE clause is not only used in the SELECT statement, but it is also used in
the UPDATE, DELETE statement, etc.,
List of operators that can be used with where clause:
operator Description
> Greater Than
>= Greater than or Equal to
< Less Than
<= Less than or Equal to
= Equal to
<> Not Equal to
BETWEEN In an inclusive Range
LIKE Search for a pattern
To specify multiple possible values for a
IN column
GROUP BY Clause:

 It Forms groups

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

 The GROUP BY clause is a SQL command that is used to group rows that
have the same values.

 For example, if you want to count how many employees in each department
of the company.

 It groups the databases on the basis of one or more column and aggregates
the results.

 The GROUP BY clause is used in the SELECT statement and it follows the
WHERE clause and precedes the ORDER BY clause.

 The GROUP BY statement is often used with aggregate functions to group


the result-set by one or more columns.

HAVING Clause

 The HAVING Clause enables to specify conditions that filter which group results
appear in the results.
 The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.

 SQL Having Clause is used to restrict the results returned by the GROUP BY clause.
 The HAVING clause must follow the GROUP BY clause in a query and must also
precede the ORDER BY clause if used.

ORDER BY Clause:

 The ORDER BY keyword is used to sort the result-set in ascending or descending


order.
 The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.

PLEASE REFER SQL QUERIES FILE

---------------------------------------------------x-------------------------------------------------------------

2.10 Arithmetic & Logical operations


1. Arithmetic operations:
Assume 'variable a' holds 10 and 'variable b' holds 20, then
Operator Description Example

Adds values on either side of the operator. a + b will


+ (Addition)
give 30

Subtracts right hand operand from left hand operand. a - b will


- (Subtraction)
give -10

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

* Multiplies values on either side of the operator. a * b will


(Multiplication) give 200

Divides left hand operand by right hand operand. b / a will


/ (Division)
give 2

Divides left hand operand by right hand operand and b%a


% (Modulus) returns remainder. will give
0

Examples: Simple Arithmetic operations in SQL


1.Addition
Query:
select (10+40+23) from dual;
Output:
(10+40+23)
----------
73
2. Subtraction:
Query:
select (20-10-5) from dual;
Output:
(20-10-5)
----------
5
3. Multiplication:
Query:
select (2*3) from dual;
Output:
(2*3)
----------
6
4. Division:
Query:
select (20/5) from dual;

(20/5)
----------
4
5. Modulus:
Query:
select12%5;
output:
12 % 5 |
----------
2

2. Logical Operations:

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Here is a list of all the logical operators available in SQL


Sr.No. Operator & Description

ALL
1 The ALL operator is used to compare a value to all values in another value
set.

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

ANY
3 The ANY operator is used to compare a value to any applicable value in the
list as per the condition.

BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.

EXISTS
5 The EXISTS operator is used to search for the presence of a row in a
specified table that meets a certain criterion.

IN
6 The IN operator is used to compare a value to a list of literal values that
have been specified.

LIKE
7 The LIKE operator is used to compare a value to similar values using
wildcard operators.

NOT
The NOT operator reverses the meaning of the logical operator with which
8
it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.

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

IS NULL
10
The NULL operator is used to compare a value with a NULL value.

UNIQUE
11 The UNIQUE operator searches every row of a specified table for
uniqueness (no duplicates).

Consider the CUSTOMERS table having the following records −


SQL> SELECT * FROM CUSTOMERS;

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
Here are some simple examples showing usage of SQL Comparison Operators −

Example 1

SQL> SELECT * FROM CUSTOMERS WHERE AGE >= 25 AND SALARY >= 6500;

Output

+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+

Example 2

SQL>SELECT * FROM CUSTOMERS WHERE AGE >= 25 OR SALARY >= 6500;

Output

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Example 3

SQL>SELECT * FROM CUSTOMERS WHERE AGE IS NOT NULL;

Output

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+

Example 4

SQL>SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ko%';

Output

+----+-------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+-------+-----+---------+---------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+-------+-----+---------+---------+

Example 5

SQL>SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );

Output

+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+

Example 6

SQL> SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;

Output

+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

| 4 | Chaitali | 25 | Mumbai | 6500.00 |


| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+

Example 7

SQL>SELECT AGE FROM CUSTOMERS


WHERE EXISTS (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);

Output

+-----+
| AGE |
+-----+
| 32 |
| 25 |
| 23 |
| 25 |
| 27 |
| 22 |
| 24 |
+-----+
7 rows in set (0.02 sec)

Example 8

SQL>SELECT * FROM CUSTOMERS


WHERE AGE > ALL (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);

Output

+----+--------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+--------+-----+-----------+---------+

Example 9

SQL>SELECT * FROM CUSTOMERS


WHERE AGE > ANY (SELECT AGE FROM CUSTOMERS WHERE SALARY > 6500);

Output

+----+----------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

| 2 | Khilan | 25 | Delhi | 1500.00 |


| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+---------+

---------------------------------------------------x-------------------------------------------------------------

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


• A function is a predefined formula which takes one or more arguments as input
then processes the arguments and returns an output.

Types of SQL functions:


• SQL has many built-in functions for performing calculations on data. SQL functions
may vary from one database management system to another.

• According to the SQL Data Type

1. Numeric Functions: To processing Number Data type


2. String Functions: To Processing on String Data type
3. Conversion Functions: To Convert Data type from one data type to another
4. Date Functions: To processing on Date Data Type

1. Numeric functions:
SQL Numeric Functions:

Numeric Functions are used to perform operations on numbers and return numbers.
Following are the numeric functions defined in SQL:

1. ABS(): It returns the absolute value of a number.


Syntax: SELECT ABS(-243.5);
Output: 243.5
2. ACOS(): It returns the cosine of a number.
Syntax: SELECT ACOS(0.25);
Output: 1.318116071652818

3. ASIN(): It returns the arc sine of a number.


Syntax: SELECT ASIN(0.25);
Output: 0.25268025514207865

4. ATAN(): It returns the arc tangent of a number.


Syntax: SELECT ATAN(2.5);
Output: 1.1902899496825317

5. CEIL(): It returns the smallest integer value that is greater than or equal to a number.
Syntax: SELECT CEIL(25.75);
Output: 26

6. CEILING(): It returns the smallest integer value that is greater than or equal to a

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

number.
Syntax: SELECT CEILING(25.75);
Output: 26

7. COS(): It returns the cosine of a number.


Syntax: SELECT COS(30);
Output: 0.15425144988758405

8. COT(): It returns the cotangent of a number.


Syntax: SELECT COT(6);
Output: -3.436353004180128

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

9. DEGREES(): It converts a radian value into degrees.


Syntax: SELECT DEGREES(1.5);
Output: 85.94366926962348

SQL>SELECT DEGREES(PI());
+------------------------------------------+
| DEGREES(PI())
+------------------------------------------+
| 180.000000
+------------------------------------------+
10. DIV(): It is used for integer division.
Syntax: SELECT 10 DIV 5;
Output: 2

11. EXP(): It returns e raised to the power of number.


Syntax: SELECT EXP(1);
Output: 2.718281828459045

12. FLOOR(): It returns the largest integer value that is less than or equal to a number.
Syntax: SELECT FLOOR(25.75);
Output: 25

13. GREATEST(): It returns the greatest value in a list of expressions.


Syntax: SELECT GREATEST(30, 2, 36, 81, 125);
Output: 125

14. LEAST(): It returns the smallest value in a list of expressions.


Syntax: SELECT LEAST(30, 2, 36, 81, 125);
Output: 2

15. LN(): It returns the natural logarithm of a number.


Syntax: SELECT LN(2);
Output: 0.6931471805599453

16. LOG10(): It returns the base-10 logarithm of a number.


Syntax: SELECT LOG10(2);
Output: 0.3010299956639812

17. LOG2(): It returns the base-2 logarithm of a number.


Syntax: SELECT LOG2(6);
Output: 2.584962500721156
18. MOD(): It returns the remainder of n divided by m.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Syntax: SELECT MOD(18, 4);


Output: 2

19. PI(): It returns the value of PI displayed with 6 decimal places.


Syntax: SELECT PI();
Output: 3.141593

20. POW(): It returns m raised to the nth power.


Syntax: SELECT POW(4, 2);
Output: 16

21. RADIANS(): It converts a value in degrees to radians.


Syntax: SELECT RADIANS(180);
Output: 3.141592653589793

22. RAND(): It returns a random number.


Syntax: SELECT RAND();
Output: 0.33623238684258644

23. ROUND(): It returns a number rounded to a certain number of decimal places.


Syntax: SELECT ROUND(5.553);
Output: 6

24. SIGN(): It returns a value indicating the sign of a number.


Syntax: SELECT SIGN(255.5);
Output: 1

25. SIN(): It returns the sine of a number.


Syntax: SELECT SIN(2);
Output: 0.9092974268256817

26. SQRT(): It returns the square root of a number.


Syntax: SELECT SQRT(25);
Output: 5

27. TAN(): It returns the tangent of a number.


Syntax: SELECT TAN(1.75);
Output: -5.52037992250933

28. ATAN2(): It returns the arctangent of the x and y coordinates, as an angle and
expressed in radians.
Syntax: SELECT ATAN2(7);
Output: 1.42889927219073

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

29. TRUNCATE(): It returns 7.53635 truncated to 2 places right of the decimal point.
Syntax: SELECT TRUNCATE(7.53635, 2);
Output: 7.53

SQL Character Functions


A character or string function is a function which takes one or more characters or
numbers as parameters and returns a character value. Basic string functions offer a
number of capabilities and return a string value as a result set.
Following are the string functions defined in SQL:

1. CONCAT(): This function is used to add two words or strings.

Syntax:

concat(string1, string2)

Example:

SELECT concat(‘helo’, ‘world’) FROM dual;

Output:

heloworld

2. LENGTH(): This function is used to find the length of the string.

Syntax:

LENGTH(string)

Example:

SQL> select length('second it') from dual;

Output:

LENGTH('SECONDIT')

------------------

3. LOWER(): This function is used to convert the upper case string into lower case.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Syntax:

LOWER(string)

Example:

SQL> select lower('ALIET') from dual;

Output:

LOWER

-----

aliet

4. UPPER() : This function is used to convert the lower case string into upper case.

Syntax:

UPPER(string)

Example:

SQL> select upper('sql123') from dual;

Output:

UPPER(

------

SQL123

5. LTRIM(): This function is used to remove the given sub string or empty spaces from
the left- hand side of the original string.

Syntax:

LTRIM(string, substring);

Example1:

SQL> select LTRIM('123123aliet', '123') from dual;

Output:

LTRIM

-----

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

aliet

Example 2:

SQL> select LTRIM(' aliet') from dual;

Output:

LTRIM

-----

Aliet

In the above example empty spaces from left side are removed.

6. RTRIM(): This function is used to remove the given sub string or empty spaces from
the right- hand side of the original string.

Syntax:

RTRIM(string, substring);

Example1:

SQL> select RTRIM('aliet123', '123') from dual;

Output:

RTRIM

-----

aliet

Example 2:

SQL> select RTRIM('aliet ') from dual;

Output:

RTRIM

-----

aliet

SQL Date functions

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

These are functions that take values that are of datatype DATE as input and return values
of datatype DATE, except for the MONTHS_BETWEEN function, which returns a number.

1. NOW(): Returns the current date and time. FORMAT YYYY-MM-DD HH:MM:SS
Example:
SELECT NOW();
Output:
2017-01-13 08:03:52
2. CURDATE(): Returns the current date.
Example:
SELECT CURDATE();
Output:
2017-01-13
3. CURTIME(): Returns the current time.

Example:
SELECT CURTIME();
Output:
08:05:15
4. DATE(): Extracts the date part of a date or date/time expression.

Example:
SELECT DATE('2003-12-31 01:02:03');
Output:
2003-12-31
5. TIME(expr): Extracts the time part of the time or datetime expression expr and returns
it as a string.
Example:
SELECT TIME('2003-12-31 01:02:03');
Output:
01:02:03

SQL Conversion Function

1. TO_CHAR(value, format)

Converts a number or datetime value to a string using the specified format.

Example1:

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD') FROM dual;

Output:

2012-07-19

Example2:

TO_CHAR(1210.73, '9999.9')

Output:

'1210.7'

Example3:

TO_CHAR(1210.73, '$9,999.00')

Output:

' $1,210.73'

Example4:

TO_CHAR(21, '000099')

Output:

' 000021'

------------------------------------------------------------------------------------------------

2. TO_DATE (x [, date_format])

Converts numeric or string value to date

Example1:

TO_DATE('070903', 'MMDDYY')

Output:

July 9, 2003

Example2:

TO_DATE('20020315', 'yyyymmdd')

Output:

2002-Mar-15

Example3:

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.')

FROM DUAL;

Output:

15-JAN-89

---------------------------------------------------------------------------

3. TO_NUMBER(string, format)

converts a character value to a numeric datatype

Example1 :

TO_NUMBER('1210.73', '9999.99')

Output:

1210.73

Example2:

TO_NUMBER('546', '999')

Output:

546

-------------------------------------------------------------------------------------

4. NVL (x, y)

If 'x' is NULL, replace it with 'y'. 'x' and 'y'must be of the same datatype.

Example1:

SELECT NVL(null, 1) FROM DUAL;

Output:

----------------------------------------------------------------------

5. NVLIF(exp1, exp2)

Compares two arguments expr1 and expr2. If expr1 and expr2 are equal, it returns
NULL; else, it returns expr1. Unlike the other null handling function, first argument can't
be NULL.

Downloaded by SCS ascasc (powam69667@bitofee.com)


lOMoARcPSD|36793593

Example1:

SELECT NULLIF (12, 12) FROM DUAL;

Output:

NULL

Example2:

SELECT NULLIF ('SUN', 'MOON') FROM DUAL;

Output:

SUN

---------------------------------------------------------------------------------------

6. DECODE (a, b, c, d, e, default_value)

Checks the value of 'a', if a = b, then returns'c'. If a = d, then returns 'e'. Else, returns
default_value.

Equivalence of IF..THEN..ELSE

Example:

SELECT DECODE(NULL,NULL,'EQUAL','NOT EQUAL',null) FROM DUAL;

Output:

EQUAL

---------------------------------------------------x-------------------------------------------------------------

Downloaded by SCS ascasc (powam69667@bitofee.com)

You might also like