Unit-3
SQL Concepts
Subject: Database Management System
SQL Concepts
• SQL is a standard language for storing,
manipulating and retrieving data in databases.
• Database language can be used to read, store and
update the data in database.
Database Languages
• DDL- Data Definition • DQL- Data Query
Language Language
– Create – Select
– Alter • DCL- Data Control
– Truncate
Language
– Drop
– Grant
– Rename
– Revoke
• DML- Data Manipulation • TCL- Transaction Control
Language Language
– Insert
– Commit
– Update
– Rollback
– Delete
– Savepoint
DDL- Data Definition Language
• It is used to define database structure or pattern.
• It is used to create schema, tables, indexes etc in database.
• Using the DDL statements, you can create the skeleton of the
database.
• Command:
– Create: used to create objects in DB.
– Alter: Used to alter the structure of DB.
– TRUNCATE: is used to remove all records from a table,
including all spaces allocated for the records are removed.
– Drop: used to delete objects from DB.
– Rename: Used to rename the object.
DML- Data Manipulation Language
• It is used for accessing and manipulating data in DB.
• It handles user request.
• Command:
– Insert: Used to insert data into table.
– Update: used to update existing data within table.
– Delete: used to delete records from table.
DQL- Data Query Language
• The purpose of DQL Command is to get some schema
relation based on the query passed to it.
• Command:
– Select: is used to retrieve data from a database.
DCL- Data Control Language
• DCL includes commands mainly deals with the rights,
permissions and other controls of the database system.
• Command:
– Grant-gives user’s access privileges to database.
– Revoke-withdraw user’s access privileges given by
using the Grant command.
TCL- Transaction Control Language
• TCL commands deals with the transaction within the
database.
• Commands:
– Commit– commits a Transaction.
– Rollback– rollbacks a transaction in case of any error
occurs.
– Savepoint–sets a savepoint within a transaction.
Data types
char (size):
• This datatype is used to store character string
value of fixed length.
• The size in brackets determines the number of
characters the cell can hold.
• The maximum number of characters this data type
can hold is 255 characters.
• For Example, Name char(20)
Data types (Cont..)
Varchar (size)/ varchar2 (size):
• This data type is used to store variable length
alpha numeric data.
• It is more flexible.
• The maximum this data type can hold up to 4000
characters.
Data types (Cont..)
Number (P,S):
• The number data type is used to store number
either fixed or floating point.
• Number can be stored up to 38 digits of precision.
• The precision (P) determines the maximum length
of the data, whereas the scale (S) determines the
number of places of right of decimal.
• If scale is not given then default is zero.
• For example, Contact_no number(10)
Data types (Cont..)
Date:
• This data type is used to represent date and time.
• The standard format is “DD-MON-YY” as in ’20-
AUG-20’.
• Date time stores date in the 24-hour format.
• By default, the time in a date field is 12:00:00 am,
if no time portion specified.
DDL commands
• CREATE
• ALTER
• TRUNCATE
• DROP
• RENAME
DDL Command: Create
• Create command defines each column of table uniquely.
• Each column has a minimum of three attributes: name, datatype,
size.
• Each column definition is separated from other by a comma.
• The SQL statement is terminated with semi colon.
• RULES FOR CREATING TABLES:
– A name can have may up to 30 characters
– Alphabets from A-Z, a-z and numbers 0-9 are allowed.
– A name should begin with alphabet
– The use of special character like _ is allowed.
– Reserved words of SQL not allowed.
• Syntax:
– CREATE TABLE tablename (columnname1 datatype(size),
column_name2 datatype(size), ...);
Create table with Primary key
• Syntax:
CREATE TABLE tablename
(columnname1 datatype(size) PRIMARY KEY,
column_name2 datatype(size), ...);
• For Example,
Student ( Student_ID, FName, LName, Address,
Mobile_No)
create table Student (Student_ID number(5) primary
key, FName varchar2(10), LName varchar2(10),
Address varchar2(20), Mobile_No number(10));
CREATE command with foreign key
• Syntax:
CREATE TABLE tablename
(columnname1 REFERENCES table2name (columnname),
column_name2 datatype(size), ...);
• For Example,
Student ( Student_ID, FName, LName, Address, Mobile_No)
Subject(SubjectID, SubjectName, Credits)
Studies(Student_ID, Subject_ID)
CREATE table Studies(Student_ID REFERENCES Student
(Student_ID), Subject_ID REFERENCES
Subject(SubjectID));
DDL command: ALTER
• The ALTER TABLE statement is used to add, delete, or
modify columns in an existing table.
• The ALTER TABLE statement is also used to add and drop
various constraints on an existing table.
• To ADD column in table:
Syntax:
ALTER TABLE table_name ADD ColumnName
datatype(size);
Example:
Add Hobbies column in student table.
Alter table Student ADD Hobbies varchar2(15);
DDL command: ALTER(Cont..)
• To change datatype of column in table:
Syntax:
ALTER TABLE tablename MODIFY ColumnName datatype(size);
Example:
change size of Hobbies to 20.
Alter table Student MODIFY Hobbies varchar2(20);
• To Drop/Delete column from table:
Syntax:
ALTER TABLE tablename DROP COLUMN ColumnName;
Example:
delete the Hobbies column.
Alter table Student DROP COLUMN Hobbies;
DDL command: TRUNCATE
• The TRUNCATE TABLE statement is used to delete the data
inside a table, but not the table itself.
• Syntax:
TRUNCATE TABLE tablename;
• Example:
TRUNCATE table Student;
DDL command: DROP
• The DROP TABLE statement is used to drop an existing
table in a database.
• Syntax:
DROP TABLE tablename;
• Example:
DROP table Student;
DDL command: RENAME
• The rename command is used to change the name of an
existing database object(like Table) to a new name.
• Syntax:
RENAME current_table_name TO new_table_name;
• Example:
RENAME Subject to Subjects;
DML commands
• INSERT
• UPDATE
• DELETE
DML command: INSERT
• It is used for inserting data into tables.
• You can insert records/data into two manners.
1) Insert data into all columns:
Syntax:
INSERT INTO tablename VALUES (value1, value2, …);
Example:
insert into Student (Student_ID, Fname, Lname, Address,
Mobile_no) values (1001, ‘Ali’, ‘Shaikh’, ‘Surat’, 987654321);
DML command: INSERT
2) Insert data into specific columns:
Syntax:
INSERT INTO tablename (columnname1,
columnname2, …) VALUES (value1, value2, …);
Example:
insert into Student (Student_ID, Fname, Lname,
Address, Mobile_no) values (1001, ‘Ali’, ‘Shaikh’, ‘Surat’,
987654321);
DML command: UPDATE
• The UPDATE statement is used to modify the existing records
in a table.
• Update/insert data into whole column:
Syntax:
UPDATE table_name SET column1=value1;
Example:
UPDATE Student SET Hobbies=‘Reading’;
• Update data into specific row:
Syntax:
UPDATE table_name SET column1=value1,.. WHERE condition;
Example:
UPDATE Student SET Hobbies=‘Traveling’ where
Fname=‘Ankit’;
DML command: DELETE
• The DELETE statement is used to delete existing records in
a table.
• Delete all records from table:
Syntax:
DELETE FROM table_name;
Example:
DELETE from Student ;
• Delete specific records from table:
Syntax:
DELETE FROM table_name WHERE condition;
Example:
DELETE from Student where Fname=‘Ankit’;
DQL command: SELECT
• It is used to fetch data from a database.
• To display all data from table:
Syntax:
SELECT * FROM tablename;
Example:
Select * from Student;
• To display specific column from table:
Syntax:
SELECT columnname1, columnname2,… FROM
tablename;
Example:
Select Fname, Lname from Student;
SELECT command with WHERE clause
• It is used to filter records.
• It is used to extract only those records that fulfill a
specified condition.
• Mostly condition is in form of:
Columnname Operator Value
• Syntax:
SELECT columnname1, columnname2,… FROM
tablename WHERE condition;
• Example:
Select Fname, Lname from Student where
Student_Id=1004;
Arithmetic Operators
Operators Description
+ Add
- Subtract
* Multiply
/ Divide
Comparison Operators
Operators Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= Not equal to
Logical operators
Operators Description
AND TRUE if all the conditions separated by AND
is TRUE
OR TRUE if any of the conditions separated by
OR is TRUE
NOT Displays a record if the condition(s) is NOT
TRUE
BETWEEN TRUE if the operand is within the range of
comparison
LIKE TRUE if the operand matches a pattern
IN TRUE if the operand is equal to one of a list
of expression
DESC command
• DESC command use for describe the list of column
definitions for specified table.
• DESC statement to get following information:
– Column Name
– Column allow NULL or NOT NULL
– Datatype of the Column
– With database size precision and If NUMERIC datatype scale.
• Syntax:
DESC tablename;
• Example:
DESC Student;
Distinct in SQL
• The SELECT DISTINCT statement is used to return only
distinct (different) values.
• Syntax:
SELECT DISTINCT(columnname) FROM tablename;
• Example:
Select DISTINCT(Fname) from Student;
Integrity 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
• Domain integrity constraints – Not Null, Check
• Entity integrity constraints – Unique, Primary key
• Referential integrity constraints – Foreign key, On
delete cascade.
Domain integrity constraints
• Domain constraints can be defined as the
definition of a valid set of values for an attribute.
• The data type of domain includes string, character,
integer, time, date, currency, etc.
• The value of the attribute must be available in the
corresponding domain.
• Constraints:
– Not Null
– Check
• Example:
Domain integrity constraint:
NOT NULL
NOT NULL constraint specifies that a column cannot
contain NULL values.
• Add NOT NULL constraint while creating a new
table:
Syntax:
Create table tablename ( ..., column_name
data_type (size) NOT NULL, …);
Example:
create table Stu_Info (ID int, Name varchar2(15),
Semester varchar2(10) NOT NULL, Age
number(3));
NOT NULL (Cont..)
• Add NOT NULL constraint in existing column of
existing table:
Syntax:
Alter table tablename MODIFY column_name NOT
NULL;
Example:
Alter table Stu_Info MODIFY Semester NOT NULL;
NOT NULL (Cont..)
• Add NOT NULL constraint in new column of
existing table:
Syntax:
Alter table tablename ADD column_name
data_type(size) NOT NULL;
Example:
Alter table Stu_Info ADD Semester varchar2(10)
NOT NULL;
Domain Integrity constraints:
CHECK
• A check constraint allows you to specify a
condition on each row in a table.
• Add CHECK constraint while creating a new
table:
Syntax:
Create table tablename ( ..., column_name
data_type(size) CHECK (condition), …);
Example:
Create table Stu_Info (ID int, Name varchar2(15),
Semester varchar2(10), Age number(3) CHECK
(Age>0));
CHECK (Cont..)
• Add CHECK constraint in existing column of
existing table:
Syntax:
Alter table tablename ADD CONSTRAINT
columnname CHECK (condition);
Example:
Alter table Stu_Info ADD CONSTRAINT Age CHECK
(Age>0);
CHECK (Cont..)
• Add CHECK constraint in new column of
existing table:
Syntax:
Alter table tablename ADD columnname
datatype(size) CHECK (condition);
Example:
Alter table Stu_Info ADD Age number(3) CHECK
(Age>0);
Entity integrity constraints
• The entity integrity constraint states that primary
key value can't be null.
• This is because the primary key value is used to
identify individual rows in relation and if the
primary key has a null value, then we can't identify
those rows.
• A table can contain a null value other than the
primary key field.
• Constraints:
– Primary key
– Unique
• Example:
Entity Integrity constraints:
Primary key
• A primary key is a column of a combination of
columns in a table that uniquely identifies a row in
the table.
• The following are rules that make a column a primary
key:
– A primary key column cannot contain a NULL value or
an empty string.
– A primary key value must be unique within the entire
table.
– A primary key value should not be changed over time.
– A table can have only ONE primary key; and in the table,
this primary key can consist of single or multiple
columns (fields).
Primary key
• Add PRIMARY KEY constraint while creating a
new table:
Syntax:
Create table tablename (columnname1 datatype
(size) PRIMARY KEY, column_name2 datatype
(size), ...);
Example:
Create table Stu_Info(ID number(5) PRIMARY KEY,
Name varchar2(15), Semester varchar2(10), Age
number(3));
Primary key (Cont..)
• Add PRIMARY KEY constraint in existing
column of existing table:
Syntax:
Alter table tablename ADD PRIMARY KEY
(columnname);
Example:
Alter table Stu_Info ADD PRIMARY KEY (Id);
Entity Integrity constraint:
Unique
• The UNIQUE constraint ensures that all values in a
column are different.
• Both the UNIQUE and PRIMARY KEY constraints
provide a guarantee for uniqueness for a column
or set of columns.
• A PRIMARY KEY constraint automatically has a
UNIQUE constraint.
• However, you can have many UNIQUE constraints
per table, but only one PRIMARY KEY constraint
per table.
Unique
• Add UNIQUE constraint while creating a new
table:
Syntax:
Create table tablename ( ..., columnname datatype
(size) UNIQUE, …);
Example:
Create table Stu_Info(ID number(5) UNIQUE,
Name varchar2(15), Semester varchar2(10), Age
number(3));
Unique (Cont..)
• Add UNIQUE constraint in existing column of
existing table:
Syntax:
Alter table tablename ADD UNIQUE
(columnname);
Example:
Alter table Stu_Info ADD UNIQUE (ID);
Referential Integrity Constraints
• A referential integrity constraint is specified
between two tables.
• In the Referential integrity constraints, if a foreign
key in Table1 refers to the Primary Key of Table2,
then every value of the Foreign Key in Table1 must
be null or be available in Table2.
• Example:
Referential integrity constraints:
Foreign key
• A FOREIGN KEY is a key used to link two tables together.
• A FOREIGN KEY is a field (or collection of fields) in one
table that refers to the PRIMARY KEY in another table.
• The table containing the foreign key is called the child
table, and the table containing the candidate key is called
the referenced or parent table.
Foreign key
• Add FOREIGN KEY constraint while creating a
new table:
Syntax:
Create table tablename (columnname1
REFERENCES tablename2 (columnname),
columnname2 datatype(size), …);
Example:
Create table Orders (OrderID int primary key,
PersonID REFERENCES Persons(PersonID),
OrderNumber number(4));
Foreign key (Cont..)
• Add FOREIGN KEY constraint in existing
column of existing table:
Syntax:
Alter table tablename ADD FOREIGN KEY
(columnname) REFERENCES parent_table
(columnname);
Example:
Alter table Orders ADD FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID);
Referential Integrity Constraint:
Foreign key with cascade delete
• A foreign key with cascade delete means that if a record in
the parent table is deleted, then the corresponding records in
the child table will automatically be deleted. This is called a
cascade delete.
• Use the ON DELETE clause to specify consequence when the
rows in the parent table are deleted.
❑ON DELETE CASCADE
❑ON DELETE SET NULL
ON DELETE CASCADE
• If a row in the parent is deleted, then all the rows
in the child table that reference the removed row
will be deleted.
• ON DELETE CASCADE Using a create table:
Syntax:
Create table tablename (…, columnname1
REFERENCES table2name (columnname) ON
DELETE CASCADE, ...);
Example:
Create table Orders (OrderID int primary key,
OrderNumber number(4), PersonID REFERENCES
Persons(PersonID) ON DELETE CASCADE);
ON DELETE CASCADE (Cont..)
• ON DELETE CASCADE Using a alter table:
Syntax:
Alter table tablename ADD FOREIGN KEY
(columnname1) REFERENCES parent_table
(columnname) ON DELETE CASCADE;
Example:
Alter table Orders ADD FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID) ON DELETE
CASCADE;
ON DELETE SET NULL
• If a row in the parent is deleted, then all the rows
in the child table that reference the removed row
will be deleted.
• ON DELETE SET NULL Using a create table:
Syntax:
Create table tablename (…, columnname1
REFERENCES table2name (columnname) ON
DELETE SET NULL, ...);
Example:
Create table Orders (OrderID int primary key,
OrderNumber number(4), PersonID REFERENCES
Persons(PersonID) ON DELETE SET NULL);
ON DELETE SET NULL (Cont..)
• ON DELETE SET NULL Using a alter table:
Syntax:
Alter table tablename ADD FOREIGN KEY
(columnname1) REFERENCES parent_table
(columnname) ON DELETE SET NULL;
Example:
Alter table Orders ADD FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID) ON DELETE SET
NULL;
SQL Functions
• Single row functions
– Numeric functions
– String functions
– Date functions
• Aggregate/ Group functions
Single row functions
• Single row functions can be character functions,
numeric functions, date functions, and conversion
functions.
• Note that these functions are used to manipulate
data items.
• These functions require one or more input
arguments and operate on each row, thereby
returning one output value for each row.
• Argument can be a column, literal or an expression.
Single row functions can be used in SELECT
statement, WHERE and ORDER BY clause.
Numeric functions
• ABS()
• CEIL()
• FLOOR()
• GREATEST()
• LEAST()
• MOD()
• POWER()
• ROUND()
• SQRT()
Numeric function: ABS()
• ABS():
It will convert given value in positive number.
Syntax:
ABS(number)
Example:
select ABS(-18) from dual;
Output:
18
Numeric function: CEIL()
• CEIL():
It will returns the smallest integer value that is
bigger than or equal to a number.
Syntax:
CEIL(number)
Example:
select CEIL(17.08) from dual;
Output:
18
Numeric function: FLOOR()
• FLOOR()
It returns the largest integer value that is smaller
than or equal to a number.
Syntax:
FLOOR(number)
Example:
select FLOOR(17.08) from dual;
Output:
17
Numeric function: MOD()
• MOD()
It returns the remainder of a number divided by
another number.
Syntax:
MOD(x, y)
where, x is a value that will be divided by y.
Example:
select MOD(18,4) from dual;
Output:
2
Numeric function: POWER()
• POWER()
It returns the value of a number raised to the
power of another number.
Syntax:
POWER(x, y)
Example:
select POWER(8,3) from dual;
Output:
512
Numeric function: ROUND()
• ROUND()
It rounds a number to a specified number of
decimal places.
Syntax:
ROUND(number, decimals)
Example:
select ROUND(135.375, 2) from dual;
Output:
135.38
Numeric function: SQRT()
• SQRT()
It returns the square root of a number.
Syntax:
SQRT(number)
Example:
select SQRT(13) from dual;
Output:
3.60555127546398929311922126747049594625
Numeric functions: GREATEST()
• GREATEST()
It is used to find greater values from given values.
Syntax:
GREATEST(value 1, value 2, …, value n);
Example,
select greatest(34, 675, 21, 8789, 6745) from dual;
Output: 8789
select greatest(‘D’, ‘a’, ‘t’ ,‘a’, ‘b’, ‘a’, ‘s’, ‘e’) from dual;
Output: t
select greatest('?','@','#','$','.') from dual;
Output: @
Numeric functions: LEAST()
• LEAST()
It is used to find smaller values from given values.
Syntax:
LEAST(value 1, value 2, …, value n);
Example,
select least(34, 675, 21, 8789, 6745) from dual;
Output: 21
select least(‘D’, ‘a’, ‘t’ ,‘a’, ‘b’, ‘a’, ‘s’, ‘e’) from dual;
Output: D
select least('?','@','#','$','.') from dual;
Output: #
String functions
• CONCAT()
• REVERSE()
• LENGTH()
• LOWER()
• UPPER()
• INITCAP()
• LPAD()
• RPAD()
• TRIM()
• TRANSLATE()
String function: CONCAT()
• CONCAT()
It adds two or more strings together.
Syntax:
CONCAT(string1, string2)
Example:
select CONCAT(‘Database’, ‘ Management’)
from dual;
Output:
Database Management
String function: REVERSE()
• REVERSE()
It reverses a string and returns the result.
Syntax:
REVERSE(string)
Example:
select REVERSE(‘Database’) from dual;
Output:
esabataD
String function: LENGTH()
• LENGTH()
It returns the length of a string.
Syntax:
LENGTH(string1)
Example:
select LENGTH(‘Database Management
System’) from dual;
Output:
26
String function: LOWER()
• LOWER()
It converts a string to lower-case.
Syntax:
LOWER(string)
Example:
select LOWER(‘CHARACTER Functions in SQL’)
from dual;
Output:
character functions in sql
String function: UPPER()
• UPPER()
It converts a string to upper-case.
Syntax:
UPPER(string)
Example:
select UPPER(‘Character Functions in SQL’)
from dual;
Output:
CHARACTER FUNCTIONS IN SQL
String function: INITCAP()
• INITCAP()
It will make all the first letters of given words into
capital letter.
Syntax:
INITCAP(string)
Example:
select INITCAP(‘CHARACTER functions in
SQL’) from dual;
Output:
Character Functions In Sql
String function: LPAD()
• LPAD()
The LPAD() function left-pads a string with another string, to a
certain length.
Syntax:
LPAD(string, length, lpad_string)
Parameters:
String: The original string.
length: The length of the string after it has been left-
padded.
lpad_string: The string to left-pad to string.
Example:
SELECT LPAD(‘Diploma’, 20, ‘*@*’) from dual;
Output:
*@**@**@**@**Diploma
String function: RPAD()
• RPAD()
The RPAD() function right-pads a string with another string, to
a certain length.
Syntax:
RPAD(string, length, rpad_string)
Parameters:
String: The original string.
length: The length of the string after it has been right-
padded.
lpad_string: The string to right-pad to string.
Example:
SELECT RPAD(‘Diploma’, 20, ‘*@*’) from dual;
Output:
Diploma*@**@**@**@**
String function: TRIM()
• TRIM()
It is basically used to remove extra spaces from a given string. But by
using trim function we can also remove any character from starting or
ending of a string.
Syntax:
TRIM(LEADING/TRAILING/BOTH ‘char_to_trim’ FROM ‘string’)
where, leading: to trim character from starting
trailing: to trim character from ending
both: to trim character from both side
Example:
select ltrim(‘ hello ') from dual – It will remove left side’s extra spaces.
select TRIM(leading '*' from '***hello***') from dual; Output: hello***
select TRIM(trailing '*' from '***hello***') from dual; Output: ***hello
select TRIM(BOTH '*' from '***hello***') from dual; Output: hello
String function: TRANSLATE()
• TRANSLATE()
It will take three arguments as a parameter. And replace
2nd arguments values with 3rd arguments values in a
string given as 1st argument.
Syntax:
TRANSLATE(string, ‘characters_to_replace’,
‘replacement_characters’)
Example:
select TRANSLATE(‘Computer Engineering’, ‘ei’, ‘@!’)
from dual;
Output:
Comput@r Eng!n@@r!ng
Date Conversion functions
• TO_CHAR()
• TO_DATE()
• LAST_DAY()
• MONTHS_BETWEEN()
• SYSDATE
Conversion function: TO_CHAR()
• TO_CHAR() function converts a DATE or number in a specified
string format.
• Syntax:
TO_CHAR(expr, string_format);
• Arguments:
1) expr
The expr is a DATE or an INTERVAL value that should be
converted.
2) string_format
The string_format is a string that determines the format that the
result string should be in.
The string_format argument is optional.
Example of to_char() with number
• Select TO_CHAR(1210.73, '9999.9') from dual;
Result: ' 1210.7'
• Select TO_CHAR(1210.73, '9,999.99') from dual;
Result: ' 1,210.73'
• Select TO_CHAR(1210.73, '$9,999.99') from dual;
Result: ' $1,210.73'
• Select TO_CHAR(21, '000099') from dual;
Result: ' 000021‘
Example of to_char() with Date
• Select TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Result: '2020/09/05'
• Select TO_CHAR(sysdate, 'Month DD, YYYY') from dual;
Result: ‘September 05, 2020’
• Select TO_CHAR(sysdate, 'FMMonth DD, YYYY') from dual;
Result: ' September 5, 2020’
• Select TO_CHAR(sysdate, 'MON DDth, YYYY') from dual;
Result: ‘SEP 05TH, 2020’
• Select TO_CHAR(sysdate, 'FMMON DDth, YYYY') from dual;
Result: ‘SEP 5TH, 2020’
• Select TO_CHAR(sysdate, 'FMMon ddth, YYYY') from dual;
Result: ‘Sep 5th, 2020’
Conversion function: To_date()
• TO_DATE function converts a string to a date.
• Syntax:
TO_DATE( string1 [, format_mask])
• Arguments:
- String1
The string that will be converted to a date.
- format_mask
Optional.
This is the format that will be used to convert string1 to a
date.
Example of To_date()
• SELECT TO_DATE('2020/09/05', 'yyyy/mm/dd') from
dual;
Result: 09/05/2020
• SELECT TO_DATE('090712', ‘YYDDMM') from dual;
Result: 12/07/2009
• SELECT TO_DATE('09072020', 'mmddyyyy') from dual;
Result: 09/07/2020
Date function: LAST_DAY()
• The LAST_DAY() function extracts the last day of the month
for a given date.
• Syntax:
LAST_DAY(date)
• Argument:
date: It is required. The date to extract the last day
of the month from.
• Example,
SELECT LAST_DAY(‘02/12/2020’) from dual;
Output: 02/29/2020
SELECT LAST_DAY(SYSDATE) from dual;
Output: 09/30/2020
Date function: Months_between()
• The MONTHS_BETWEEN() function is used to get the
number of months between dates (date1, date2).
• Syntax:
MONTHS_BETWEEN(date1,date2)
• See the following conditions:
– If date1 is later than date2, then the result is positive.
– If date1 is earlier than date2, then the result is negative.
– If date1 and date2 are either the same days of the month or both
last days of months, then the result is always an integer.
– Otherwise, Oracle Database calculates the fractional portion of the
result based on a 31-day month and considers the difference in
time components date1 and date2.
Example of months_between()
• select months_between('09/07/2020','08/07/2020') from
dual;
Result: 1
• select months_between('09/07/2020',‘10/07/2020') from
dual;
Result: -1
• select months_between(’09/30/2020',’08/31/2020') from
dual;
Result: 1
Date function: SYSDATE
• SYSDATE function returns the current date and time of the
Operating System (OS) where the Oracle Database
installed.
• Syntax:
SYSDATE
• Example:
select SYSDATE from dual;
Output:
09/26/2020
Aggregate/ Group functions
• Group functions are built-in SQL functions that
operate on groups of rows and return one value for the
entire group.
• The group functions are as follow:
– AVG()
– SUM()
– MIN()
– MAX()
– COUNT()
– COUNT(*)
– DISTINCT()
Group function: AVG()
• AVG()
It is used to find average of a given column’s
values.
Syntax:
select AVG(column_name) from tablename;
Example:
select AVG(Credits) from Subject;
Output:
24.2
Group function: SUM()
• SUM()
It is used to perform summation operation on
given column’s values.
Syntax:
select SUM(column_name) from tablename;
Example:
select SUM(Credits) from Subject;
Output:
121
Group function: MIN()
• MIN()
It is used to find minimum number from given
column’s values.
Syntax:
select MIN(column_name) from tablename;
Example:
select MIN(Credits) from Subject;
Output: 23
Group function: MAX()
• MAX()
It is used to find maximum number from given
column’s values.
Syntax:
select MAX(column_name) from tablename;
Example:
select MAX(Credits) from Subject;
Output: 25
Group function: COUNT()
• COUNT()
It is used to count total number of rows in given
column.
Syntax:
select COUNT(column_name) from tablename;
Example:
select COUNT(Credits) from Subject;
Output:
5
Group function: COUNT(*)
• COUNT(*)
It will count total number of rows in a given table.
Syntax:
select COUNT(*) from tablename;
Example:
select COUNT(*) from Subject;
Output:
5
Group function: DISTINCT()
• DISTINCT()
It is used to display unique values from given
column.
Syntax:
select DISTINCT(column_name) from
tablename;
Example:
Display unique name of all students.
select DISTINCT(Fname) from Student;
How many unique names are in Student table?
select COUNT(DISTINCT(Fname)) from
Student;
Join
• A SQL Join statement is used to combine data or
rows from two or more tables based on a common
field between them.
• Different types of Joins are:
– INNER JOIN
– OUTER JOIN
Inner join
• The INNER JOIN selects all rows from both the tables as
long as the condition satisfies.
• This keyword will create the result-set by combining all
rows from both the tables where the condition satisfies i.e
value of the common field will be same.
• They are also referred to as an EQUI JOIN.
Inner join (Cont..)
• Syntax:
SELECT table1.column1, table1.column2, table2.column1,...
FROM table1
INNER JOIN table2
ON
table1.matching_column= table2.matching_column;
Example
Student Student_Course
Schema:
Student (Roll_no, Name, Address)
Student_Course (Course_Id, Roll_no)
Example (Cont..)
SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student INNER JOIN StudentCourse ON
Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:
Outer joins
• In the SQL outer JOIN all the content of the both
tables are integrated together either they are
matched or not.
• Outer join is used for missing information those
are not returned in inner join.
• There are three types of Outer join:
– Left join
– Right join
– Full join
Left outer join
• This join returns all the rows of the table on the left side of
the join and matching rows for the table on the right side of
join.
• If there is no matching in the right table then it returns
NULL values.
• LEFT JOIN is also known as LEFT OUTER JOIN.
Left join (Cont…)
• Syntax:
SELECT table1.column1, table1.column2, table2.column1,...
FROM
table1 LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
• Example:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Left join (Cont…)
• Output:
Right join
• This join returns all the rows of the table on the right side
of the join and matching rows for the table on the left side
of join.
• If there is no matching in the left table then it returns NULL
values.
• RIGHT JOIN is also known as RIGHT OUTER JOIN.
Right join (Cont..)
• Syntax:
SELECT table1.column1, table1.column2, table2.column1,...
FROM
table1 RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
• Example:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Right join (Cont..)
• Output:
Full join
• FULL JOIN creates the result-set by combining result of
both LEFT JOIN and RIGHT JOIN.
• If there is no matching in either left table or right table
then it returns NULL values.
• RIGHT JOIN is also known as RIGHT OUTER JOIN.
Full join (Cont..)
• Syntax:
SELECT table1.column1, table1.column2, table2.column1,...
FROM
table1 FULL JOIN table2
ON table1.matching_column = table2.matching_column;
• Example:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Full join (Cont..)
• Output:
Self join
• The SQL SELF JOIN is used to join a table to itself as if the table were
two tables; temporarily renaming at least one table in the SQL
statement.
• Syntax:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;
• Example: Employees(ID, Name, Salary, ManagerId)
Id FullName Salary ManagerId
1 John Smith 10000 3
2 Jane Anderson 12000 3
3 Tom Lanon 15000 4
4 Anne Connor 20000
5 Jeremy York 9000 1
Self join (cont..)
SELECT employee.Id, employee.FullName,
employee.ManagerId, manager.FullName as ManagerName
FROM Employees employee JOIN Employees manager ON
employee.ManagerId = manager.Id;
Output:
Id FullName ManagerId ManagerName
1 John Smith 3 Tom Lanon
2 Jane Anderson 3 Tom Lanon
3 Tom Lanon 4 Anne Connor
5 Jeremy York 1 John Smith
Sub-queries
• Subquery can be simply defined as a query within another
query.
• Important rules for Subqueries:
– Subqueries can be used with SELECT statements along
with expression operator. It could be equality operator or
comparison operator such as =, >=, <= and Like operator.
– A subquery is a query within another query. The outer
query is called as main query and inner query is called
as subquery.
– The subquery generally executes first, and its output is
used to complete the query condition for the main or
outer query.
– Subquery must be enclosed in parentheses.
– Subqueries are on the right side of the comparison
operator.
Sub-queries (Cont..)
• Syntax:
SELECT column1name, column2name,…
FROM table1name
WHERE column_name OPERATOR
(SELECT column1name, column2name FROM
table1name WHERE condition);
Sub-queries (Cont..)
Example:
SELECT COURSE_ID, NAME, AGE FROM Student
where ROLL_NO IN (Select ROLL_NO from StudentCourse);
Output:
Operators
• IN
• NOT IN
• ANY
• ALL
• EXISTS
IN Operator
• The IN operator allows you to specify multiple
values in a WHERE clause.
• The IN operator is a shorthand for multiple OR
conditions.
• Syntax:
SELECT column_name(s) FROM tablename
WHERE column_name IN (value1, value2, ...);
or
SELECT column_name(s) FROM tablename
WHERE column_name IN (SELECT STATEMENT);
ANY Operator
• The ANY operator is used with a WHERE or
HAVING clause.
• The ANY operator returns true if any of the
subquery values meet the condition.
• Syntax:
SELECT column_name(s) FROM tablename
WHERE column_name operator ANY
(SELECT column_name FROM tablename WHERE
condition);
ALL Operator
• The ALL operator are used with a WHERE or
HAVING clause.
• The ALL operator returns true if all of the
subquery values meet the condition.
• Syntax:
SELECT column_name(s) FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE
condition);
EXISTS Operator
• The EXISTS operator is used to test for the
existence of any record in a subquery.
• The EXISTS operator returns true if the sub query
returns one or more records.
• Syntax:
SELECT column_name(s) FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE
condition);
Group by clause
• The GROUP BY statement groups rows that have the same
values into summary rows.
• The GROUP BY statement is often used with aggregate
functions (COUNT, MAX, MIN, SUM, AVG) to group the
result-set by one or more columns.
• Syntax:
SELECT column_name(s) FROM table_name WHERE
condition GROUP BY column_name(s);
Example:
List the total number of students who belongs to same city.
select address, count(Student_ID) from student group
by address;
Having clause
• The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions.
• Syntax:
SELECT column_name(s) FROM table_name WHERE
condition GROUP BY column_name(s) HAVING condition;
• Example:
List out total number of students who are studying more
than 1 subject.
select count(student_id),subject_id from studies group by
subject_id having count(student_id)>1;
Example
Emp_no Name Salary Age
1 A 10000 21
2 B 12000 23
3 C 8000 20
4 D 15000 20
5 E 10000 21
Display number of employees who are in same age group.
Select Age, count(Name) from Employee group by Age;
Display number of employees who are in same age group and having
count more than 1.
Select Age, count(Emp_no) from Employee group by Age Having
count(Emp_no)>1;
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.
• To arrange in ascending order (Syntax):
SELECT column1, column2, ... FROM table_name
ORDER BY column1;
• To arrange in descending order (Syntax):
SELECT column1, column2, ... FROM table_name
ORDER BY column1 DESC;
Set Operations
Set Operations
• Set operators combine the results of two component
queries into a single result. Queries containing set
operators are called compound queries.
• Following are the Set operators in SQL:
– UNION: All distinct rows selected by either query
– UNION ALL: All rows selected by either query, including
all duplicates
– INTERSECT: All distinct rows selected by both queries
– MINUS: All distinct rows selected by the first query but
not the second
Union
• Union operation in SQL is same operation as
performed for sets.
• For ex:
Set 1 ‘A’ contains values 1, 2, 3 and set 2 ‘B’
contains values 2, 3, 4 then union of these two sets
will be as per below:
A = {1,2,3}
B = {2,3,4}
A U B = {1,2,3,4}
• It eliminates duplicate values and get all the values
from set 1 and all the values from set 2.
Union (cont..)
• In SQL, union operation will take values of selected
column of first table and values of selected column
from second table and merge values of both the
tables and eliminate duplicate values.
• Syntax:
select column1, column2, … , columnN from
table1
UNION
select column1, column2, … , columnN from
table2
Rules to perform union operation
• For union operation number of columns in both
the tables should be same, and sequence of
columns should be maintained.
• Datatype of columns of both the tables, that is
column1 in table1 and column1 in table2 should
be same.
Example Tables
Student
Student_id Name Mobile Number City Email ID
1 Samir 99988 Surat [email protected]
2 Ali 99998 Bardoli [email protected]
3 Karan 99989 Surat [email protected]
4 Harsh 88889 Valsad [email protected]
Student_marks Subject
Student_id Subject_id Marks Subject_ Subject_name Credits
1 101 90 id
1 102 97 101 DBMS 25
1 103 95 102 JAVA 25
2 101 70 103 DFS 23
2 103 78 104 JAVA 24
3 101 60 105 FCP 21
Union (cont..)
• Example:
For given table let us merge name from student
table and subject table that is,
Output:
Name
select name from student Ali
UNION DBMS
DFS
select subject_name from subject FCP
Harsh
JAVA
Karan
Samir
Intersection
• Intersection operation in SQL is same operation as
performed for sets.
• For ex:
Set 1 ‘A’ contains values 1, 2, 3 and set 2 ‘B’
contains values 2, 3, 4 than Intersect of these two
sets will be as per below:
A = {1,2,3}
B = {2,3,4}
A ꓵ B = {2,3}
• It eliminates duplicate values and get all the
common values from set 1 and set 2.
Intersection (cont..)
• In SQL, Intersection operation will take common
values of selected column of first table and
selected column from second table and generate
answer after eliminating duplicate values.
• Syntax:
select column1, column2, … , columnN from
table1
INTERSECT
select column1, column2, … , columnN from
table2
Rules for Intersection operation
• For Intersect operation number of columns in both
the tables should be same, and sequence of
columns should be maintained.
• Datatypes of values should be same for columns in
both the tables that means column1 of table1
should contain same datatype like column1 of
table2.
Example Tables
Student
Student_id Name Mobile Number City Email ID
1 Samir 99988 Surat
[email protected]2 Ali 99998 Bardoli
[email protected]3 Karan 99989 Surat
[email protected]4 Harsh 88889 Valsad
[email protected] Instructor
Instructor_id Instructor_name Date of Joining
F001 Sarah 01-12-2006
F002 Aamir 01-07-2009
F003 Archana 01-08-2010
F004 Harsh 02-07-2002
F005 Samir 05-06-2008
Intersect (cont..)
• Example:
For given table find out name that is common in
student as well as in instructor table,
select name from student
INTERSECT
select instructor_name from instructor
Output:
Name
Harsh
Samir
Set Minus
• Set Minus operation in SQL is same operation as
performed for sets.
• For ex:
Set 1 ‘A’ contains values 1, 2, 3 and set 2 ‘B’
contains values 2, 3, 4 than Set Minus of these two
sets will be as per below:
A = {1,2,3}
B = {2,3,4}
A - B = {1}
• It eliminates duplicate values and get all the values
which is there in set 1 but not in set 2.
Set Minus (cont..)
• In SQL, Set Minus operation will fetch unique
values from table1 which is not there in table2.
• Syntax:
select column1, column2, … , columnN from
table1
MINUS
select column1, column2, … , columnN from
table2
Rules for set minus operation
• For Set Minus operation number of columns in
both the tables should be same, and sequence of
columns should be maintained.
• Datatypes of values should be same for columns in
both the tables that means column1 of table1
should contain same datatype like column1 of
table2.
Example Tables
Student
Student_id Name Mobile Number City Email ID
1 Samir 99988 Surat
[email protected]2 Ali 99998 Bardoli
[email protected]3 Karan 99989 Surat
[email protected]4 Harsh 88889 Valsad
[email protected] Instructor
Instructor_id Instructor_name Date of Joining
F001 Sarah 01-12-2006
F002 Aamir 01-07-2009
F003 Archana 01-08-2010
F004 Harsh 02-07-2002
F005 Samir 05-06-2008
Set Minus
• Example:
For given table find out name who is available in
student but not in instructor,
select name from student
MINUS
select instructor_name from instructor
• Output:
Name
Ali
Karan
Practice questions
• Consider following tables and perform SQL
queries:
State(state_id, state_name)
City(city_id, state_id, city_name, latitude,
longitude)
Weather(city_id, month, temp_f, rain_percentage)
Queries for above schema
1. Display all the values of city with their temperature value.
2. Display state name with it’s city name.
3. List all the city name who is having temperature greater than
80 Fahrenheit in month ‘January’.
4. Give city names in which rain percentage is between 50 to 70.
5. Display city name with state name in which rain chances is
more than 60% in the month of ‘August’.
6. Display all details of cities for state ‘Gujarat’.
7. Display city name with it’s temperature and rain chances
month wise.
8. List all the cities with lower temperature value to higher
temperature value.
9. Give state names in which rain percentage is less than 30%.
10. Display city name, latitude, longitude for all cities in which
temperature is more than 80 Fahrenheit in all the months of
winter(November - February).
CASE statement
• The CASE statement goes through conditions and
returns a value when the first condition is met (like an
IF-THEN-ELSE statement).
• So, once a condition is true, it will stop reading and
return the result. If no conditions are true, it returns
the value in the ELSE clause.
• If there is no ELSE part and no conditions are true, it
returns NULL.
• Types:
– Value match (Simple) CASE expression: Compares
single value and run statement accordingly.
– Searched CASE expression: Evaluates Boolean
expression and run statement accordingly.
Value match (Simple) CASE
expression
• Syntax:
SELECT [<column_names>,]
CASE <column_name>
WHEN <value> THEN ‘statement’
END [AS <alias_name>]
FROM <table_name>;
Example
• Display eid, ename and department name ‘Sales’ whose
D_id =1.
select EID, ENAME, CASE D_ID
WHEN 1 THEN 'Sales’ END AS Dname
from employee1;
Searched CASE expression
• Syntax: (Simple If)
SELECT [<column_names>,]
CASE WHEN <expression> THEN ‘statement’
END [AS <alias_name>]
FROM <table_name>;
• Example: Display the salary with salary level.
select ename, salary,
CASE WHEN salary <= 3000 THEN 'Low'
END AS "Salary Level"
from employee1;
Searched CASE expression
• Syntax: (Simple If-Else)
SELECT [<column_names>,]
CASE WHEN <expression> THEN ‘statement’
ELSE ‘statement’
END [AS <alias_name>]
FROM <table_name>;
• Example:
select ename, salary,
CASE WHEN salary <= 3000 THEN 'Low'
else 'Unknown'
END AS "Salary Level"
from employee1;
Searched CASE expression
• Syntax: (If-Else Ladder)
SELECT [<column_names>,]
CASE WHEN <expression> THEN ‘statement’
WHEN <expression> THEN ‘statement’
ELSE ‘statement’
END [AS <alias_name>]
FROM <table_name>;
Searched CASE expression
• Example:
select ename, salary,
CASE WHEN salary <= 3000 THEN 'Low'
WHEN salary > =3000 and salary <6000 THEN 'Medium'
WHEN salary >=6000 and salary <=7000 THEN 'High'
else 'Unknown'
END AS "Salary Level"
from employee1;
Searched CASE expression
• Syntax: (Nested If-Else)
SELECT [<column_names>,]
CASE WHEN <expression> THEN
CASE WHEN <expression> THEN ‘stmt’
ELSE ‘stmt’
END
ELSE ‘stmt’
END [AS <alias_name>]
FROM <table_name>;
Introduction to View
• View is the logical table created from existing one
or more tables.
• View is virtual table and it is not presented
physically in memory.
• The need of View:
– Data security
– Reduction of data redundancy
• View can queried exactly as table.
Types
View
Read-Only View Updateable View
View Defined from View Defined from
single table multiple table with
referencing clause
View Defined from
multiple table
without
referencing clause
Types (cont…)
• Read-Only View: If a View is used to only look at
table data then view is known as read-only view.
• Updateable View: If a View is used to look at table
data as well as insert, update and delete data then
view is known as updateable view.
Creating View
• Syntax:
CREATE VIEW <view_name> AS
SELECT <column_names> FROM <table_name>
WHERE <condition>
GROUP BY <criteria>
HAVING <predicates>
• To give alias to columns of view:
CREATE VIEW <view_name> AS
SELECT <column_names> “<Alias_name>” FROM
<table_name>
WHERE <condition>
GROUP BY <criteria>
HAVING <predicates>
Example
• Consider following tables:
– Movie (mid, name, length, type, release_date)
– Stars (sid, name, fees, dob)
– Director (did, name, no_of_films)
– Movie_master (mmid, mid, sid, did, budget,
collection)
• Create view movie_details having field mid,
name and type.
create view movie_details as select mid, name, type
from movie;
Retrieving Data from View
• Syntax:
SELECT <column_name> FROM <view_name>
WHERE <condition>
• Example:
select * from movie_details;
Updateable View
• When data manipulation is done on updateable view,
modification in the view will be immediately passed to
the underlying table.
• Rules for applying data manipulation on view
defined using single table:
– If the user wants to insert records with the help of a
view, then the primary key column and all NOT
NULL columns must be included in view.
– User can update and delete records with the help of
a view even if the primary key column and all NOT
NULL columns are excluded from the view
definition and base table will be modified
accordingly.
Example
• insert into movie_details values (3, 'Barfi', 'Motivational');
• select * from movie;
• Here, length and release_date field of movie table is
allowing null. So record can be inserted properly.
• update movie_details set type='Inspirational' where
mid=3;
• delete from movie_details where mid=3;
Continue…
• Rules for applying data manipulation on view
defined using multiple table which have no
referencing clause:
– Insert, update or delete operation is not allowed.
• Example: create view Film_industry which has the
attributes mid, sid, movie name and stars name.
create view Film_industry as select
mid,sid,movie.name,stars.name "Star name" from
movie,stars;
• When insert, update or delete operation is performed
on this view:
Continue…
• Rules for applying data manipulation on view
defined using multiple table which have referencing
clause:
– Insert operation is not allowed.
– Delete operation do not affect the master table but it affects
the detail table.
– Update operation can be performed on only one table when
multiple tables are joined.
• Example:
Create view Movie_view with the field name, budget,
collection.
create view movie_view as select name, budget, collection
from movie_master, movie where
movie.mid=movie_master.mid;
Continue…
• Insert:
• Update: update movie_view set collection=100000 where
name='3 Idiots‘;
– It is done on single table so it works properly.
• Update: update movie_view set name='Barfi' where
collection=990000;
– It requires both tables so it does not work.
• Delete: delete from movie_view where name='3 Idiots';
– Data is deleted from movie_master but not from movie.
Common Restriction on Updateable View
• View definition must not include:
– Aggregate functions
– DISTINCT, GROUP BY or HAVING clause
– Sub-queries
– Constant, Strings or value expression
– Set operations
– If a view is defined from another view, the second
view should be updateable.
Destroying A View
• Syntax:
DROP VIEW <view_name>;
drop view movie_view;