You are on page 1of 37

RDBMS (By kusuma mam)

BCom CA SEM-3

Unit - 3

(Structured Query Language (SQL))

Table of Contents

3.1 Introduction to Structured Query Language (SQL)....................................................................................................4


3.1.1 SQL Terminology.......................................................................................................................................................4
3.1.2 Role of SQL in Database Architecture........................................................................................................................4
3.1.3 SQL Standards – Their Characteristics and Benefits..................................................................................................5
3.1.4 Database Schema......................................................................................................................................................5
3.1.5 Levels of Database Schema.......................................................................................................................................6
3.1.6 Difference between Data Schema and Database......................................................................................................6
3.1.7 SQL Tables................................................................................................................................................................. 6
3.1.8 SQL Data Types..........................................................................................................................................................6
3.1.9 Difference between CHAR, VARCHAR and VARCHAR2..............................................................................................7
3.2 SQL Commands.........................................................................................................................................................8
3.2.1 DDL Commands.........................................................................................................................................................9
3.2.2 DML Commands......................................................................................................................................................12
3.2.3 DCL Commands.......................................................................................................................................................15
3.2.4 TCL Commands........................................................................................................................................................16
3.2.5 DUAL Table in Oracle...............................................................................................................................................17
3.2.6 Operators in SQL.....................................................................................................................................................18
3.2.6.1 Types of Operators Based on Number of Operands................................................................................................18
3.2.6.1.1 Unary Operators..............................................................................................................................................18
3.2.6.1.2 Binary Operators.............................................................................................................................................18
3.2.6.2 Types of Operators Based on the Type of Operation..............................................................................................18
3.2.6.2.1 Arithmetic Operators.......................................................................................................................................18
3.2.6.2.2 Comparison Operators....................................................................................................................................19
3.2.6.2.3 Logical Operators.............................................................................................................................................19
3.2.6.2.4 Special Operators............................................................................................................................................20
3.2.6.2.5 Character Operators........................................................................................................................................20
3.2.7 SQL NULL Value.......................................................................................................................................................20
3.2.8 Aggregate Functions................................................................................................................................................21
3.3 SQL Queries.............................................................................................................................................................22
3.3.1 ORDER BY Clause.....................................................................................................................................................22
3.3.2 WHERE Clause.........................................................................................................................................................22
3.3.3 GROUP BY Clause & HAVING Clause........................................................................................................................22
3.3.4 Nested Queries (Sub Queries).................................................................................................................................23
3.3.4.1 Correlated Sub Query:.............................................................................................................................................24
3.3.4.2 Difference between a Sub Query and a Correlated Sub Query:..............................................................................24
3.4 SQL Joins..................................................................................................................................................................25
3.4.1 NON EQUI JOIN:......................................................................................................................................................25
3.4.2 EQUI JOIN:...............................................................................................................................................................25
3.4.2.1 SQL Inner Join:.........................................................................................................................................................25
3.4.2.1.1 SQL Self Join:...................................................................................................................................................26
3.4.2.2 SQL Outer Join:........................................................................................................................................................27
3.4.2.2.1 Left Outer Join:................................................................................................................................................27
3.4.2.2.2 Right Outer Join...............................................................................................................................................28
3.4.2.2.3 Full Outer Join..................................................................................................................................................29
3.5 SQL Views................................................................................................................................................................30
3.6 Sequences...............................................................................................................................................................31
3.7 Indexes and Synonyms............................................................................................................................................32
3.8 SQL Integrity Constraints.........................................................................................................................................32
3.9 Oracle Built In Functions..........................................................................................................................................35
3.1 Introduction to Structured Query Language (SQL)

 SQL stands for Structured Query Language. It is sometimes called as SEQUEL (Structured English Query Language).
 SQL is a query language used for accessing and modifying information in the database. That is, it lets us access and
manipulate databases.
 SQL is an ANSI (American National Standards Institute) standard
 Few of the SQL commands used in SQL programming are SELECT Statement, UPDATE Statement, INSERT INTO
Statement, DELETE Statement, WHERE Clause, ORDER BY Clause, GROUP BY Clause, Joins, Views, GROUP Functions,
Indexes etc
 SQL is a non-procedural, English-like language that processes data in groups of records. Few functions of SQL are:
 Create tables and other database objects
 Store Data
 Modify Data
 Retrieve Data
 Delete Data
3.1.1 SQL Terminology

Catalog: A catalog is a directory of information about data sets, files, or a database. It usually describes where a data set,
file or database entity is located and may also include other information, such as the type of device on which each data
set or file is stored

Schema: A database schema is a structure that contains description of objects created by a user such as tables, views,
stored procedures etc. We can assign login permissions to a single schema to a user so that the user can only access the
objects they are authorized to access

Data Definition Language (DDL): DDL is a set of commands that are used to create and modify the structure of database
objects in database (i.e. creating, altering, dropping tables and establishing constraints)

Data Manipulation Language (DML): DML is a set of commands that are used to store (insert), retrieve, modify (update)
or delete data in database

Data Control Language (DCL): DCL is a set of commands used to control access to data stored in a database
(Authorization). It includes commands for administering user privileges
Transaction Control Language (TCL): TCL is a set of commands used to manage transactions in database. These are used
to manage the changes made by DML statements. It also allows statements to be grouped together into logical
transactions

3.1.2 Role of SQL in Database Architecture

 Many RDBMS are available on many operating system platforms including WINDOWS and UNIX. Oracle is a popular
example of an RDBMS. Even the Data Dictionary is simply a collection of tables of data along with indexes and other
objects such as sequences and triggers that are created using SQL
 SQL has a basic grammar and syntax
 The functionality of the SQL language is virtually identical across all the operating system platforms
 For using SQL, one does not require programming experience. But if one has, it can help them to conceptualize
what a particular SQL command will help to execute and retrieve SQL queries that result data using SELECT, FROM,
WHERE and ORDER BY commands.

3.1.3 SQL Standards – Their Characteristics and Benefits

 SQL supports basic data structures and operations that allow the user to design (create), access (retrieve), maintain
(update, delete), control and protect data in database.
 Well Defined Standards Exist: SQL databases use long-established standard, which is being adopted by ANSI & ISO.
Non-SQL databases do not adhere to any clear standard. Hence, SQL works with database programs like DB2, Oracle,
MS Access, Sybase, and MS SQL Server etc.
 Reduced Training Costs: Using standard SQL it is easier to manage database systems without having to write
substantial amount of code.
 High Speed: SQL Queries can be used to retrieve large amounts of records from a database quickly and efficiently.
 Portability of applications and database definition: It is easy to move database applications and database definition
from one machine to another
 Increased Productivity: SQL is very simple and easy to learn. Hence, DB programmers can become proficient in its
use.
 Application Longevity: An Application designed using SQL tends to remain standard for a long time
 Reduced dependence on a single vendor: Since SQL is a standard query language that works with many database
programs (like DB2, Oracle, MS Access, Sybase, and MS SQL Server), hence there is no dependence on a single
vendor
 Emergence of ORDBMS: Previously SQL databases were synonymous with relational database. With the emergence
of Object Oriented DBMS, object storage capabilities are extended to relational databases.

3.1.4 Database Schema

 The schema of a database system is its structure described in a formal language (like SQL) supported by the
database management system (DBMS)
 The term "schema" refers to the organization of data as a blueprint of how the database is constructed (divided into
database tables in the case of relational databases)
 The formal definition of a database schema is a set of formulas (sentences) called integrity constraints imposed on a
database. It can contain formulas representing integrity constraints specifically for an application and the constraints
specifically for a type of database, all expressed in the same database language.
 In a relational database, the schema defines the tables, fields, relationships, views, indexes, procedures, functions,
triggers, sequences, materialized views, synonyms, XML schemas, and other elements.
 A database generally stores its schema in a data dictionary. Although a schema is defined in text database language,
the term is often used to refer to a graphical depiction of the database structure.
 In other words, schema is the structure of the database that defines the objects in the database

3.1.5 Levels of Database Schema

A database schema can be divided broadly into two categories −

Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices,
etc. It defines how the data will be stored in a secondary storage.

Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It
defines tables, views, and integrity constraints.

3.1.6 Difference between Data Schema and Database

The Data Schema (or simply “schema”) and Database are different. A schema contains a group of tables whereas a
database contains a group of schemas.

Data Schema
 Schema is a logical structure defined to store data in Database. A schema defines attributes of the database such as
tables and its properties (columns).
 A schema is the set of metadata (data dictionary) used by the database (generated using DDL). A database schema is
a description of the data in a database. Simply we can consider a schema to be a user account and collection of all
objects within it

Database

 A Database is a collection of inter-related data. It is a memory component to store Data, connected to a computer
installed with DBMS Software (such as Oracle, MySQL etc).
 A database is the thing that contains all the schemas we create and their data (plus a bunch of predefined system
users, tables, views, etc. that make the whole things work).

3.1.7 SQL Tables

 A table is a collection of related data held in a structured format within a database. It consists of columns, and rows.
 In relational databases, and flat file databases, a table is a set of data elements (values) using a model of vertical
columns (identifiable by name) and horizontal rows, the cell being the unit where a row and column intersect.
 A table has a specified number of columns, but can have any number of rows.
 Each row is identified by the values in one or more columns.
 A specific set of columns which uniquely identify a row is called the primary key.

3.1.8 SQL Data Types

 A data type specifies a particular type of data such as integer, floating-point, Boolean (true or false) etc.
 A data type also specifies the possible values for that type, the operations that can be performed on that type and
the way the values of that type are stored. For Ex: Oracle treats values of one data type differently from values of
another by using a set of properties
 Data stored in a relational database can be stored using a variety of data types. SQL provides many predefined data
types and subtypes. The primary oracle data types are NUMBER, CHAR and VARCHAR for storing numbers and text
data
 Following are the Key Data Types in SQL:

Data Type Syntax Description


NUMBER(size) It is a fixed-point number format;
It is used to store a number of specified size in
digits;
NUMBER(size, d) It is used to store a number of specified “size”
(equivalent to 39 or 40 decimal digits depending on
the position of the decimal point) with “d” digits (it
can range from -84 to 127) after the decimal point;
CHAR(size) It is used to store fixed-length character data;
Size is the number of characters to store (Maximum
supported size is 255 characters);
By default, this data type occupies 1 byte of memory
per character;
It is padded on right side with spaces to full length
of the specified size
VARCHAR2(size) It is used to store a variable-length character string;
size specifies the maximum number of characters of
data that it can hold (Minimum 1 byte to Maximum
4000 bytes);
DATE Valid dates ranging from January 1, 4712 BC, to
December 31, 9999 AD;
The default date format is DD-MON-YY;
Ex: 09-MAR-18

3.1.9 Difference between CHAR, VARCHAR and VARCHAR2

CHAR:

1) Fixed length memory storage


2) CHAR takes up 1 byte per character
3) We need to use CHAR when the data entries in a column are expected to be the same size
4) For Ex: Consider the below case. “test” occupies 100 bytes with first four bytes having the actual character data
values and rest with blank data

Declare test CHAR(100);


test=”Test”;

VARCHAR:

1) Variable length memory storage (changeable)


2) VARCHAR takes up 1 byte per character + 2 bytes to hold length information
3) We need to use VARCHAR when the data entries in a column are expected to vary considerably in size
4) For Ex: Consider the below case. “test” occupies only 4+2=6 bytes: first 4 bytes for value and other 2 bytes for
variable length information

Declare test VARCHAR(100);


test=”Test”

VARCHAR2:

1) It is a replacement for VARCHAR in new versions of Oracle


2) VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters
3) If VARCHAR is used in declaration then it will occupy space for NULL values. In case of VARCHAR2 data type, it will
not occupy any space for NULL values
3.2 SQL Commands

 SQL commands help the user to interact with SQL application and the database and pass instructions to perform
specific task that work with data to create, update or manage the database
 SQL commands can be used not only for searching the database but also to perform various other functions like, for
example, we can create tables, add data to tables, modify data, drop the table or set permissions for users.
 SQL commands provide access for the structure and also the data part of the tables.
 SQL commands are grouped into 4 major categories depending on their functionality. Following is their overview:

Language Command Description


Data Definition Language (DDL) CREATE Create a new database object (like Table) and
add it to data dictionary
DDL commands are used to DESCRIBE Allows us to view the structure/description of
create/alter/modify a database or an already created table
table structure and schema. These ALTER Change the definition (structure) of an existing
statements handle the design and table, column
storage of database objects. DROP Removes a database object (like table) from
the data dictionary
RENAME Allows us to change the name of an already
existing table
TRUNCATE It is used to remove all the rows from a table
Data Manipulation Language (DML) INSERT Insert new record(s) into a table
UPDATE Update/modify the values of existing records in
DML consists of basic operations we a table
perform on data such as selecting a DELETE Delete existing records from a table
few records from a table, inserting SELECT Select (Identify) the column values to display
new records, deleting unnecessary from a table
records, and modifying existing
records.
Data Control Language (DCL) GRANT Allows users to read/write on certain database
objects by giving privileges to user groups
DCL commands control the level of REVOKE Allows the DBA to take away the user
access that users have on database privileges (like read/write permission) on
objects. database objects
Transaction Control Language (TCL) COMMIT Allows the user to commit (make permanent
changes to database) all changes made by SQL
TCL commands allow us to control during the unit of work
and manage transactions to SAVEPOINT Allows the user to mark the current point in
maintain the integrity of data within the processing of a database transaction
SQL statements. ROLLBACK Allows the user to undo the changes made by
SQL during the unit of work
3.2.1 DDL Commands

 Data Definition Language (DDL) deals with database schemas and descriptions of how the data should reside in the
database
 DDL commands are used to create, modify and delete the structure of the object in the database
 The syntax of DDL command includes TABLE keyword after the command name. Following are the DDL commands:

i) CREATE

 The CREATE TABLE statement allows us to create structure of the table and specify all the required columns,
their data type and size of the columns (to store data).
 Data type is used to specify the type of data to be stored in the selected column
 Size specifies the number of elements inside the column
 Integrity Constraints (entry level rules to ensure data integrity) like primary key, unique key, foreign key can
be defined for the selected columns while creating the table
 Syntax: The syntax for the CREATE TABLE statement in SQL is:

CREATE TABLE table_name


(
column1 datatype(size),
column2 datatype(size),
...
);

table_name - is the name of the table to be created


column1, column2 etc – are the names of the columns
datatype – is the data type for the columns (like number, char, date etc)

 Example:

SQL> CREATE TABLE student (


Rollno number(2),
Name varchar2(20),
Course varchar2(10)
);

ii) DESCRIBE

 DESCRIBE command is used to view the structure/description of an already created table


 It lists all the columns in the specified table or view.
 It returns one row per table column, containing:
 Column: The name of the column
 Type: The type of data in the column
 Nullable: Whether nulls are allowed (1=yes, 0=no)
 Primary Key: Whether the column is in the primary key (1=yes, 0=no)
 Syntax1: DESCRIBE table_name;
 Syntax1 Example: DESCRIBE student;
 Syntax2: DESC table_name;
 Syntax2 Example: DESC emp;

iii) ALTER

 The ALTER TABLE command is used to change the definition (structure) of an existing table by modifying the
definition of its columns
 The ALTER command is used to perform the following functions:
i) Add, modify or drop columns of a table
ii) Add and drop constraints
iii) Enable and Disable constraints

 Syntax to add a new column:


ALTER TABLE table_name add(newcolumn datatype(size));

 Example to add a new column: To add a column “phno” to the student table, the query would be as follows:
ALTER TABLE student add(phno number(10));

 Syntax to modify an existing column:


ALTER TABLE table_name modify(columnname datatype(new-size));

 Example to modify an existing column: To modify the size of the column “name” to “25” in student table,
the query would be as follows:
ALTER TABLE student modify(Name varchar2(25));

 Syntax to drop an existing column:


ALTER TABLE table_name drop columnname;

 Example to drop an existing column:


ALTER TABLE student drop phno;

iv) DROP

 The DROP TABLE command is used to remove an object from the database (destroys a table structure)
 The DROP command removes the table structure from the database including all the rows in the table
 When a table is dropped all the references to the table will become invalid

 Syntax for dropping a table:


DROP TABLE table_name;

 Example for dropping a table:


DROP TABLE student;

v) RENAME

 RENAME statement is used to change the name of the table


 Syntax: The syntax for RENAME statement is as follows. Here, table_name is the table that exists in the
current database and new_table_name is the new table name
RENAME TABLE table_name TO new_table_name;

 Example:
RENAME TABLE student TO s;

vi) TRUNCATE

 The TRUNCATE command is used to delete all the rows from the table and free the space containing the
table
 It removes all the rows of a table and commits the data in the table

 Syntax:
TRUNCATE TABLE table_name;

 Example:
TRUNCATE TABLE student;

3.2.2 DML Commands

 DML stands for Data Manipulation Language


 DML consists of basic operations we perform on data such as selecting a few records from a table, inserting new
records, deleting unnecessary records, and modifying existing records.
 DML commands are limited to the data part of the table and does not involve with the structure of the table
 Following are the DML commands:

i) INSERT

 INSERT command is used to enter and store the values in the database object in the defined order and type
(INSERT statement is used to add new rows of data to a table)
 The data values given by the user in the insert statement should match with the data type declared for the
selected column
 SQL INSERT command is implemented in 3 different methods. They are:

1) Simple INSERT statement


 We need to describe the structure of the table before inserting the values using this INSERT
method
 Simple insert statement is used to insert a single row of values to the selected table.
 The data values are directly specified in a pair of parentheses as (datavalue1,datavalue2,….)
followed by “values” keyword
 The data values should be given in the same sequence as the table fields are created
 Numeric values are directly specified (i.e. specified as it is) where as the char/varchar/varchar2
values are enclosed in single quotations (written as ‘ravi‘)
 Syntax:
insert into table_name values(column1 value, column2 value, …., column n value);
 Example:
Insert into student values(1, ‘abc’, ‘BCom’, 9999999999);

2) Partial INSERT statement


 Partial insert statement is used to enter values for selected columns by leaving other columns
empty (or by specifying a default value constraint for it)
 The statement is implemented using insert command by specifying required fields in a pair of
parentheses and specifying the values for the selected fields with “values” keyword
 In this insert method, order of values are dependent on the column names given with insert
command
 Syntax:
Insert into table_name(column1, column2, column4) values(column1_value,
column2_value, column4_value);
 Example:
Insert into student(rollno, name, phno) values(2, ‘xyz’, 8888888888);

3) Interactive INSERT statement


 Interactive insert is the method of insert statement used to enter multiple values to the selected
table with various values.
 In order to insert multiple records in selected table, interactive insert statement is implemented
 An ampersand operator (&) is used to display interactive messages to accept the values given by
the user and store them in the given fields
 & operator is preceded before the field name (as in &rollno to accept the value for rollno field).
Char, varchar, varchar2, date columns should be enclosed in single quotations (as in ‘&name’ to
accept the value for name field). Columns are separated by a comma (,) and the statement is
terminated by a semicolon (;)
 Syntax:
Insert into table_name values(&column1, ‘&column2’, ‘&column3’, &column4);
 Example:
Insert into student values(&rollno, ‘&name’, ‘&course’, &phno);

When above interactive insert statement is executed, DBMS interacts with the user as below
and user can insert multiple records (in this case, we are inserting 2 records):

SQL> Enter value for rollno: 3


SQL> Enter value for name: pqr
SQL> Enter value for course: BSc
SQL> Enter value for phno: 8989898989
SQL> 1 row inserted
SQL> / 
SQL> Enter value for rollno: 4
SQL> Enter value for name: mno
SQL> Enter value for course: BCom
SQL> Enter value for phno: 5656565656
SQL> 1 row inserted

ii) UPDATE

 UPDATE command is used to edit or update the data values in a table based on conditions for the selected
record or field.
 In the Update statement, WHERE clause identifies the rows that get affected. If the WHERE clause is not
implemented, column values for all the rows get affected
 Update command is implemented using “set” keyword to overwrite the previous data values with currently
given values
 The update command is used for multiple purposes as following:
 To change the content (values) for the selected records
 To enter the values for the fields which are left empty during insertion
 To update the fields by performing calculations (such as sum, average)
 To delete the data for the selected row/column by specifying empty values
 Syntax:
Method1
UPDATE table_name SET column1=value1, column2=value2, …. [WHERE condition];

Method2
UPDATE table_name SET column1=expression1, column2=expression2, …. ;

Here,
table_name - is the table name which is being updated
Column1, column2, … - the columns whose values are being updated
Value1, value2, ... – are the new values being updated
Expression1, expression2, … - are the expressions that evaluate to new values being updated

 Ex1: update student set name=’Srinivas’ where rollno=1;


 Ex2: update student set (rollno=2,name=’Lakshmi’) where rollno=2;

iii) DELETE

 DELETE statement is used to delete record(s) from a table based on user choice
 It deletes either single record or multiple records based on conditions specified using “where” clause
 Delete is used to remove only data records (not the fields/columns)
 The WHERE clause in the DELETE command is optional and it identifies the rows in the column that gets
deleted. If the WHERE clause is not included, all the rows in the table are deleted
 Syntax:
DELETE from table_name [WHERE condition];
 Ex1: delete from student where name=’abc’;
 Ex2: delete from student;

Q) What is the difference between DELETE and TRUNCATE commands?


A) DELETE is a DML command used to remove rows from the table (with or without specifying WHERE
clause). Commit and Rollback can be performed after issuing DELETE command. Moreover, it will not clear
the table space used by the rows.

TRUNCATE is a DDL command which removes all rows from the table. It cannot be rolled back. Moreover, it
will clear the table space used by the rows.

iv) SELECT

 SELECT is the most commonly used SQL command


 SELECT statement is used to query or retrieve data from a table in the database
 A query may retrieve information from specified columns or from all of the columns in the table
 To create a simple SQL SELECT statement, one must specify the column(s) name and the table name
 The purpose of SELECT statement is to select all columns and rows from a table. * (all columns) and distinct
are the options used with it
 Syntax:

SELECT column1, column2, … FROM table_name


[WHERE clause]
[ORDER BY clause]
[GROUP BY clause]
[HAVING clause];

Here,
Table_name is the name of the table from which the information is retrieved
Column1, column2, … includes one or more columns from which data is retrieved
The clauses mentioned with in the open brackets are optional

 WHERE clause: It is used to post conditions and retrieve only selected records
 ORDER BY clause: It is used to sort the result-set by a specified column (either by ascending or by
descending order)
 GROUP BY clause: It is used to collect data across multiple records and group the results by one or more
columns
 HAVING clause: It is used in combination with the GROUP BY clause to filter the records returned by GROUP
BY clause.
 A select statement is used to display the records in multiple methods as
 All rows and all columns
 Selected columns and all rows
 Selected rows with all columns
 Selected rows with selected columns
 Ex1: select * from student;
The above command displays all the records and fields from the student table
 Ex2: select rollno, name, course from student;
The above command is used to display selected columns with all the records available in the table
 Ex3: select * from student where rollno=3;
The above command is used to display all the columns for the record where the rollno of the student is
3 from student table (i.e. only selected records with all fields)
 Ex4: select rollno, name, course from student where rollno=2;
The above command is used to display selected columns and selected records based on the condition.

3.2.3 DCL Commands

 DCL stands for Data Control Language. It is also a subset of SQL.


 DCL commands allows the Database Administrators to control the level of access that users have on database
objects
 DCL commands are used to enforce database security in a multiple user database environment
 Two types of DCL commands are GRANT and REVOKE

i) GRANT

 GRANT is a command used to provide access or privileges on the database objects to the users

 Syntax for GRANT command is:

GRANT privilege_name
ON object_name
TO {user_name | public | role_name}
[WITH GRANT OPTION];

Privilege_name is the access right or privilege granted to the user. Some of the access rights are ALL,
CONNECT, SELECT, UPDATE, DELETE etc
Object_name is the name of a database object like TABLE, VIEW and SEQUENCE
User_name is the name of the user to whom privileges are granted
Public is used to grant access rights to all users
Role_name is a set of privileges granted to a role (group of users)
WITH GRANT OPTION – allows a user to grant access rights to other users

Example:

Step1: Create a new user as below:


Create user u1 identified by u1pwd;
Step2: Grant SELECT privilege to the user u1 as below:
GRANT SELECT ON student TO u1;

ii) REVOKE

 REVOKE command is usually used by an administrator user to remove the database access from a user
which were previously granted
 Syntax:

REVOKE privilege_name
ON object
FROM user_name;

 Ex: REVOKE SELECT ON student FROM u1;

3.2.4 TCL Commands

 TCL stands for Transaction Control Language. It is a subset of SQL


 A transaction is a unit of work (sequence of steps) that is performed against a database.
 For example: if we are creating, updating or deleting a record from the table, then it means we are performing a
transaction on that table. It is important to control these transactions to ensure the data integrity and to handle
database errors.
 Practically, we will club many SQL queries into a group and execute them together as a part of a transaction.
 TCL commands are used with the DML Commands (such as - INSERT, UPDATE and DELETE) only. They cannot be used
while creating tables or dropping them because these operations are automatically committed in the database.
 The following commands are used to control transactions:

i) COMMIT

 The COMMIT command is the transactional command used to permanently save changes done by a
transaction in SQL to the database.
 It saves all the transactions to the database since the last executed COMMIT or ROLLBACK command.
 Syntax for committing a database transaction:
COMMIT [WORK];

ii) ROLLBACK

 The ROLLBACK command is the transactional command used to undo transactions that have not already
been saved to the database.
 It can only be used to undo transactions since the last COMMIT or ROLLBACK command issued.
 Syntax for rolling back a database transaction:
ROLLBACK [WORK];
iii) SAVEPOINT

 A SAVEPOINT is a point in a transaction up to which we can rollback the transaction without rolling back
the entire transaction.
 Syntax:
SAVEPOINT SAVEPOINT_NAME;
 Examples:
SAVEPOINT SP1;
SAVEPOINT SP2;
 The syntax for rolling back to a SAVEPOINT is as shown below:
ROLLBACK TO SAVEPOINT_NAME;
 Example for rolling back to the SAVEPOINT named SP1:
ROLLBACK TO SP1;

3.2.5 DUAL Table in Oracle

 The DUAL table is a special one-row, one-column table present by default in Oracle and other database installations.
 In Oracle, this table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'.
 DUAL table is useful for computing a constant expression with the SELECT statement.
 Example: It is suitable for selecting a pseudo column such as SYSDATE or USER as specified below:

select sysdate from dual;  It returns the current system date


select user from dual;  It returns the username of the current user logged on to sql

3.2.6 Operators in SQL

 An Operator is a symbol or a keyword which manipulates data items (called operands) and returns a result
 Examples: The multiplication operator is represented by an asterisk (*), an operator that tests for nulls is
represented by the keywords IS NULL
 There are two types of operators as mentioned below:

3.2.6.1 Types of Operators Based on Number of Operands

3.2.6.1.1 Unary Operators

 A unary operator is the operator that operates on only one operand.


 Syntax: operator operand
 Ex: -300 (Here, - is the operator and 300 is the operand)

3.2.6.1.2 Binary Operators

 An operator is referred to as binary if it operates on two operands


 Syntax: operand1 operator operand2
 Ex: 12 + 13

3.2.6.2 Types of Operators Based on the Type of Operation

3.2.6.2.1 Arithmetic Operators

 Operators which are used to perform Arithmetic Operations (mathematical calculations) in SQL are called Arithmetic
Operators
 Following are the arithmetic operators in SQL:

Operator Description Example


+ (unary) Makes operand positive Select +3 from dual;
- (unary) Makes operand negative Select -4 from dual;
* Multiplication operator Select sal * 5 from emp;
/ Division operator Select sal / 10 from emp;
+ (binary) Addition operator Select sal + 2000 from emp;
- (binary) Subtraction operator Select sal – 100 from emp;
Mod (modulus) Modulus operator (Division operator that returns Select mod(sal,4) from emp;
remainder as result)

3.2.6.2.2 Comparison Operators

 A comparison (or relational) operator is a mathematical symbol which is used to compare two values.
 Comparison operators are used in conditions that compare one expression with another. The result of a comparison
can be TRUE, FALSE, or UNKNOWN (an operator that has one or two NULL expressions returns UNKNOWN).
 Following are the comparison operators in SQL:

Operator Description Example


= Equal to Select ename from emp where sal = 1500;
<> Not equal to Select ename from emp where sal <> 5000;
< Less than Select ename, job from emp where sal < 1000;
<= Less than or equal to Select ename, job from emp where sal <= 1000;
> Greater than Select ename, job from emp where sal > 3000;
>= Greater than or equal to Select ename, job from emp where sal >= 3000;

3.2.6.2.3 Logical Operators

 The Logical operators are those that compare two conditions at a time to determine whether a row can be selected
for the output or not.
 It returns a true or false value when combined with one or more true or false values.
 When retrieving data using a SELECT statement, we can use logical operators in the WHERE clause
 Following are the logical operators in SQL:

Operator Description Example


AND Returns TRUE if both conditions Select * from emp where
are TRUE; Returns FALSE if either job=’CLERK’ AND deptno=10;
conditions is FALSE; otherwise
returns UNKNOWN (if either of
conditions are UNKNOWN)
OR Returns TRUE if either condition is Select * from emp where
TRUE; Returns FALSE if both are job=’CLERK’ OR deptno=10;
FALSE; Otherwise, returns
UNKNOWN
NOT Returns TRUE if the given Select * from emp where NOT (job
condition is FALSE; Returns FALSE is NULL);
if it is TRUE; If it is UNKNOWN, it
remains UNKNOWN Select * from emp where NOT (sal
BETWEEN 1000 AND 2000);

3.2.6.2.4 Special Operators

 Following are the special operators in SQL:

Operator Description Example


IN Equivalent to “any member of” Select * from emp where ename IN
(‘SMITH’,’WARD’);
BETWEEN x and y Equivalent to “Greater than or Select ename, job from emp where
equal to x and less than or equal sal BETWEEN 2000 AND 5000;
to y”
x LIKE y Returns TRUE if x matches the Select * from emp where ename
pattern y. Within y, the character like ‘%E%’;
“%” matches any string of zero or
more characters except null Select * from emp where ename
like ‘J_m%’;
The character “_” matches any
single character
EXISTS TRUE if a sub-query returns at Select * from emp where EXISTS
least one row (select ename from emp where
MGR is null);
IS NULL Tests for a null value Select * from emp where comm is
NOT NULL and sal > 1500;

3.2.6.2.5 Character Operators


 Character operators are used in expressions to manipulate character strings
 Concatenation Operator is one of mostly used character operators
 Concatenation Operator in SQL: ||
 Description: Concatenates the character strings
 Example: select empno || ‘-‘ || ename || ‘-‘ || sal from emp;

3.2.7 SQL NULL Value

 The 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
 A field with a NULL value is a field with no value
 A NULL value is different than a zero value or a blank value
 By default, a table column can hold NULL values
 It is not possible to test for NULL values with comparison operators (such as =, <>, < etc). We have to use IS NULL
or IS NOT NULL operator for determining if a given value is NULL or not
 The column can contain NULL value only if the NOT NULL constraint is not mentioned
 An example specifying a NOT NULL constraint while creating a table:

CREATE TABLE STUDENT


(
ROLLNO NUMBER(3) NOT NULL,
NAME VARCHAR2(20) NOT NULL,
ADDRESS VARCHAR2(40),
PHNO NUMBER(10)
);

 In the above example, NOT NULL specifies that column should always accept an explicit value of the given data
type. There are 2 columns where NOT NULL is not used which means these columns can contain a NULL value. A
field with a NULL value is one that has been left blank during record creation
 Example: select * from emp where comm is NULL;

3.2.8 Aggregate Functions

 An aggregate function allows us to perform a calculation on a set of values to return a single scalar value
 We often use aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement
 The following are the most commonly used SQL aggregate functions:

MIN(X) – gets the minimum value in a set of values in column X.


MAX(X) – gets the maximum value in a set of values in column X.
SUM(X) – calculates the sum of values in column X.
AVG(X) – calculates the average of a set of values in column X.
COUNT(X) – counts the number of values in column X in a specified table or view.
COUNT (*) – counts the number of records in a specified table or view.
 All aggregate functions except the COUNT function ignore NULL values.

 Syntax: AGGREGATE_FUNCTION ([DISTINCT | ALL] EXPRESSION) where

AGGREGATE_FUNCTION - is the name of the aggregate function (such as MIN, MAX, SUM, AVG or COUNT)
DISTINCT - specifies that the aggregate function should consider only distinct values of the argument expression
ALL - specifies that the aggregate function should consider all values including all duplicate values of the
argument expression. The default is ALL
EXPRESSION - Specifies a column, or any other expression, on which we want to perform the aggregation

 Examples:

 select count(age), count(distinct age), count(all age) from emp;


 select max(sal) from emp;
 select avg(sal) from emp;

3.3 SQL Queries

3.3.1 ORDER BY Clause

 The ORDER BY keyword is used to sort the result-set (resulting records from a query) in ascending or descending
order.
 The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, we
need to use the DESC keyword.
 Syntax: SELECT column1, column2, .. FROM tablename ORDER BY column1, column2, .. ASC|DESC;
 Example: The following SQL statement selects all employees from the "EMP" table, sorted by the "JOB" column:
SELECT * FROM EMP ORDER BY JOB;
 ORDER BY DESC Example: The following SQL statement selects all employees from the "EMP" table, sorted in the
Descending order by the "JOB" column: SELECT * FROM EMP ORDER BY JOB DESC;

3.3.2 WHERE Clause

 The WHERE clause is used to filter records. It is used with conditional statements which use comparison operators
(such as =, <>, <, > etc)
 The WHERE clause is used to extract only those records that fulfill a specified condition. Note: The WHERE clause is
not only used in SELECT statement, it is also used in UPDATE, DELETE statement, etc
 Syntax: SELECT column1, column2, .. FROM tablename WHERE condition;
 Example: The following SQL statement selects all the employees from the department with deptno "10", in the
"EMP" table: SELECT * FROM EMP WHERE deptno=10;

3.3.3 GROUP BY Clause & HAVING Clause


 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.

 GROUP BY clause Syntax:

SELECT column_name(s) FROM table_name


GROUP BY column_name(s);

 Example: The following SQL statement lists the number of employees working for each job

SELECT COUNT(EMPNO), JOB FROM EMP GROUP BY JOB;

 The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions
(such as MIN, MAX, SUM etc). That is, SQL HAVING clause is “like a WHERE clause for aggregated data”

 HAVING clause is always used with GROUP BY clause. That is, any column name appearing in the HAVING clause
must also appear in the GROUP BY clause.

 HAVING clause Syntax:

SELECT column_name(s) FROM table_name


GROUP BY column_name(s) HAVING condition;

 HAVING clause Example: The following SQL statement lists the number of employees working for each job. Only
include those jobs with more than 2 employees:

SELECT COUNT(EMPNO), JOB FROM EMP GROUP BY JOB HAVING COUNT(EMPNO) > 2;

3.3.4 Nested Queries (Sub Queries)

 A sub query is a SQL query nested inside a larger query.


 A sub query may occur in :
 A SELECT clause
 A FROM clause
 A WHERE clause
 The sub query can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another sub query to
perform the following tasks:
 Compare an expression to the result of the query
 Determine if an expression is included in the results of the query
 Check whether the query selects any rows
 A sub query is usually added within the WHERE clause of another SQL SELECT statement. We can use the
comparison operators (such as >, <, or =), multiple-row operators (such as IN, LIKE, or BETWEEN) in that WHERE
clause.
 A sub query is also called an inner query or inner select, while the statement containing a sub query is also called an
outer query or outer select.
 The inner query executes first before its parent query so that the results of an inner query can be passed to the
outer query.
 Syntax: select col_list from table_name where col_name operator (select col_list from table_name);
 The sub query (inner query) executes once before the main query (outer query) executes. The main query (outer
query) uses the sub query result.
 Example for sub query inside SELECT statement: The following SQL statement displays the details of the employee
with the highest salary:

select * from emp where sal = (select max(sal) from emp);

 Example for sub query inside UPDATE statement: The following SQL statement updates the salary of employees
who belongs to department ‘SALES’. In this example, observe that 2 different tables are involved: the outer query
acts on EMP table where as inner query acts on DEPT table

update emp set sal=1800 where deptno = (select deptno from dept where dname='SALES');

 Example for sub query inside INSERT statement: The following SQL statement inserts all the records available in the
table student1 into another table student2 (having the same structure as student1)

Insert into student2 (select * from student1);

3.3.4.1 Correlated Sub Query:

 A correlated sub query is a SELECT statement nested inside another SQL statement, which contains a reference to
one or more columns in the outer query. That means, it is used to select data from a table referenced in the outer
query
 The correlated sub query is dependent on the outer query for its execution. It cannot be executed independently (if
we try to execute it independently, it gives syntax error)
 A query is called correlated sub query when both the inner query and the outer query are interdependent. For every
row processed by the inner query, the outer query is processed as well.
 Example: In the following SQL statement, there is a parent-child relationship between dept & emp tables (deptno is
the primary key in dept table and foreign key in emp table). Here, the sub query contains a reference to one column
in the outer query (“e.deptno”). Hence, this sub query is a correlated sub query

select * from emp e where e.deptno = (select d.deptno from dept d where d.deptno = e.deptno);

3.3.4.2 Difference between a Sub Query and a Correlated Sub Query:

Sub Query (Normal) Correlated Sub Query


The inner query is executed only once. The inner The outer query will get executed first and for every
query will get executed first and the output of the row of outer query, inner query will get executed. So
inner query used by the outer query the inner query will get executed as many times as
the no. of rows in result of the outer query. The
outer query output can use the inner query output
for comparison.
The inner query is not dependent on outer query. It The inner query and outer query are dependent on
can be executed separately and it returns a result each other. So, it cannot be executed separately
(results in syntax error)
Example: Example:
select * from emp select * from emp e
where sal = where e.deptno =
(select max(sal) from emp); (select d.deptno
from dept d
where d.deptno = e.deptno);

3.4 SQL Joins

 An SQL JOIN clause combines rows from two or more tables. It creates a set of rows in a temporary table
 A JOIN works on two or more tables if they have at least one common field and have a relationship between
them
 JOIN keeps the base tables (structure and data) unchanged
 Broadly, there are two types of SQL JOINS - NON EQUI JOIN and EQUI JOIN

3.4.1 NON EQUI JOIN:

 The SQL NON EQUI JOIN is a join that uses comparison operator other than the equal sign like >, <, >=, <= for the
condition

3.4.2 EQUI JOIN:

 The SQL EQUI JOIN is a simple SQL join uses the equal sign (=) as the comparison operator for the condition. It is of
two types - SQL Inner join and SQL Outer Join

3.4.2.1 SQL Inner Join:

 Inner Join returns all the records satisfying the SQL equi-join condition specified
 Example: Consider below 2 tables EMP and DEPT

DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800

 Query for Inner Join:

select empno,ename,sal,dname from emp inner join dept on emp.deptno = dept.deptno;


(OR)
select empno,ename,sal,dname from emp,dept where emp.deptno = dept.deptno;

 Output:

EMPNO ENAME SAL DNAME


7369 Smith 800 RESEARCH
7499 Allen 1800 SALES
7521 Ward 1800 SALES
7566 Jones 2975 RESEARCH

3.4.2.1.1 SQL Self Join:

 A Self Join is a special type of inner join where in a table is joined to itself (particularly when the table has a foreign
key that references its own primary key)
 In a self join, we must define an alias for both copies of the table to avoid column ambiguity while referring them in
the query
 Example: Assume we want to find all pairs of students residing in the same location from the below table Student.

Student:

ROLLNO NAME COURSE LOCATION


13 ravi mca kphb
34 kavi bsc ameerpet
23 siri mca kphb
47 mahesh bcom kphb
26 suresh bcom ameerpet

 Query for Self Join:

select c1.rollno, c1.name, c2.rollno, c2.name, c1.location


from student c1 inner join student c2 on
c1.location = c2.location
where c1.rollno < c2.rollno
order by c1.rollno, c2.rollno;

 Output:

C1.ROLLNO C1.NAME C2.ROLLNO C2.NAME C1.LOCATION


13 Ravi 23 Siri kphb
13 Ravi 47 Mahesh Kphb
23 Siri 47 Mahesh Kphb
26 Suresh 34 Kavi Ameerpet

3.4.2.2 SQL Outer Join:

 This join returns all rows from both tables which satisfy the join condition along with rows which do not satisfy the
join condition from one of the
 Outer joins are subdivided further into left outer joins, right outer joins and full outer joins depending on which
table’s rows are retained (left, right or both). In this case, left and right refer to the two sides of the JOIN keyword

3.4.2.2.1 Left Outer Join:

 The result of a left outer join (or simply left join) for table A and B always contains all records of the “left” table (A),
even if the join-condition does not find any matching record in the “right” table (B)
 A left outer join returns all the rows from an inner join plus all rows in the left table that do not match to the right
table
 Example : Consider the below 2 tables EMP and DEPT

EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800

DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES
 Query for Left Outer Join:

select * from emp left outer join dept on emp.deptno=dept.deptno;

 Output:

EMPNO ENAME SAL DEPTNO DNAME


7369 Smith 800 20 RESEARCH
7499 Allen 1800 30 SALES
7521 Ward 1800 30 SALES
7566 Jones 2975 20 RESEARCH
7654 Martin 1800
7698 Blake 1800

3.4.2.2.2 Right Outer Join

 The result of a right outer join (or simply right join) for table A and B always contains all records of the “right” table
(B), even if the join-condition does not find any matching record in the “left” table (A)
 A right outer join returns all the rows from an inner join plus all rows in the right table that do not match to the left
table
 Example : Consider the below 2 tables EMP and DEPT

EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800

DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES

 Query for Right Outer Join:

select * from emp right outer join dept on emp.deptno=dept.deptno;

 Output:
EMPNO ENAME SAL DEPTNO DNAME
7369 Smith 800 20 RESEARCH
7499 Allen 1800 30 SALES
7521 Ward 1800 30 SALES
7566 Jones 2975 20 RESEARCH
10 ACCOUNTING

3.4.2.2.3 Full Outer Join

 The result of a full outer join for table A and B combines the effect of applying both left and right outer joins
 A full outer join returns all the rows from an inner join plus all rows in the left table that do not match to the right
table plus all rows in the right table that do not match to the left table
 Example : Consider the below 2 tables EMP and DEPT

EMP
EMPNO ENAME SAL DEPTNO
7369 Smith 800 20
7499 Allen 1800 30
7521 Ward 1800 30
7566 Jones 2975 20
7654 Martin 1800
7698 Blake 1800

DEPT
DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES

 Query for Right Outer Join:

select * from emp full outer join dept on emp.deptno=dept.deptno;

 Output:

EMPNO ENAME SAL DEPTNO DNAME


7369 Smith 800 20 RESEARCH
7499 Allen 1800 30 SALES
7521 Ward 1800 30 SALES
7566 Jones 2975 20 RESEARCH
7654 Martin 1800
7698 Blake 1800
10 ACCOUNTING

3.5 SQL Views

 A view is a predefined SQL statement (query) that is stored in the database with an associated name.
 To reduce redundant data to the minimum possible, RDBMS allows the creation of an object called View.
 An interesting fact about a View is that it is stored only as a definition. It actually does not store the data of their
own (That is why; view is called a virtual table). When a reference is made to a view, its definition is scanned, the
base table is opened and the data related to the constructed view is accessible.
 A view can contain all or selected number of rows from a table.
 Views allow users to do the following:
 Structure data in a way that users (or groups of users) find it convenient
 Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need
and no more
 Summarize data from various tables which can be used to generate reports
 Creating Views: Database views are created using the CREATE VIEW statement. Views can be created from a single
table, multiple tables or another view
 Syntax for Creating a View:

CREATE VIEW view_name AS SELECT column1, column2 ..


FROM table_name WHERE [condition];

 Example: CREATE VIEW emp_view AS SELECT EMPNO,ENAME FROM EMP;

Output:

EMPNO ENAME
7369 Smith
7499 Allen
7521 Ward
7566 Jones
7654 Martin
7698 Blake

 Syntax for Updating a View: The definition of the view created in SQL can be modified by using the following syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2 .. FROM table_name
WHERE [condition];

 Example: CREATE OR REPLACE VIEW emp_view AS SELECT EMPNO,ENAME, SAL FROM EMP;
EMPNO ENAME SAL
7369 Smith 800
7499 Allen 1800
7521 Ward 1800
7566 Jones 2975
7654 Martin 1800
7698 Blake 1800

 Syntax for Dropping a View:

DROP VIEW view_name;

3.6 Sequences

 Sequence is a database object used to automatically generate unique numbers


 Sequences are typically used to create a primary key value
 Syntax for Creating a Sequence:

create sequence sequence_name start with starting_value


increment by step_value maxvalue ending_value;

 Example for Creating a Sequence: The below statement creates a database sequence named SEQ1 that starts with
100, has a step of 1 and can take maximum value as 120

Create sequence SEQ1 start with 100 increment by 2 maxvalue 120;

 Example for Using a DB Sequence: Consider a table PERSON. The following SQL statement inserts a record in it using
the above created sequence

Insert into person values (SEQ1.NEXTVAL, ‘&NAME’, ‘&ADDRESS’);

 Syntax for Modifying a Sequence:

alter sequence sequence_name


increment by step_value
maxvalue ending_value;

 Example for Modifying a Sequence: The below statement modifies the database sequence named SEQ1

alter sequence SEQ1


increment by 3
maxvalue 130;

 Dropping a Sequence: drop sequence sequence_name;


3.7 Indexes and Synonyms

Indexes

 An Index is a database object that can be used to speed up the retrieval of rows
 Indexes are logically and physically independent of the table. It means they can be created or dropped at any time
and will have no effect on the base tables or other indexes
 Automatic Created Indexes: When a primary key or unique key constraint is defined in a table definition then a
unique index is created automatically
 Creating Indexes Manually: User can create non-unique indexes on columns to speed up access time to rows.
 Example for Creating a Single Column Index: Create index emp_ename_idx on emp (ename);
 Example for Creating a Multi Column Index: Create index emp_multi_idx on emp (ename, deptno);
 Finding details about created indexes: The data dictionary contains the name of index, table name and column
names. For example, in Oracle RDBMS, user_ind_columns view contains the details about user created indexes
 Removing an index from the data dictionary: Indexes cannot be modified. They can be dropped as below:
Drop index emp_ename_idx;

Synonyms

 A synonym permits short names or alternative names for database objects


 Syntax for Creating a Synonym: create synonym synonym_name for table_name;
 Example: create synonym e30 for emp30;
 Syntax for Removing a synonym: drop synonym synonym_name;

3.8 SQL Integrity Constraints

 SQL Integrity Constraints are used to apply business rules for the database tables
 Various integrity constraints available in SQL are: Primary Key, Foreign Key, NOT NULL, Unique Key, Check
 Constraints can be defined in two ways:
i) The constraints can be specified immediately after the column definition. This is called column-level
definition
ii) The constraints can be specified after all the columns are defined. This is called table-level definition

 Following are the Integrity Constraints in detail:

1) SQL Primary Key

 This constraint defines a column or combination of columns which uniquely identifies each row in the table

 Syntax to define a primary key at column level: colname datatype (length) primary key

 Example to define a primary key at column level:


Create table student
(
Rollno number(2) primary key,
Name varchar2(20),
Course varchar2(5)
);

 Syntax to define a primary key at table level:

Method1:
primary key (colname1, colname2, ..) where colname1, colname2 are the names of the columns
which define the primary key

Method2: Alter table table_name add primary key (colname);

 Example to define a primary key at table level:

Method1:

Create table student


(
Rollno number(2),
Name varchar2(20),
Course varchar2(5),
primary key (rollno)
);

Method2: Alter table student2 add primary key (rollno);

2) SQL Foreign Key or Referential Integrity

 This constraint identifies any column referencing the primary key in another table
 It establishes a relationship between two columns in the same table or between different tables
 For a column to be defined as a foreign key, it should be defined as a primary key in the table which it is
referring
 Syntax to define a foreign key at column level:
Colname datatype (length) references parent_table_name (primary_key_of_parent_table)
 Example to define a foreign key at column level:
Create table student
(
rollno number (2),
name varchar2(15),
courseno number(2) references course (courseid)
);
 Syntax to define a foreign key at table level:
Foreign key (colname) references parent_table_name (primary_key_of_parent_table)
 Example to define a foreign key at table level:
Create table student
(
rollno number (2),
name varchar2(15),
courseno number(2),
location varchar2(15),
foreign key (courseno) references course (courseid)
);

3) SQL Not Null Constraint

 This constraint ensures all rows in the table contain a definite value for the columns which are specified as
not null (which means a null value is not allowed)
 Syntax to define a Not Null constraint: colname datatype (length) NOT NULL
 Example to define a Not Null constraint: To create a student table with name field mandatory, the Not Null
constraint defined would be like:

Create table student


(
Rollno number(2) primary key,
Name varchar2(15) NOT NULL,
Courseno number(2)
);

4) SQL Unique Key

 This constraint ensures that a column or a group of columns defined as a unique key have a distinct value in
all rows
 Column(s) defined as unique key cannot have duplicate values
 Column(s) defined as unique key can have a null value
 Syntax to define a Unique key at column level: colname datatype (length) UNIQUE
 Example to define a Unique key at column level:

Create table student (


Rollno number(2) primary key,
Name varchar2(15) NOT NULL,
Courseno number(2),
Phno number(10) UNIQUE
);

 Syntax to define a Unique key at table level: UNIQUE (colname)


 Example to define a Unique key at table level:

Create table student (


Rollno number(2) primary key,
Name varchar2(15) NOT NULL,
Phno number(10),
UNIQUE (phno)
);

5) SQL Check Constraint

 This constraint defines a business rule on a column. All the rows must satisfy this rule
 This constraint can be applied for a single column or a group of columns
 Syntax to define a Check constraint at column level:
colname datatype (length) CHECK (condition)
 Example to define a Check constraint at column level:
Create table student
(
Rollno number(2),
Name varchar2(15),
Gender varchar2(1) CHECK (gender in (‘M’,’F’))
);
 Syntax to define a Check constraint at table level:
CHECK (condition)
 Example to define a Check constraint at table level:
Create table student
(
Rollno number(2),
Name varchar2(15),
Gender varchar2(1),
CHECK (gender in (‘M’,’F’))
);

3.9 Oracle Built In Functions

 There are two types of functions in Oracle

1) Group Functions:

 These functions group the rows of data based on the values returned by the query
 The group functions are used to calculate aggregate values like total or average, which return just one value
after processing a group of rows
 Below table lists the Group functions in Oracle:
Group Function Description
MIN(X) gets the minimum value in a set of values in column X
MAX(X) gets the maximum value in a set of values in column X
SUM(X) calculates the sum of values in column X
AVG(X) calculates the average of a set of values in column X
COUNT(X) counts the number of values in column X in a specified table or view
COUNT(*) counts the number of records in a specified table or view

2) Single Row Functions:

 Single row or Scalar functions return a value for every row that is processed in a query
 There are four types of single row functions. They are:

i) Numeric Functions:

 These are the functions that accept numeric inputs, process them and return numeric values
 Few of the numeric functions are tabulated below:

Function Name Description Examples Output


ABS(x) Returns absolute value of the number ‘x’ ABS(-2) 2
ABS(3) 3
CEIL(x) Integer value that is greater than or equal CEIL(2.83) 3
to the number ‘x’ CEIL(2.49) 3
CEIL(-1.6) -1
FLOOR(x) Integer value that is less than or equal to FLOOR(2.83) 2
the number ‘x’ FLOOR(2.49) 2
FLOOR(-1.6) -2
TRUNC(x,y) Truncates the value of number ‘x’ up to ‘y’ TRUNC(140.234, 2) 140.23
decimal values TRUNC(5.7) 5
ROUND(x,y) Rounded off value of the number ‘x’ up to ROUND(125.456, 1) 123.5
the number ‘y’ decimal places ROUND(125.456, 0) 125

ii) Character or Text Functions:

 These are functions that accept character inputs, process them and can return both character as
well as numeric values
 Few of the character functions are tabulated below:

Function Name Description Examples Output


LOWER(string_value) All the letters in ‘string_value’ LOWER(‘Good Morning’) good morning
are converted to lowercase
UPPER(string_value) All the letters in ‘string_value’ UPPER(‘Good Morning’) GOOD
are converted to uppercase MORNING
INITCAP(string_value) All the letters in ‘string_value’ INITCAP(‘GOOD Good Morning
are converted to Title Case MORNING’)
LTRIM(string_value, All occurrences of ‘trim_text’ is LTRIM(‘Good Morning’, Morning
trim_text) removed from the left of ’Good’)
‘string_value’
RTRIM(string_value, All occurrences of ‘trim_text’ is RTRIM(‘Good Morning’, Good
trim_text) removed from the right of ’ Morning’)
‘string_value’
TRIM(trim_text All occurrences of ‘trim_text’ is TRIM(‘*’ from Good
FROM string_value) removed from the left and right ‘**Good*’)
of ‘string_value’. ‘trim_text’ can
be only one character long
SUBSTR(string_value, Returns ‘n’ number of SUBSTR(‘Good Morning’, Morning
m, n) characters from ‘string_value’ 6, 7)
starting from the ‘m’ position

LENGTH(string_value) Number of characters in LENGTH(‘Good Morning’) 12


‘string_value’ is returned
LPAD (string_value, Returns ‘string_value’ left- LPAD (‘Good’, 6, ‘*’) **Good
n, pad_value) padded with ‘pad_value’ in
such a way that the length of
the whole string is ‘n’
characters
RPAD (string_value, Returns ‘string_value’ right- RPAD (‘Good’, 6, ‘*’) Good**
n, pad_value) padded with ‘pad_value’ in
such a way that the length of
the whole string is ‘n’
characters

iii) Date Functions:

 These are functions that take DATE type inputs, process them and return values of DATE type
(except for the MONTHS_BETWEEN function, which returns a number)
 Few of the DATE functions are tabulated below:

Function Name Description Examples Output


ADD_MONTHS Returns a date value after adding ‘n’ ADD_MONTHS (’27- 27-Jun-18
(date, n) months to the date ‘x’ Mar-18’, 3)
MONTHS_BETWEEN Returns the number of months between MONTHS_BETWEEN 4
(x1, x2) dates x1 and x2 (’27-Jul-18’, ’27-
Mar-18’)
NEXT_DAY (x, Returns the next date of the ‘week_day’ NEXT_DAY (’27-Mar- 31-Mar-18
week_day) on or after the date ‘x’ occurs 18’, ‘Saturday’)
LAST_DAY (x) It is used to determine the last date of a LAST_DAY (’27- 31-Mar-18
month from the date ‘x’ specified MAR-18’)
SYSDATE Returns the system’s current date and Select SYSDATE 27-MAR-18
time from dual;

iv) Conversion Functions:

 These are functions that help us to convert a value in one form to another form. For Example: a null
value into an actual value, or a value from one data type to another data type
 Few of the conversion functions available in oracle are tabulated below:

Function Name Description Examples Output


TO_CHAR (x [,y]) Converts Numeric and Date values to a TO_CHAR (SYSDATE, Tuesday,
string value ‘Day, Month YYYY’) March 2018
TO_DATE (x Converts a valid numeric and character TO_DATE('27-Mar- 27-Mar-2018
[,date_format]) values to a Date value. Date is formatted 18', 'DD MON YYYY')
to the format specified by ‘date_format’
NVL (x, y) If ‘x’ is NULL, replace it with ‘y’. ‘x’ and ‘y’ Select NVL(COMM, 1000 (if
must be of the same data type 1000) from EMP; COMM value
is NULL)

***** End of Unit-3 Notes *****

You might also like