UNIT - 2.DBMS-2-218

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 217

What is Relational Model?

• Relational Model was proposed by E.F. Codd.


• Relational Model represents how data is stored
in Relational Databases.
• A relational database stores data in the form of
relations or tables.
Some popular Relational Database management
systems are:
• DB2 and Informix Dynamic Server - IBM
• Oracle and RDB – Oracle
• SQL Server and Access - Microsoft
Relational Model Concepts
• Attribute: Each column in a Table. Attributes are the
characteristics which define a relation. e.g.,
Student_Rollno, NAME,etc.
• Tables – In the Relational model, the relations are saved in
the table format. It is stored along with its entities. A table
has two properties rows and columns. Rows represent
records and columns represent attributes.
• Tuple – It is nothing but a single row of a table, which
contains a single record.
• Relation Schema: A relation schema represents the name
of the relation with its attributes.
• Degree: The total number of attributes which in the
relation is called the degree of the relation.
• Cardinality: Total number of rows present in the Table.
• Column: The column represents the set of values for a
specific attribute.
• Relation instance – Relation instance is a finite set of
tuples in the RDBMS system. Relation instances never
have duplicate tuples.
• Relation key - Every row has one, two or multiple
attributes, which is called relation key.
• Attribute domain – Every attribute has some pre-
defined value
• NULL Values: The value which is not known or
unavailable is called NULL value.
Properties of Relations

• Name of the relation is distinct from all other


relations.
• Each relation cell contains exactly one atomic
(single) value
• Each attribute contains a distinct name
• Attribute domain has no significance
• tuple has no duplicate value
• Order of tuple can have a different sequence
Relational Integrity Constraints or
Constraints in Relational Model
• While designing Relational Model, we can set
some conditions to store the data in the
specific format or range in database is called
Constraints.
• These constraints are checked before
performing any operation (insertion, deletion
and updation) in database.
• If there is a violation in any of constraints,
operation will fail.
1. Domain Constraints
• These are attribute level constraints.
• An attribute can only take values between the
domain range.
• Example: If a constraints AGE>0 is applied on
STUDENT relation, inserting negative value of
AGE will result in failure.
2. Key Integrity
• Every relation in the database should have at least one
set of attributes which defines a tuple uniquely.
• Those set of attributes is called key attribute or
primary key.
• Example: ROLL_NO in STUDENT is a key. No two
students can have same roll number.
So, a key has two properties:
• It should be unique for all tuples.
• It can’t have NULL values.
3. Referential Integrity
• When one attribute of a relation can only take values
from other attribute of same relation or any other
relation, it is called referential integrity.
• Referential Integrity constraints in DBMS are based
on the concept of Foreign Keys.
• Let us suppose we have 2 relations
• BRANCH_CODE of STUDENT can only take the values
which are present in BRANCH_CODE of BRANCH
which is called referential integrity constraint.
• The relation which is referencing to other relation is
called REFERENCING RELATION (STUDENT in this
case) and the relation to which other relations refer
is called REFERENCED RELATION (BRANCH in this
case).
Foreign Key Example:1
Foreign Key Example:2
Relational Model Operations
• Four basic update operations performed on
relational database model are Insert, update,
delete and select.
• Insert is used to insert data into the relation
• Delete is used to delete tuples from the table.
• Modify allows you to change the values of
some attributes in existing tuples.
• Select allows you to choose a specific range of
data.
Insert Operation

• The insert operation is used to insert new


tuple into a relation.
Update Operation
• You can see that in the below-given relation
table CustomerName= 'Apple' is updated from
Inactive to Active.
Delete Operation

• It is used to remove one or more tuple in a


relation.
Select Operation
• Select operation is used to display the
particular tuple value based on the user input.
• In the above-given example,
CustomerName="Amazon" is selected
Best Practices for creating a
Relational Model
• Data need to be represented as a collection of
relations
• Each relation should be depicted clearly in the table
• Rows should contain data about instances of an entity
• Columns must contain data about attributes of the
entity
• Cells of the table should hold a single value
• Each column should be given a unique name
• No two rows can be identical
• The values of an attribute should be from the same
domain
Advantages of using Relational Model
• Simplicity: A Relational data model in DBMS is simpler than the
hierarchical and network model.
• Structural Independence: The relational database is only concerned
with data and not with a structure. This can improve the
performance of the model.
• Easy to use: The Relational model in DBMS is easy as tables
consisting of rows and columns are quite natural and simple to
understand
• Query capability: It makes possible for a high-level query language
like SQL to avoid complex database navigation.
• Data independence: The Structure of Relational database can be
changed without having to change any application.
• Scalable: Regarding a number of records, or rows, and the number
of fields, a database should be enlarged to enhance its usability.
Disadvantages of using Relational
Model
• Few relational databases have limits on field lengths
which can't be exceeded.
• Relational databases can sometimes become
complex as the amount of data grows, and the
relations between pieces of data become more
complicated.
• Complex relational database systems may lead to
isolated databases where the information cannot be
shared from one system to another.
Relational Algebra
• Relational algebra is a procedural query
language.
• It provides a step by step process to obtain
the result of the query.
• It uses operators to perform queries.
• It is procedural language and very useful for
representing the query execution plan.
• Relational algebra mainly provides theoretical
foundation for relational databases and SQL.
Types of Relational operation
1. Projection (π)
• Projection is used to select the particular
columns of data from a relation.
• Syntax:
2. Selection (σ)
• Selection is used to select the required tuples of data
from a relation.
• Syntax:
3. Rename (ρ)
• Rename operation allows renaming a certain
output relation
• Query :Rename the Member relation as
LibraryMemebr.
4. Union (⋃)

• For the union of two relations, both the


relations must have the same set of attributes.
• Syntax: table_name1 ∪ table_name2
5. Intersection Operator (∩)

• For the intersection of two relations, both the


relations must have the same set of attributes.
• It is used to select common rows (tuples)
from two tables (relations).
• Syntax:
table_name1 ∩ table_name2
6. Set Difference (-)
• Lets say we have two relations R1 and R2 and
we want to select all those tuples(rows) that
are present in Relation R1 but not present in
Relation R2, this can be done using Set
difference R1 – R2.
• Example: A={1,2,3} B={3} A-B={1,2}
• Syntax: table_name1 - table_name2
• Query:

Output:
7. Cartesian product (X)
• Lets say we have two relations R1 and R2 then the
Cartesian product of these two relations (R1 X R2)
would combine each tuple of first relation R1 with
the each tuple of second relation R2.
• Syntax : R1 X R2
• Query: R XS
• Output:
8. Natural join (⋈)
• Natural join between two or more relations will
result in all the combination of tuples where they
have equal values for the common attribute.

Query: Member ⋈ Borrow


DDL with constraints
The following constraints are
commonly used in SQL:
• NOT NULL - Ensures that a column cannot
have a NULL value.
• UNIQUE - Ensures that all values in a column
are different.
• PRIMARY KEY - A combination of a NOT NULL
and UNIQUE. ...
• FOREIGN KEY - Uniquely identifies a
row/record in another table.
• Check - Ensures that all values in a column
satisfies a specific condition
• Default- Sets a default value for a column
when no value is specified
• index- Used to create and retrieve data from
the database very quickly
Not Null
• Ensures that a column cannot have a NULL
value.
• Example:
create table student (regno int not null, name
varchar(50) not null);
• Sample output:
Unique
• Ensures that all values in a column are
different.
• Example:
create table student (regno int unique,name
varchar(50) not null);
PRIMARY KEY
• The PRIMARY KEY constraint uniquely identifies each
record in a table.
• Primary keys must contain UNIQUE values, and
cannot contain NULL values.
• Example:
create table student( regno int primary key, name
varchar2(50));
How to add primary key in the existing
table

• Example: now we are going add primary key


as regno in the existing table student.
• Syntax:
alter table table_name add constraint
constraint_name primary key( column_name);
• Example:
alter table student add cosntraint pk primary key
(regno);
Remove the primary key in the existing
table
• Syntax:
alter table table_name drop constraint constraint_name;
• Example:
alter table student drop constraint pk;
FOREIGN KEY
• A FOREIGN KEY is a key used to link two tables
together.
• A FOREIGN KEY is a field or attribute in one
table that refers to the PRIMARY KEY in
another table.
Person table:
create table person (personid not null primary
key, lastname varchar(50) not null, firstname
varchar(50) not null, age int not null);
• Order table creation:
Create order (
orderid int not null primary key,
orderNumber int not null,
personid int ,
foreign key(personid) references person (personid)
);
CHECK Constraint
• The check constraint is used to limit the value
range in a column value

• Example:
create table persons (
id int not null,
lastname varchar(255) not null,
firstname varchar(255),
age int check (age>=18)
);
DEFAULT Constraint
• The DEFAULT constraint is used to provide a
default value for a column.

• Example:
create table orders (
id int not null,
ordernumber int not null,
orderdate date default getdate()
);
AUTO INCREMENT
• Auto-increment allows a unique number to be generated
automatically when a new record is inserted into a table.
• Example:
create table persons (
personid int ,
lastname varchar(255) not null,
firstname varchar(255),
age int
);
Create sequence seq_name min value 1 start with 1
increment by 1 cache 10;
Then we can insert the values into tables
>> insert into persons(personid,lastname, firstname,age)
values (seq_name.nextval, ‘cccc’,’ssss’,22);
3. DML Commands

Prepared by
Dr.S.Sankar
AP/CSE
Sona College of Technology
DML
• A data manipulation language (DML) is a
computer programming language used for
adding (inserting), deleting, and modifying
(updating) data in a database.
Example student table
INSERT command
• Insert command is used to insert data into a
table.
• Syntax:
Insert into table_name values(col1 value,col2
value, ...);
• Example:
Insert into student values(1,’aakash’, 100);
Insert value into only specific columns

• Syntax:
Insert into student (col1_name, col3_name)
values (col1_value, col3_value);
• Example:
insert into student (name) values(‘abishek’);
Insert NULL value to a column

• Syntax:
Insert into student values( col1_value,null);
• Example:
Insert into student values(3,’Akshara’, null);
UPDATE command
• UPDATE command is used to update any
record of data in a table.
• WHERE is used to add a condition to any SQL
query
• Syntax:
update table_name SET column_name =
new_value WHERE some_condition;
• Example:
Update student set mark=100 where regno=2;
Updating Multiple Columns
• UPDATE statement is used to update the
values of multiple columns.
• Table: Student

• Example:
Update student set name=‘aiswarya’,mark=100
where regno=3;
DELETE command

• DELETE command is used to delete data from


a table.
Delete a particular Record from a Table

• Syntax:
delete from table_name where column_name=col_value;
• Example:
delete from student where regno=3;
Delete all Records from a Table
• Delete command is used to remove all the
records from the table.
• Syntax:
delete from table_name;
• Example:
delete from student;
Example table: Student
Select Query
• SELECT query is used to retrieve data from a
table.
Select all records from a table
• Syntax:
Select * from table_name;
• Example:
Select * from student;
Select a particular record based on a
condition
• We can use the where clause to set a
condition
• Syntax:
Select * from table_name where col_name=col_val;
• Example:
Select * from student where regno=1;
Operators for WHERE clause condition
SQL LIKE clause
• LIKE clause compares data with an expression
using wildcard operators to match pattern
given in the condition.
Wildcard operators
• There are two wildcard operators that are
used in LIKE clause.
• Percent sign %: represents zero, one or more
than one character.
• Underscore sign _: represents only a single
character.
Sample table
Display the name first letter starts
with ‘a’
• Syntax:
Select * from table_name where col_name like
‘a%’;
• Example:
Select * from student where name like ‘a%’;
Like clause Using _ and %
• Eample:
select * from student where name like ‘_a%’;
• The above query will return all records
from Student table where s_name contain 'd'
as second character.
Using % only
In a table, attribute value starts with any
character.
Example:
select * FROM Student where name like '%i';
Student table where name contain ‘i' as last
character.
ORDER BY Clause
• Order by clause is used with SELECT statement
for arranging retrieved data in sorted order.
• To sort the data in descending order DESC.
• Syntax:
Select *from table_name order by column_name;
• Example:
select * from emp order by salary;

set lines 300


set trimout on
set tab off
Output
Displaying name in the descending
order
Group By Clause
• Group by clause is used to group the results of
a SELECT query based on one or more
columns.
• It is used to group the rows that have the
same values. It will display only one record in
each group.
• Syntax:
Select col1,col3 from table_name group by
salary;
SELECT name, age FROM Emp GROUP BY salary
HAVING Clause
• The HAVING clause is used in SQL because the WHERE
keyword could not be used with aggregate functions.

• Example
SELECT * FROM sale GROUP BY customer HAVING
sum(previous_balance) > 3000
DISTINCT keyword

• The distinct keyword is used with SELECT statement


to retrieve unique values from the table.
• Syntax:
select distinct column-name from table-name;
• Example:
SELECT DISTINCT salary FROM Emp;

• Output:
AND operator
• AND operator is used to set multiple
conditions with the WHERE clause,
alongwith, SELECT, UPDATE or DELETE SQL
queries.
• Example:
Select * from emp where salary < 10000 and age > 25;
• Output:
Example:
1. To display all the tuple from the database
table.
2. Order by salary
3. Group by salary
Join Queries in SQL

Prepared by
Dr.S.Sankar
AP/CSE
Sona College of Technology
SQL Join statement
• A SQL Join statement is used to combine rows
from two or more tables based on a common
field between them. Different types of Joins
are:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
1. INNER JOIN
• The INNER JOIN keyword 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.
• We can also write JOIN instead of INNER JOIN.
JOIN is same as INNER JOIN.

• Syntax:
SELECT
table1.column1,table1.column2,table2.column1,....
FROM table1 INNER JOIN table2 ON
table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
• Example:
SELECT StudentCourse.COURSE_ID,
Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse ON
Student.ROLL_NO = StudentCourse.ROLL_NO;
• Output:
2. LEFT 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.
• The rows for which there is no matching row
on right side, the result-set will contain null.
• LEFT JOIN is also known as LEFT OUTER JOIN.
Example
• Syntax:
SELECT
table1.column1,table1.column2,table2.column1,....
FROM table1 LEFT JOIN table2 ON
table1.matching_column =
table2.matching_column;

table1: First table. table2: Second table


matching_column: Column common to both the
tables.
• Example:
SELECT
Student.NAME,StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
• Output:
3. RIGHT JOIN
• RIGHT JOIN is similar to LEFT 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.
• The rows for which there is no matching row
on left side, the result-set will contain null.
• RIGHT JOIN is also known as RIGHT OUTER
JOIN.
• Syntax:
SELECT
table1.column1,table1.column2,table2.column1,.... FROM
table1 RIGHT JOIN table2 ON table1.matching_column =
table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Example
• Example:
SELECT
Student.NAME,StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
• Output:
FULL JOIN
• FULL JOIN creates the result-set by combining
result of both LEFT JOIN and RIGHT JOIN.
• The result-set will contain all the rows from
both the tables.
• The rows for which there is no matching, the
result-set will contain NULL values.
• Syntax:
SELECT
table1.column1,table1.column2,table2.column1,.... FROM
table1 FULL JOIN table2 ON table1.matching_column =
table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Example
• Example:
SELECT
Student.NAME,StudentCourse.COURSE_ID
FROM Student FULL JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
• Output:
SQL – Assertion
CS 4750
Database Systems

Fall 2020 – University of Virginia © Praphamontripong 1


Assertions
• Assertions = conditions that the database must always satisfy

• Domain constraints and referential-integrity constraints are


specific forms of assertions

• CHECK – verify the assertion on one-table, one-attribute

• ASSERTION – verify one or more tables, one or more attributes

Some constraints cannot be expressed by using only domain


constraints or referential-integrity constraints; for example,
• “Every department must have at least five courses offered every
semester” – must be expressed as an assertion

Note:
• Although ASSERTION is in the SQL standard, most DBMS does not
support it. Therefore, CHECK and TRIGGERS are commonly used as
work around approaches.
Fall 2020 – University of Virginia © Praphamontripong 2
How Do Assertions Work?
• CREATE ASSERTION <assertion-name>
• CHECK <predicate>;

• DROP ASSERTION <assertion-name>

CREATE ASSERTION …

no The requested yes


modification to db violates
the assertion?

Allow the modification Not allow the


to the db modification to the db

Fall 2020 – University of Virginia © Praphamontripong 3


Example (1)
For each tuple in the student relation, the value of the attribute
tot_cred must equal the sum of credits of courses that the
student has completed successfully.

CREATE ASSERTION credits_earned_constraint


CHECK (NOT EXISTS
(SELECT ID
FROM student
WHERE tot_cred <> (SELECT SUM(credits)
FROM takes
NATURAL JOIN course
WHERE student.ID=takes.ID
AND grade IS NOT NULL
AND grade <> ’F’ ) ) )

Fall 2020 – University of Virginia © Praphamontripong 4


Example (2)
The total length of all movies by a given studio shall not exceed
10,000 minutes

CREATE ASSERTION sumLength


CHECK (10000 >= ALL
(SELECT SUM(length)
FROM Movies
GROUP BY studioName ) )

Since this constraint involves only the relation Movies, it can be


expressed as a tuple-based CHECK constraint

CHECK (10000 >= ALL


(SELECT SUM(length)
FROM Movies
GROUP BY studioName ) )

Fall 2020 – University of Virginia © Praphamontripong 5


Comparison of Constraints
Type of Where declared When activated Guaranteed
constraint to hold?
Attributed- With attribute On insertion to No if
based CHECK relation or attribute subqueries
update
Tuple-based Element of relation On insertion to No if
CHECK schema relation or tuple subqueries
update
ASSERTION Element of On any change to Yes
database scheme any mentioned
relation

Fall 2020 – University of Virginia © Praphamontripong 6


Database security and
Authorization:
Prepared by
Dr.S.Sankar
AP/CSE
Sona College of Technology
Security issues in Databases
1. Deployment Failures (Before testing the DB
launches)
2. Broken databases (buffer-overflow vulnerability,
SQL Slammer worm )
3. Data leaks (administrators should use SSL- or
TLS-encrypted communication platforms)
4. Stolen database backups
5. The abuse of database features (hacker can gain
access through legitimate credentials before forcing
the service to run arbitrary code. )
6. A lack of segregation (separation of administrator and
user powers)
7. Hopscotch (find a weakness in the database
infrastructure that can be then leveraged to launch a
series of more serious attacks until they have access to
the back end database.)
8. SQL injections (possible to execute
malicious SQL statements)
9. Suboptimal key management (keys are stored within
company disk drives in many organizations. Database
administrators may do so under the false belief that keys
much be stored on disk in case of database failures. This
isn’t true, and leaving such keys unprotected on disk can
leave you vulnerable to attacks.)
10. Database inconsistencies
• Database developers and system
administrators should have a consistent way
of ensuring the safety of their databases
• using automation and documentation for
tracking and to make changes that will keep
enterprise information safe.
grant/revoke privileges
ANOOP.T
• Introduction
• Attack Intent
• Real World Examples
• How SQL Injection works?
• Video
• Impact of SQL injection
• Types of attacks
• Hack a website
• Defence Against SQL Injection
• Other Injection Types
• SQL Injection tools
• Conclusion
• SQL injection is a code injection technique,
used to attack data-driven applications, in
which malicious SQLstatements are inserted
into an entry field for execution
• This is a method to attack web applications
that have a data repository.
• The attacker would send a specially
crafted SQL statement that is designed to
cause some malicious action.
• Determining database schema
• Extracting data
• Adding or modifying data
• Bypassing authentication
• On August 17, 2009, the United States Justice
Department charged an American citizen
Albert Gonzalez and two Russians with the
theft of 130 million credit card numbers using
an SQL injection attack.
• In 2008 a sweep of attacks began exploiting
the SQL injection vulnerabilities of Microsoft's
IIS web server and SQL database server. Over
500,000 sites were exploited.
• The ability to inject SQL commands into the
database engine through an existing
application
• SQL injection is the use of publicly available
fields to gain entry to your database.
• This is done by entering SQL commands into
your form fields instead of the expected data.
• Improperly coded forms will allow a hacker to
use them as an entry point to your database
1. App sends form to user. Attacker
Form
2. Attacker submits form with SQL
exploit data. User
3. Application builds string with ‘ or 1=1--
exploit data. Pass
4. Application sends SQL query to
DB.
5. DB executes query, including
exploit, sends data back to Firewall
application.
6. Application returns data to user.

DB Server
Web Server
$link = mysql_connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD) or
die ("Couldn't connect: " . mysql_error());
mysql_select_db($DB_DATABASE);
$query = "select count(*) from users where username = '$username' and
password = '$password‘ ";
$result = mysql_query($query);
Unauthorized Access Attempt:
password = ’ or 1=1 --
SQL statement becomes:
select count(*) from users where username = ‘user’
and password = ‘’ or 1=1 --
Checks if password is empty OR 1=1, which is always
true, permitting access.
Database Modification Attack:
password = foo’; delete from table users
where username like ‘%
DB executes two SQL statements:
select count(*) from users where username = ‘user’ and password
= ‘foo’
delete from table users where username like ‘%’
1. Leakage of sensitive
information.
2. Reputation decline.
3. Modification of sensitive
information.
4. Loss of control of db server.
5. Data loss.
6. Denial of service.
1. First order attacks
• The attacker can simply enter a malicious
string and cause the modified code to be
executed immediately
2. Second order attacks
• The attacker injects into a persistent storage
(such as a table row) which is deemed as a
trusted source. An attack is subsequently
executed by another activity.
1. Lateral Injection
3. Lateral Injection
The attacker can manipulate the implicit
function To_Char() by changing the values of the
environment
• Injection through user input
First order
• Injection through cookies injection
• Injection through server variables
• Shell injection.
• Websites require constant access to the
database.
• Firewalls provide little or no defense against
SQL injection attacks.
• Your website is public and firewalls must be
set to allow every site visitor access to your
database, usually over port 80/443.
• Antivirus programs are equally ineffective at
blocking SQL injection attacks.
1. Comprehensive data sanitization
• Web sites must filter all user input
• For example, e-mail addresses should be
filtered to allow only the characters allowed in
an e-mail address.
• Its SQL injection defenses can catch most
attempts to sneak SQL through web channels.
2. Use a web application firewall
• A popular example is the free, open source
module ModSecurity.
• ModSecurity provides a sophisticated and
ever-evolving set of rules to filter potentially
dangerous web requests.
3. Limit database privileges by context
• Create multiple database user accounts with
the minimum levels of privilege for their usage
environment.
• For example, the code behind a login page
should query the database using an account
limited only to the relevent credentials table.
• This way, a breach through this channel
cannot be leveraged to compromise the entire
database.
4. Avoid constructing SQL queries with user
input
• Even data sanitization routines can be flawed.
• Using SQL variable binding with prepared
statements or stored procedures is much safer
than constructing full queries.
• Shell injection.
• Scripting language injection.
• File inclusion.
• XML injection.
• XPath injection.
• LDAP injection.
• SMTP injection.
• BSQL Hacker
• SQLmap
• SQLninja
• Safe3 SQL Injector
• SQLSus
• Mole
• Havij
• SQL injection is technique for exploiting
applications that use relational databases as
their back end.
• Applications compose SQL statements and
send to database.
• SQL injection use the fact that many of these
applications concatenate the fixed part of SQL
statement with user-supplied data that forms
WHERE predicates or additional sub-queries.
• The technique is based on malformed user-
supplied data
• Transform the innocent SQL calls to a malicious
call
• Cause unauthorized access, deletion of data, or
theft of information
• All databases can be a target of SQL injection and
all are vulnerable to this technique.
• The vulnerability is in the application layer
outside of the database, and the moment that
the application has a connection into the
database.
• www.google.com
• www.youtube.com
• www.slideshare.net
• www.beyondsecurity.com
• www.wikipedia.org
• www.breakthesecurity.cysecurity.org
• http://www.esecurityplanet.com/
• http://resources.infosecinstitute.com/best-free-and-open-source-sql-
injection-tools/
Triggers in SQL
Prepared by
Dr.S.Sankar
AP/CSE
Sona College of Technology
Trigger
• Triggers are the SQL statements that are executed
automatically when there is any change in the
database.
• For example, a trigger can be invoked when a row
is inserted into a specified table or when certain
table columns are being updated.
(or)
• A trigger is a database object that is associated
with the table, it will be activated when some
events occur.
Triggers are written to be executed in response
to any of the following events.
• A database manipulation (DML) statement
(DELETE, INSERT, or UPDATE).
• A database definition (DDL) statement
(CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON,
LOGOFF, STARTUP, or SHUTDOWN).
Advantages of Triggers
These are the following advantages of Triggers:
• It cannot consume any memory space.
• It executes automatically according to the
event.
• It can directly link with the database table and
perform any changes.
• It can use a DML statement.
• The trigger can be executed when we run the
following statements:
• INSERT
• UPDATE
• DELETE
• Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
On [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
• create trigger [trigger_name]: Creates or replaces an
existing trigger with the trigger_name.
• [before | after]: This specifies when the trigger will be
executed.
• {insert | update | delete}: This specifies the DML operation.
• on [table_name]: This specifies the name of the table
associated with the trigger.
• [for each row]: This specifies a row-level trigger, i.e., the
trigger will be executed for each row being affected.
• [trigger_body]: This provides the operation to be
performed as trigger is fired
Example
• Create trigger tri
after insert
on student
for each row
begin
dbms_output.put_line(‘one row inserted’);
end;
/
Include this command before creating
trigger
> Set serveroutput on
Condition based Trigger Execution
• Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
On [table_name]
[for each row]
when (condition)
Declare
Begin
End
Dynamic SQL

Prepared by
Dr.S.Sankar
AP/CSE
Sona College of Technology
What is Dynamic SQL?

• Dynamic SQL is a programming technique


that enables you to build SQL statements
dynamically at runtime.
• It helps us to manage big industrial
applications
• We can use stored procedures to create
dynamic queries which can run when we
desire.
• For Dynamic SQL, we use the exec keyword.
• When we use static SQL it is not altered from
one execution to others, but in the case of
dynamic SQL, we can alter the query in each
execution.
Why static SQL is better than Dynamic
SQL
• If a query compiles successfully it implies that
the syntax is correct.
• If a query compiles successfully it verifies that
all the permissions and validations are correct.
• As all the data is pre-known in static SQL the
overhead charges are reduced considerably.
Why do we need Dynamic SQL?
• When we need to run dynamic queries on our
database, mainly DML queries.
• When we need to access an object which is
not in existence during the compile time.
• Whenever we need to optimize the run time
of our queries.
How to use Dynamic SQL?

• Syntax:
Static SQL
• Static SQL refers to those SQL statements
which are fixed and can be hard coded into
the application.
• As static sqls are fixed queries, these
statements can be analysed and optimized
and do not require any specific handling for
security purpose.
Dynamic SQL
• Dynamic SQL refers to those SQL statements
which are generated dynamically based on
user's input and run in the application.
• Dynamic Sqls helps to develop general and
flexible applications.
• Dynamic SQL may need more permissions and
security handling and a malicious user can
create dangerous code as well.
Ex:No.3 Query the database using
simple and complex queries
Prepared by
Dr.S.Sankar
AP/CSE
Sona College of Technology
Employee table
1. Get all employee details from the employee
table
1. Get all employee details from the employee
table
Select * from employee;
2. Get First_Name,Last_Name from employee
table
2. Get First_Name,Last_Name from employee
table

Select first_name, Last_Name from employee ;


3. Get First_Name from employee table using
alias name “Employee_Name”
3. Get First_Name from employee table using
alias name “Employee_Name”

Select first_name as Employee_Name from


employee ;
4. Get First_Name from employee table in
upper case

Select upper(FIRST_NAME) from EMPLOYEE;


5. Get First_Name from employee table in
lower case
5. Get First_Name from employee table in
lower case

Select lower(FIRST_NAME) from EMPLOYEE;


6. Get unique DEPARTMENT from employee
table
6. Get unique DEPARTMENT from employee
table

select distinct DEPARTMENT from EMPLOYEE;


7.Select first 3 characters of FIRST_NAME from
EMPLOYEE
7.Select first 3 characters of FIRST_NAME from
EMPLOYEE
select substr(FIRST_NAME,0,3) from employee;
8. Get all employee details from the employee
table order by First_Name Ascending
8. Get all employee details from the employee
table order by First_Name Ascending

Select * from employee order by FIRST_NAME


asc;
9. Get all employee details from the employee
table order by First_Name descending
9. Get all employee details from the employee
table order by First_Name descending

Select * from employee order by FIRST_NAME


desc;
10. Get all employee details from the employee
table order by First_Name Ascending
10. Get all employee details from the employee
table order by First_Name Ascending

Select * from employee order by FIRST_NAME


asc;
11. Get employee details from employee table
whose employee name is “John”
11. Get employee details from employee table
whose employee name is “John”

Select * from EMPLOYEE where


first_name='John‘;
12. Get employee details from employee table
whose employee name are “John” and “Roy”
12. Get employee details from employee table
whose employee name are “John” and “Roy”

Select * from EMPLOYEE where FIRST_NAME in


('John','Roy');
13. Get employee details from employee table
whose employee name are not “John” and
“Roy”
13. Get employee details from employee table
whose employee name are not “John” and
“Roy”

Select * from EMPLOYEE where FIRST_NAME


not in ('John','Roy');
14. Get employee details from employee table
whose first name starts with 'J‘
14. Get employee details from employee table
whose first name starts with 'J‘

Select * from EMPLOYEE where FIRST_NAME


like 'J%‘;
15. Get employee details from employee table
whose first name contains 'o‘
15. Get employee details from employee table
whose first name contains 'o‘;

Select * from EMPLOYEE where FIRST_NAME


like '%o%'
16. Get employee details from employee table
whose first name ends with 'n'
16. Get employee details from employee table
whose first name ends with 'n‘

Select * from EMPLOYEE where FIRST_NAME


like '%n‘;
17. Get employee details from employee table
whose first name ends with 'n' and name
contains 4 letters
17. Get employee details from employee table
whose first name ends with 'n' and name
contains 4 letters

Select * from EMPLOYEE where FIRST_NAME


like '___n' (Underscores);
18. Get employee details from employee table
whose Salary greater than 600000
18. Get employee details from employee table
whose Salary greater than 600000

Select * from EMPLOYEE where Salary >600000;


19. Get employee details from employee table
whose Salary between 500000 and 800000
19. Get employee details from employee table
whose Salary between 500000 and 800000

Select * from EMPLOYEE where Salary between


500000 and 800000;
20. Get employee details from employee table
whose joining year is “2013”
20. Get employee details from employee table
whose joining year is “2013”

Select * from EMPLOYEE where


to_char(joining_date,'YYYY')='2013‘;
21. Get employee details from employee table
whose joining month is “January”
21. Get employee details from employee table
whose joining month is “January”

Select * from EMPLOYEE where


to_char(joining_date,'MM')='01' ;
22. Get Joining Date from employee table
22. Get Joining Date from employee table

select to_char(JOINING_DATE,'dd/mm/yyyy
hh:mi:ss') from EMPLOYEE;

You might also like