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

Unit 2 - Notes DBMS

K

Uploaded by

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

Unit 2 - Notes DBMS

K

Uploaded by

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

The Database Language SQL  Structured query language (SQL) is a programming language for

storing and processing information in a relational database.

Types of Database Languages in DBMS

DDL (Data Definition Language)


 The DDL is used for creating tables, indexes, constraints, and schema in the Database.
 By using DDL statements we can able to create the architecture of the required database.
 Create It is used to create objects in the database
 Alter It is used for change or alter the structure of the database objects
 Drop It is used for delete objects from the database
 Truncate It is used for remove all records from a table
 Rename It is used to rename the object in database
 Comment It is used for comment on the data dictionary.

DCL (Data Control Language) - Used to retrieve the saved data from database.
 Grant It is used for give user access to the database
 Revoke It is used for to take back the access or permissions from the user

DML (Data Manipulation Language) - used to Manipulate the data in the database
 Select It is used for select data from the Table based on the requirements
 Insert It is sued for Inserting data into existing table
 Update It is used for update data in the Table based on the requirement
 Delete It is used for delete data from the Table
 Merge It is used for merge operations
 Call It is used for call a structured query language or Java sub program
 Lock Table It have ability to control the concurrency

TCL (Transaction Control Language) used to run the changes made by the DML commands
 Commit It is used for save the transaction on the Database.
 Rollback It is used for restore the database to original state from last commit.
 Savepoint It is used for go back to the saved state.
Oracle Date Functions
Function Example Result Description
ADD_MONTHS( DATE Add a number of
ADD_MONTHS 31-MAR-16
'2016-02-29', 1 ) months (n)
SELECT CURRENT_DATE 06-AUG-2017 Return the current date
CURRENT_DATE
FROM dual 19:43:44 and time
SELECT 06-AUG-17 Return the current date
CURRENT_TIMESTAMP CURRENT_TIMESTAMP 08.26.52.742000000 and time with time zone
FROM dual PM -07:00
Extract YEAR,
EXTRACT(YEAR FROM
EXTRACT 2017 MONTH, DAY, …
SYSDATE)
from a date time
LAST_DAY(DATE '2016- Gets the last day of the
LAST_DAY 29-FEB-16
02-01') month
SELECT 06-AUG-17 Return
LOCALTIMESTAMP LOCALTIMESTAMP 08.26.52.742000000 a TIMESTAMP value
FROM dual PM
MONTHS_BETWEEN( Return the number of
MONTHS_BETWEEN DATE '2017-07-01', DATE 6 months between two
'2017-01-01' ) dates.
NEXT_DAY( DATE '2000- Get the first weekday
NEXT_DAY 02-JAN-00
01-01', 'SUNDAY' )
Return the current
SYSDATE SYSDATE 01-AUG-17
system date and time
01-AUG-17 Return the system date
SELECT SYSTIMESTAMP
SYSTIMESTAMP 01.33.57.929000000 and time
FROM dual;
PM -07:00
TO_CHAR( DATE'2017-01- Sunday, January 01, Convert a DATE to a
TO_CHAR
01', 'DL' ) 2017 character string
TO_DATE( '01 Jan 2017', Convert character string
TO_DATE 01-JAN-17
'DD MON YYYY' ) to a DATE value.
Oracle String Functions
Function Example Result Purpose
Returns an ASCII code value of a
ASCII ASCII(‘A’) 65
character.
Converts a numeric value to its
CHR CHR(’65’) ‘A’
corresponding ASCII character.
Concatenate two strings and return the
CONCAT CONCAT(‘A’,’BC’) ‘ABC’
combined string.
Converts the first character in each
‘Hi
INITCAP INITCAP(‘hi there’) word in a specified string to uppercase
There’
and the rest to lowercase.
Search for a substring and return the
INSTR INSTR( ‘This is a playlist’, ‘is’) 3 location of the substring in a string
Return the number of characters (or
LENGTH LENGTH(‘ABC’) 3
length) of a specified string
Return a string with all characters
LOWER LOWER(‘Abc’) ‘abc’
converted to lowercase.
Return a string that is left-padded with
LPAD LPAD(‘ABC’,5,’*’) ‘**ABC’ the specified characters to a certain
length.
Remove spaces or other specified
LTRIM LTRIM(‘ ABC ‘) ‘ABC ‘ characters in a set from the left end of a
string.
‘BLACK Replace all occurrences of a substring
REPLACE(‘JACK AND
REPLACE AND by another substring in a string.
JOND’,’J’,’BL’);
BLOND’
Return a string that is right-padded
RPAD RPAD(‘ABC’,5,’*’) ‘ABC**’ with the specified characters to a
certain length.
Remove all spaces or specified
RTRIM RTRIM(‘ ABC ‘) ‘ ABC’ character in a set from the right end of
a string.
SUBSTR SUBSTR(‘Oracle Substring’, 1, 6 ) ‘Oracle’ Extract a substring from a string.
Replace all occurrences of characters
TRANSLATE TRANSLATE(‘12345’, ‘143’, ‘bx’) ‘b2x5’
by other characters in a string.
Remove the space character or other
TRIM TRIM(‘ ABC ‘) ‘ABC’ specified characters either from the
start or end of a string.
Convert all characters in a specified
UPPER UPPER(‘Abc’) ‘ABC’
string to uppercase.
Queries Involving More than One Relation
Multiple relation queries involve the execution of queries that involve multiple tables in a database.
JOIN operations are used to combine related tables into a single result set.

Querying Multiple Tables in SQL:

Method 1: Using SELECT and WHERE


The most common way to query multiple tables is with a simple SELECT expression.
Syntax:
SELECT table1name.column1name, table2name.column2name FROM table1name, table2name
WHERE table1name.column1name = table2name.column1name;

Method 2: Using JOINS


SQL Joins can also be used for the same purpose using the below syntax:
Syntax:
SELECT table1.column1,table1.column2, table2.column1,....
FROM table1 JOIN table2 ON table1.matching_column = table2.matching_column;
Types of Join
There are mainly two types of joins in DBMS:
Inner Joins: Theta, Natural, EQUI
Outer Join: Left, Right, Full

Types of SQL Join


There are different types of joins used in SQL:
 Inner Join / Simple Join
 Left Outer Join / Left Join
 Right Outer Join / Right Join
 Full Outer Join
 Cross Join
 Self Join
Inner Join
The inner join is used to select all matching rows or columns in both tables or as long as the defined
condition is valid in SQL.
Syntax:
Select column_1, column_2, column_3 FROM table_1 INNER JOIN table_2 ON
table_1.column = table_2.column;

Natural Join
It is a type of inner type that joins two or more tables based on the same column name and has the same
data type present on both tables.
Syntax:
Select * from tablename1 Natural JOIN tablename_2;

CROSS JOIN
It is also known as CARTESIAN JOIN, which returns the Cartesian product of two or more joined tables.
The CROSS JOIN produces a table that merges each row from the first table with each second table row.
It is not required to include any condition in CROSS JOIN.
Syntax:
Select * from table_1 cross join table_2;

SELF JOIN
It is a SELF JOIN used to create a table by joining itself as there were two tables. It makes temporary
naming of at least one table in an SQL statement.
Syntax:
Select column1, column2, column(s) FROM table_1 Tbl1, table_2 Tbl2 WHERE condition;

Tbl1 and Tbl2 are two different table aliases for the same table.
Aggregation Operators in DBMS
In a DBMS, aggregation operators are used to perform operations on a group of values to return a single
summarizing value.
The most common aggregation operators include COUNT, SUM, AVG, MIN, and MAX.

Aggregation Operators Syntax Example:


COUNT
COUNT(expression) SELECT COUNT(*) FROM
Returns the number of rows that
Employees;
matches a specified criterion.
SUM
SELECT SUM(salary) FROM
Returns the total sum of a numeric SUM(expression)
Employees;
column.
AVG
SELECT AVG(salary) FROM
Returns the average value of a numeric AVG(expression)
Employees;
column.
MIN
SELECT MIN(salary) FROM
Returns the smallest value of the MIN(expression)
Employees;
selected column.
MAX
SELECT MAX(salary) FROM
Returns the largest value of the selected MAX(expression)
Employees;
column.

GROUP BY & HAVING Clause in SQL


In SQL, the GROUP BY clause categorizes rows with similar values into groups.

The HAVING clause filters groups based on conditions after GROUP BY forms them. It functions like
WHERE but for grouped data.

Here’s the order:


WHERE filters rows first, then GROUP BY categorizes them, and finally, HAVING filters the groups.

The GROUP BY statement is used with SELECT. WHERE goes before GROUP BY, and ORDER BY
goes after.

HAVING is used because WHERE can’t be used with aggregate functions.


Both WHERE and HAVING filter records in SQL queries.

Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes
o Thus, integrity constraint is used to guard against accidental damage to the database.

1. Domain constraints
o Domain constraints can be defined as the definition of a
valid set of values for an attribute.
o 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.

2. Entity integrity constraints


o The entity integrity constraint states that primary key
value can't be null.
o 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.
o A table can contain a null value other than the primary
key field.

3. Referential Integrity Constraints


o A referential integrity constraint is
specified between two tables.
o In the Referential integrity constraints,
if a foreign key in Table 1 refers to the
Primary Key of Table 2, then every
value of the Foreign Key in Table 1
must be null or be available in Table 2.

4. Key constraints
o Keys are the entity set that is used to identify an
entity within its entity set uniquely.
o An entity set can have multiple keys, but out of
which one key will be the primary key. A primary
key can contain a unique and null value in the
relational table.
Triggers
WHAT IS TRIGGER
A trigger is a special kind of stored procedure that is activated ("triggered") in response to a particular event in a
database.
Trigger is called automatically when a data modification event occurs against a table.

3 TYPES OF TRIGGERS

1) DML triggers are automatically fired when an INSERT, UPDATE or DELETE event occurs on a table.
2) DDL triggers are automatically invoked when a CREATE, ALTER, or DROP event occurs in a database.
3) Logon triggers is invoked when a LOGON event is raised when a user session is established.

Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
ON table_name
[FOR EACH ROW]
WHEN (condition)
[trigger_body]

 {BEFORE / AFTER / INSTEAD OF}: Choose when the trigger acts (before, after, or instead of a DML event).
 {INSERT [OR] / UPDATE [OR] / DELETE}: Specify the DML operation (insert, update, delete) that activates the trigger.

Advantages of Triggers

 Triggers in SQL can replace schedulers by immediately checking data changes, eliminating the
need for background scheduler applications.
 They enhance security by enforcing additional checks on sensitive data during insertions,
updates, or deletions, ensuring system integrity.
 Triggers prevent the insertion of invalid data into columns by validating input or performing
corrective actions, such as logging errors or data manipulation.

Disadvantages of Triggers

 Triggers may be difficult to troubleshoot as they execute automatically in the database. If there is
some error then it is hard to find the logic of trigger because they are fired before or after
updates/inserts happen.
 The triggers may increase the overhead of the database as they are executed every time any field
is updated.

CREATE TRIGGER Add_marks


BEFORE INSERT ON Student
FOR EACH ROW SET new.Marks = new.Marks + 100;
SQL Views
Views in SQL are a kind of virtual table. A view also has rows and columns like tables,
But a view doesn’t store data on the disk like a table.

CREATE VIEWS in SQL


We can create a view using CREATE VIEW statement. A View can be created from a single table or multiple
tables.
Syntax
CREATE VIEW view_name AS SELECT col1, col2....FROM table_name WHERE condition;

Example 1: Creating View from a single table


CREATE VIEW view1 AS SELECT NAME, ADDRESS FROM StudentDetails WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM view1;

Example 2: Creating View from multiple tables


CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

DELETE VIEWS in SQL


SQL allows us to delete an existing View. We can delete or drop View using the DROP statement.
Syntax
DROP VIEW view_name;

The SQL Indexes


SQL Indexes are special lookup tables that are used to speed up the process of data retrieval.
SQL Indexes work similar to the index of a book or a journal.

The basic syntax of a CREATE INDEX is as follows −


CREATE INDEX index_name ON table_name;
Types of Indexes
There are various types of indexes that can be created using the CREATE INDEX statement. They are:
 Unique Index
CREATE UNIQUE INDEX index_name on table_name (column_name);
 Single-Column Index
CREATE INDEX index_name ON table_name (column_name);
 Composite Index
CREATE INDEX index_name on table_name (column1, column2);
 Implicit Index
Implicit indexes are indexes that are automatically created by the database server when an
object is created.

The DROP INDEX Statement


DROP INDEX index_name;
SQL Indexes - Types, Uses, Advantages, Disadvantages, and Scenarios
Index Type Use Advantages Disadvantages Ideal Scenarios
Automatically
created with the Fast data retrieval; Additional storage; Unique identifier
Primary
primary key to Ensures data Slower insert/update for each row (e.g.,
Key Index
enforce integrity operations UserID)
uniqueness
Columns requiring
Enforces Prevents duplicate
Slower write unique data but not
Unique uniqueness on a values; Improves
operations; Additional suitable as a
Index column not part of search
storage requirement primary key (e.g.,
the primary key performance
Email)
Determines the Fast data retrieval Only one per table; Columns frequently
Clustered physical storage for range queries; Update operations used in sorting and
Index order of data in the Efficient use of can be slow due to range queries
table disk space reordering (e.g., Dates)
Provides a Faster access than
Increased storage; Frequently
Non- separate structure table scan;
Slower write searched fields not
Clustered from the data rows Multiple non-
operations due to in clustered index
Index and includes a clustered indexes
index updates (e.g., FirstName)
pointer allowed per table
Multi-column
Improves
More complex, searches and
Composite Index on two or performance on
Increased storage; sorting (e.g.,
Index more columns queries involving
Slower writes FirstName,
multiple columns
LastName)
Facilitates
Large text fields
Used for full-text complex queries Takes up significant
Full-Text (e.g., Product
searches in text on text data; storage space;
Index Descriptions,
data Faster than LIKE Specialized use-case
Articles)
searches
Not suitable for Columns with
Efficient for Small storage
frequently changing limited unique
Bitmap columns with a low space; Fast for
data; Performance entries (e.g.,
Index cardinality (few read-intensive
issues with high Gender, Marital
unique values) tasks
cardinality data Status)
Geographical data,
Improves location-based
Spatial For indexing performance for Specific use-case; queries (e.g.,
Index spatial data types queries involving Additional complexity Maps, Regions)
spatial data
Dynamic SQL
Dynamic SQL is a programming technique that could be used to write SQL queries during runtime.
To run a dynamic SQL statement, run the stored procedure mysql as shown below :
EXEC mysql N'SELECT statement';
Use prefix N with the “mysql” to use dynamic SQL as a Unicode string.

What is a cursor in DBMS?


Whenever DML statements are executed, a temporary work area is created in the system memory and it is called
a cursor.
A cursor in DBMS is a programming construct that provides a way to traverse and manipulate records within a
database.
Types of Cursor in DBMS
There are two types of cursor in DBMS: implicit cursor and explicit cursor.

Uses of Cursor in DBMS


Iterating through records: Data filtering: Data manipulation: Data processing: Record locking

What is JDBC?
JDBC stands for Java DataBase Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.

What is a Stored Procedure?


A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.
So if you have an SQL query that you write over and over again, save it as a stored procedure, and then just
call it to execute it.

Stored Procedure Syntax


CREATE PROCEDURE procedure_name AS sql_statement

Execute a Stored Procedure


EXEC procedure_name;

CREATE PROCEDURE SelectAllCustomers AS SELECT * FROM Customers


EXEC SelectAllCustomers;

You might also like