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

SOUTH POINT INSTITUTE OF TECHNOLOGY

& MANAGEMENT

Database Management Systems


( DBMS )

Submitted By: Submitted To:


Vichitar Kumar Mrs. Jyoti Sharma
22021001919
B.tech 3rd Year CSE
Table of Program

Sign
S.No Name of Program Date
Of
Facult
y
1. To study Data Definition language

2. To implementation on DML, TCL and DRL

3. To implement Nested Queries & Join Queries

4. To implement Views.

5. To implement Index

6 To study various Date handling functions and their usage.

7.
To Study String Handling Functions with Usage.

8. Case study of oracle 11g with emphasis on RECOVERY


Techniques, Concurrency and Transaction Management.
PRACTICAL:-1
AIM: - 1 To study Data Definition language.

DDL or Data Definition Language actually consists


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

Examples of DDL commands:

 CREATE – iss used to create the database or its objects (like table,index,
function, views, store procedure and triggers).

 DROP – is used to delete objects from the database.

 ALTER- is used to alter the structure of the database.

 TRUNCATE– is used to remove all records from a table, including all spaces
allocated for the records are removed.

 COMMENT – is used to add comments to the data dictionary.

 RENAME – is used to rename an object existing in the database.

AIM: - 1.1 Create, alter, drop, truncate

CREATE: - create is a DDL SQL command used to create a table or a database in relational
database management system.

Example:-

Output:-
 ALTER:- alter command is used for altering the table structure, such as, to add a column
to existing table. to rename any existing column. to change datatype of any column or to
modify its size.

Example:-

Output:-
DROP:- The SQL DROP command is used to remove an object from the database. If you drop a
table, all the rows in the table is deleted and the ta
table
ble structure is removed from the database.
Once a table is dropped we cannot get it back, so be careful while using DROP command.

Example:-

Output:-

TURNCATE:- TRUNCATE TABLE removes all rows from a table, but the table structure and its
columns, constraints, indexes, and so on remain. To remove the table definition in addition to its
data, use the DROP TABLE statement.

Example:-

Output:-
AIM:-1.2.
1.2. To implement Constraints.
SQL constraints are used to specify
pecify rules for the data in a table. Constraints are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data action, the aaction
ction is aborted.

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. Uniquely identifies each row in a table

 FOREIGN KEY - Uniquely identifies a row/record


ro in anothertable

 CHECK - Ensures that all values in a column satisfies a specific condition ∙

 DEFAULT - Sets a default value for a column when no value isspecified ∙ INDEX - Used to create and retrieve
data from the database very quickly

AIM:-1.2.1.
2.1. (a). Primary key, (b).Foreign Key, (c). Check, (d). Unique, (e). Null, (f). Not null
, (g) . Default, (h). Enable Constraints, (i). Disable Constraints (j). Drop Constraints

(a)Primary Key:- The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys
must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary
key; and in the table, this primary key can consist of single or multiple columns (fields).
Example:-

Output:-
(b) Foreign Key:- A FOREIGN KEY is a key used to link two tables together. A
FOREIGNKEYisafield(orcollectionoffields)inonetablethatreferstothe PRIMARY
KEY in another table............. The FOREIGN KEY constraint is used to prevent
actions that would destroy links between tables.

Example:-

Output:-

CREATE TABLE Orders statement and want to see if the "Orders" table is present, run the
above query in your SQLite environment. If the table has been successfully created, you sshould
hould see it in the result.

(c) Check:-The CHECK constraint is used to limit the value range that can be placed in
a column. If you define a CHECK constraint on a single column it allows only certain
values for this column. If you define a CHECK constraint
constraint on a table it can limit the
values in certain columns based on values in other columns in the row.

Examples:-
Output:-

(d) Unique:-A unique key is a set of one or more than one fields/columns of a table that uniquely
identify a record in a database
tabase table. You can say that it is little like primary key but it can accept
only one null value and it cannot have duplicate values.

Example:-

Output:-

(e) Null:-The SQL NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very
important to understand that a NULL value is different than a zero value or a field that contains
spaces.

Example:-
Output:-

(f) Not null:- A NOT NULL constraint in SQL is used to prevent inserting NULL values intothe
specifiedcolumn, consideringitasanotacceptedvalueforthatcolumn.Thismeans that you should
provide a valid SQL NOT NULL value to that column in the INSERT or UPDATE statements,
statement asthe
column will always contain data
Example:-

Output:-
(g) Default:- The DEFAULT constraint is used to provide a default value for a column. The
default value will be added to all new records IF no other value isspecified.

Example:-

Output:-

(h) Enable Constraints:- If a constraint is enabled, data is checked as it is entered or updated in


the database, and data that does not conform to the constraint is prevented from being entered. If
a constraint is disabled, then data that does no
nott conform can be allowed to enter the database.

Example:-

(i) Disable Constrains:- You can use the ALTER TABLE statement to enable, disable, modify, or
drop a constraint. When the database is using a UNIQUE or PRIMARY KEY index to enforce a
constraint,
int, and constraints associated with that index are dropped or disabled, the index is dropped,
unless you specify otherwise.

Example:-
(j)Drop Constraints:- The DROP CONSTRAINT command is used to delete a UNIQUE, PRIMARY KEY,
FOREIGN KEY, or CHECK constraint.
onstraint.

1. DROP a UNIQUE Constraint. To drop a UNIQUE constraint, use the following SQL: ...

2. DROP a PRIMARY KEY Constraint. To drop a PRIMARY KEY constraint, use the following
SQL: ...
3. DROP a FOREIGN KEY Constraint. ...
4. DROP a CHECK Constraint.

Example:-

Output:-
PRACTICAL:-2

AIM:-2. To implementation on DML, TCL and DRL

DML:- A data manipulation language (DML) is a computer programming language used for adding
(inserting), deleting, and modifying (upda
(updating)
ting) data in a database............................ A popular data
manipulation language is that of Structured Query Language (SQL), which is used to retrieve and
manipulate data in a relational database.

 SELECT - retrieve data from a database


 INSERT - insert data into a table
 UPDATE - updates existing data within a table
 DELETE - Delete all records from a database table
 MERGE - UPSERT operation (insert or update)
 CALL - call a PL/SQL or Java subprogram
 EXPLAIN PLAN - interpretation of the data aaccess path
 LOCK TABLE - concurrency Control

TCL:- Transaction Control Language(TCL) commands are used to manage transactions in the
database. These are used to manage the changes made to the data in a table by DML statements.
It also allows statements to be grouped together into logical transactions.

 COMMIT - commits a Transaction


 ROLLBACK - rollback a transaction in case of any error occurs
 SAVEPOINT - to rollback the transaction making points within groups
 SET TRANSACTION - specify characteristi
characteristics of the transaction

DRL:-DRL/DSL
DRL/DSL stands for Data Retrieval Language/Data Selection Language. It is a set commands
which are used to retrieve data from database server. It manipulates the data in database for
display purpose like aggregate function. In DRL/DSL, for accessing the data it uses the DML
command that is SELECT.

SELECT is the only one DRL statement in SQL.

SELECT: Select statement is used to see the data present in the database. Syntax for writing this
statement is,
If we want to see the data present in all the columns of the table, then we can use following
syntax,
AIM: - 2.1. (a).Insert, (b).Select, (c).
(c).Update, (d).Delete, (e).commit,

(f).rollback,(g).save point, (h). Like'%', (i).Relational Operator (j) Logical operators

(a) INSERT:- Insert is a widely


widely-used
used command in the Structured Query Language (SQL) data
manipulation language (DML) used by SQL Server and Oracle relational databases. The
insert command is used for inserting one or more rows into
into a database table with specified
table column values.

Example:-
INSERT INTO Person (ID, LastName, FirstName, Age) VALUES (001, 'ssss', 'rrrrr',
'rrrrr' 24);

INSERT INTO Person (ID, LastName, FirstName, Ag


Age) VALUES (002, 'ss',
, 'rrr', 16);

Output:-

(b)SELECT:- Select statement is used to see the data present in the database. Syntax for writing this
statement is,

If we want to see the data present in all the columns of the table, then we can use foll
following
owing
syntax,
(c)UPDATE:-
An SQL UPDATE statement changes the data of one or more records in a table. Either all the rows
can be updated, or a subset may be chosen using a condition. The UPDATE statement has the
following form: UPDATE table_name SSET column_name = value [, column_name = value ...] [
WHERE condition]

SYNTAX:-

Example:

(d) DELETE:- In the database structured query language (SQL), the DELETE statement
removes one or more records from a table. A subset may be defined for delet
deletion
ion using a
condition, otherwise all records are removed.

SYNTAX:-

Example:-
(e) COMMIT:- A COMMIT statement in SQL ends a transaction within a relational database
management system (RDBMS) and makes all changes visible to other users. ...
A COMMIT statement will also release any existing savepoints that may be in use. This means
that once a COMMIT statement is issued, you can not rollback the transaction.

SYNTAX:-

Example:-

(f)ROLLBACK:- SQL ............In SQL, ROLLBACK is a co


command
mmand that causes all data changes since the last
BEGIN WORK , or START TRANSACTION to be discarded by the relational database management
systems (RDBMS), so that the state of the data is "rolled back" to the way it was before those
changes were made.

SYNTAX:-

Example:-
(g) SAVEPOINT:- A savepoint is a way of implementing subtransactions (also known as nested
transactions) within a relational database management system by indicating a point within a
transaction that can be "rolled back to" with
without
out affecting any work done in the transaction before
the savepoint was created.

SYNTAX:-

Example:-

(h) LIKE%:- The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column. There are two wildcards often used in conju
conjunction with the LIKE operator: % - The percent
sign represents zero, one, or multiple characters. _ - The underscore represents a single character.

SYNTAX:-
(i) Relational Operator:- A comparison (or relational) operator is a mathematical symbol
which is used to compare two values...................... In SQL the assignment operator ( = )
assigns a value to a variable or of a column or field of a table
Description

Equal to.

Greater than.

Operator Operates on

= Any compatible data types > Any compatible data types

Less than.

Greater than equal to.

Less than equal to.

Not equal to.

< Any compatible data types >= Any compatible data types <= Any compatible data types <>

Any compatible data types

SYNTAX:-

Select [column_name]*[expression]<comparison operator>


[column_name]*[expression]
From <table_name>
Where <expression>[comparison operator]<expression>;
(j) Logical operators:-

The Logical operators are those that are true or false. They ret
return
urn a true or false values to
combine one or more true or false values.

The Logical operators are:


Operator Description

AND Logical AND compares between two Booleans as expression and returns true when
both expressions are true...

OR Logical OR compares
ompares between two Booleans as expression and returns true when one of
the expression is true...

NOT Not takes a single Boolean as an argument and changes its value from false to true or from true to false....

SYNTAX:-
PRACTIC
PRACTICAL:-3
AIM:- 3. To implement Nested Queries & Join Queries

NESTED QUERIES:- A Subquery or Inner query or a Nested query is a query within another SQL query
and embedded within the WHERE clause. A subquery is used to return data that will be used in the
main query as a condition to further restrict the data to be retrieved.
retrieved

There are mainly two types of nested queries:


∙ Independent Nested Queries: In independent nested queries, query execution starts from
innermost query to outermost queries. The execution of inner query is independent of
outer query, but the result of inner query is used in execution of outer query. Various
operators like IN, NOT IN, ANY, ALL etc are used in writing independent nested queries.

∙ Co-related Nested Queries: In co-related


co related nested queries, the output of inner query depends
on the row which is being currently executed in outer query. ee.g.;
.g.; If wewant to find out
S_NAME of STUDENTs who are enrolled in C_ID ‘C1’,

JOIN Queries:- A JOIN clause is used to combine rows from two or more tables, based on a related
column between them. A JOIN clause is used to combine rows from two or more ta tables,
bles, based on
a related column between them.

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

(INNER) JOIN:: Returns records that have matching values in both tables

LEFT (OUTER) JOIN:: Returns all re


records
cords from the left table, and the matched records from the right table

RIGHT (OUTER) JOIN:: Returns all records from the right table, and the matched records from the left table
FULL (OUTER) JOIN:: Returns all records when there is a match in either left or right table
AIM:- 3.1. To implementation of Nested Queries

Consider the CUSTOMERS table having the following records −

Now, let us check the following subquery with a SELECT statement.


Select * from customers
Where ID IN (select ID
From customers
Where salary > 4500);
This would produce the following result.
AIM:- 3.2. (a) Inner join, (b).Left join, (c).Right join (d).Full join(e) Natural Join (f) Theta Join
(g) Cross Join

(a) Inner Join

OUTPUT:-

(b) Left join

OUTPUT:-
(c) Right Join

OUTPUT:-

+--------+----------+---------+

| OrderID| LastName | FirstName|

+--------+----------+---------+

|1 | Smith | John |

|2 | Doe | Jane |

|3 | NULL | NULL | -- Order without a corresponding employee

|4 | Johnson | Bob |

| ... | ... | ... |

+--------+----------+---------+

(d)Full Join
OUTPUT:-

(e)Natural Join

OUTPUT:-

+---------+------------+------------
------------+---------------+----------+--------+

| food_id | food_name | company_id | price | company_name | locati


location
on |

+---------+------------+------------
------------+---------------+--------------+----------+

|1 | Pizza | 101 | 10.99 | ABC Company | New York |

|2 | Burger | 102 | 5.99 | XYZ Corp | Chicago |

|3 | Salad | 103 | 8.99 | DEF Inc | LA |

+---------+------------+------------
------------+---------------+--------------+----------+
(f)Theta Join

OUTPUT:-

A.column 2 > B.column2

column 1 column 2

12

(g)Cross Join

OUTPUT:-
PRACTICAL:-4
AIM:- 4. To implement Views.
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in the database. We can
create a view by selecting fields from one or more tables present in the database. A View can either have all the rows of a table
or specific rows based on certain condition.

Output:

Creating View from multiple tables:: In this example we will create a View named MarksView from two tables StudentDetails
and StudentMarks. To create a View from multiple tables we can simply include multiple tables in the SELECT statement.

Query:
Output:
AIM:- 4.1. (a). View, (b).joint view, (c).force view, (d). View with check option

(a)View

OUTPUT:-
EMPNO ENAME SALARY
---------- -------------------- ---------- ----------
7369 SMITH 1000
7499 MARK 1050
7565 WILL 1500
7678 JOHN 1800
7578 TOM 1500
7548 TURNER 1500
6 rows selected.

(b)joint View
CREATE OR REPLACE VIEW DEPT_EMP AS
SELECT A.EMPNO "EID", A.ENAME "EMPNAME", A.DEPTNO "DNO", B.DNAM "D_NAME", B.LOC
"D_LOC"
FROM EMPL A, DEPMT B
WHERE A.DEPTNO = B.DEPTNO;

OUTPUT:-
EID NAME SAL
---------- -------------------- ---------- ----------
7369 SMITH 1000
7499 MARK 1050
7565 WILL 1500
7678 JOHN 1800
7578 TOM 1500
7548 TURNER 1500
6 rows selected.
(d) Force View

OUTPUT:-
EMPNO ENAME SALARY DEPTNO
---------- -------------------- ---------- ------
---------- -----------------
7369 SMITH 1000 20
7499 MARK 1050 30
7565 WILL 1500 30
7678 JOHN 1800 20
7578 TOM 1500 10
7548 TURNER 1500 10
6

(e) View with check option

OUTPUT:-

EMPNO ENAME SALARY DEPTNO


---------- -------------------- ---------- -----------
7578 TOM 1500 10
7548 TURNER 1500 10
PRACTICAL:
PRACTICAL:-5
AIM:- 5 To implement Index.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the
table and which column or columns to index,, and to indicate whether the index is in an ascending or descending order.

Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply
Si put, an index is a
pointer to data in a table. An index in a database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to the index, which lists
all the topics alphabetically and are then referred to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with the UPDATE and the INSERT
statements

AIM :- 5.1 1 (a) Normal Index (b) Unique Index (c) Bitmap Index
(d) Composite (e) B-Tree (f) Clustered (g) Non- Clustered

(a) Normal index


Normal Indexes:
∙ To create normal index, you must have CREATE ANY INDEX privilege. After that you can create index on the table. ∙
’ALL_INDEXES’
L_INDEXES’ is the system table which gives user the information about the indexes on the table. If Indexing is not
there on table level you can do the indexing on column of the table.

Syntax of Normal Index:

(b)Unique index
Unique Index
∙ If the Unique
ique index key consists of one column, SQL Server will guarantee that each value in the index key is unique. ∙
To create unique index you must have CREATE ANY INDEX privilege.
∙ The CREATE UNIQUE INDEX command creates a unique index on a table (no duplica
duplicate
te values allowed)

Example
Output :-
+--------+------------+----------+--------------+-------------
-------------+-----------+-------------+----------+--------+------+------------
------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_ Column_namename | Collation | Cardinality | Sub_part | Packed | Null |
Index_type | Comment | Index_comment |
+--------+------------+----------+--------------+-------------
-------------+-----------+-------------+----------+--------+------+------------
------------+---------+---------------+
| Persons| 0 | uidx_pid | 1 | PersonID | A | ... | ... | ... | YES | BTREE | | |
+--------+------------+----------+--------------+-------------
-------------+-----------+-------------+----------+--------+------+------------
------------+---------+---------------+

Bit-Map Index
∙ If Table contains the distinct values which are not more than 20 distinct values then user should go for Bit map indexes. ∙
User should avoid the indexing on each and every row and do the indexing only on distinct records of the table column. ∙
The bit map ap indexes are very much useful in dataware housing where there are low level of concurrent transactions. ∙ Bit
map index stores row_id as associated key value with bitmap and did the indexing only distinct values.Means If in 1
million records only 20 distinct
stinct values are there so Bitmap index only stores 20 values as bitmap and fetches the
records from that 20 values only.

Syntax:

Example/Real Life Scenario:


“Suppose There are 2 tables which has milions of records.We need to improve the performance of Query.Now It is taking 4
mins to fetch 1 million Records.”
Step 1:
Explain Plan select * from DEPT d,EMP e where d.DEPTNO= e.deptno;
Output:
Cost of DEPT Table-20000 – table is Full Scanned
Cost of EMP tabe-20000-table is Full Scanned
Step 2:
Check
eck whether there are SQL Indexes on table columns:
Select * from ALL_INDEXES where Table name in (‘EMP’,’DEPT’);
Output:
No indexes found.
Step 3:
Check description of the table and check whether the normal index where the Unique index and where bitmap
bitm indexes are
applicable.
Step 4:
Creation of normal index on EMP table name column.
Create index NI_EMP_NAME on EMP(NAME);
Step 5:
EMP_ID has unique values so kindly create UNIQUE INDEX ON that column.DEPTNO has also unique values so for DEPTNO
column we need to create unique index.
CREATE UNIQUE INDEX UI1_EMP on EMP(EMP_ID);
Step 6:
Check for Distinct values.So Department_name has 20 distinct departments so on Department_name column create Bit Bit-map
index.
CREATE BITMAP index BM_DEPT_NAME on DEPT(Department_name);
Step 7:
Check the cost of Query
Explain Plan select * from DEPT d,EMP e where d.DEPTNO= e.deptno;
Output:
Emp Table :-> 20 Fast Unique Scan
DEPT Table:-> 10 Bit-map Scan
and Results will come in 10 Seconds..Hope everyone get idea about basic indexing and how it is been used in real life scenarios

Composite index: An index that contains more than one column. In both SQL Server 2005 and 2008, you can include up to 16
columns in an index,
dex, as long as the index doesn’t exceed the 900-byte
900 byte limit. Both clustered and nonclustered indexes can be
composite indexes.
ou can create an index on multiple columns in a table. If you want to create an index on the EMPLOYEE_ID and
DEPARTMENT_ID columns umns in the employees table, for example, you can do so, and the result is called a composite or
concatenated index. Here's an
example:
SQL> create index test_idx1 on employees(employee_id,department_id); Index created. SQL>
You can create composite B-treetree indexes as well bitmap indexes. The optimizer will take into account a composite index when
the WHERE clause in a query refers to all the columns in the index or even the leading column.
A composite index is also known as a multiple-column
column index.
Iff you specify the columns in the right order in the index definition, a single composite index can speed up these kinds of queries
qu
on the same table
We will use the employees table in the sample database for the demonstration.

syntax

EXPLAIN SELECT firstName,


stName, lastName, email FROM employees WHERE lastName = 'Patterson';

Output

Example of Clustered Index –


If you apply primary key to any column, then automatically it will become clustered index.
create table Student
( Roll_No int primary key,
Name varchar(50),
Gender varchar(30),
Mob_No bigint );

insert into Student


values (4, 'ankita', 'female', 9876543210 );
values (3, 'anita', 'female', 9675432890 );

insert into Student


values (5, 'mahima', 'female', 8976453201 );
In this example, Roll no is a primary key, it will automatically act as a clustered index.
The output of this code will produce in increasing order of roll no.

ROLL_NO NAME GENDER MOB_NO

3 anita female 9675432890

4 ankita female 9876543210

5 mahima female 8976453201

You can have only one clustered index in one table, but you can have one clustered index on multiple columns, and that type
of index is called composite index.
2. Non-clustered Index :
Non-Clustered Index is similar to the index of a book. The index of a book consists of a chapter name and page number, if you
want to read any topic or chapter then you can directly go to that page by using index of that book. No need to go through each
and every page of a book.
The data is stored in one place, and index is stored in another place. Since, the data and non-clustered index is stored
separately, then you can have multiple non-clustered index in a table.
In non-clustered index, index contains the pointer to data.

Example of Non-clustered Index –


create table Student
( Roll_No int primary key,
Name varchar(50),
Gender varchar(30),
Mob_No bigint );

insert into Student


values (4, 'afzal', 'male', 9876543210 );

insert into Student


values (3, 'sudhir', 'male', 9675432890 );

insert into Student


values (5, 'zoya', 'female', 8976453201 );

create nonclustered index NIX_FTE_Name


on Student (Name ASC);
Here, roll no is a primary key, hence there is automatically a clustered index.
If we want to apply non-clustered index in NAME column (in ascending order), then the new table will be created for that
column. Output before applying non-clustered index :

ROLL_NO NAME GENDER MOB_NO

3 sudhir male 9675432890

4 afzal male 9876543210

5 zoya female 8976453201

Output after applying non-clustered index :

NAME ROW ADDRESS

Afzal 3452

Sudhir 5643

zoya 9876
PRACTICAL:-6
AIM:- 6 To study various Date handling functions and their usage.

SQL Dates

The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the
format of the date column in the database.

As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it
gets more complicated.

SQL Date Data Types

MySQL comes with the following data types for storing a date or a date/time value in the database:

∙ DATE - format YYYY-MM-DD


∙ DATETIME - format: YYYY-MM-DD HH:MI:SS
∙ TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
∙ YEAR - format YYYY or YY

SQL Server comes with the following data types for storing a date or a date/time value in the database:

∙ DATE - format YYYY-MM-DD


∙ DATETIME - format: YYYY-MM-DD HH:MI:SS
∙ SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
∙ TIMESTAMP - format: a unique number

Note: The date types are chosen for a column when you create a new table in your database!
OrderId ProductName OrderDate

1 Geitost 2008-11-11

2 Camembert Pierrot 2008-11-09

3 Mozzarella di Giovanni 2008-11-11


4 Mascarpone Fabioli 2008-10-29

SQL Working with Dates

You can compare two dates easily if there is no time component involved!

Assume we have the following "Orders" table:

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.

We use the following SELECT statement:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:


OrderId ProductNa
OrderD
me
ate

Geitost 2008-
OrderId ProductName OrderDate
11-11

1 Geitost 2008-11-11 13:23:44 2 Camembert Pierrot 2008-11-09 15:45:21 3 Mozzarella di

Giovanni 2008-11-11 11:12:01 4 Mascarpone Fabioli 2008-10-29 14:56:59


1

3 Mozzarella
2008-
di
11-11
Giovanni

Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"

column): If we use the same SELECT statement as above:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'


PRACTICAL:-7
AIM:- 7 To Study String Handling Functions with Usage.

String functions
are used to perform an operation on input string and return an output string.
Following are the string functions defined in SQL:
1. ASCII(): This function is used to find the ASCII value of a character.

2. Syntax: SELECT ascii('t');


Output: 116

3. CHAR_LENGTH(): Doesn’t work for SQL Server. Use LEN() for SQL Server. This function is used to find the length of a word.

4. Syntax: SELECT char_length('Hello!');


Output: 6

5. CHARACTER_LENGTH(): Doesn’t work for SQL Server. Use LEN() for SQL Server. This function is used to find the length of a
line.

6. Syntax: SELECT CHARACTER_LENGTH('geeks for geeks');


Output: 15

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

8. Syntax: SELECT 'Geeks' || ' ' || 'forGeeks' FROM dual;


Output: ‘GeeksforGeeks’

9. CONCAT_WS(): This function is used to add two words or strings with a symbol as concatenating symbol.

Syntax: SELECT CONCAT_WS('_', 'geeks', 'for', 'geeks');


Output: geeks_for_geeks

10. FIND_IN_SET(): This function is used to find a symbol from a set of symbols.

11. Syntax: SELECT FIND_IN_SET('b', 'a, b, c, d, e, f');


Output: 2

12. FORMAT(): This function is used to display a number in the given format.

13. Syntax: Format("0.981", "Percent");


Output: ‘98.10%’

14. INSERT(): This function is used to insert the data into a database.

15. Syntax: INSERT INTO database (geek_id, geek_name) VALUES (5000, 'abc');
Output: successfully updated

16. INSTR(): This function is used to find the occurrence of an alphabet.

17. Syntax: INSTR('geeks for geeks', 'e');


Output: 2 (the first occurrence of ‘e’)
Syntax: INSTR('geeks for geeks', 'e', 1, 2 );
Output: 3 (the second occurrence of ‘e’)
18. LCASE(): This function is used to convert the given string into lower case.

19. Syntax: LCASE ("shubham singh To Learn");


Output: shubhamsingh to learn
PRACTICAL:-8
AIM:-8. Case study of oracle 11g with emphasis on RECOVERY Techniques, Concurrency and Transaction Management.

Transactions
A transaction models the execution of a software procedure constituted by a set of instructions that may ”read from” and
“write on” a database, and that form a single logical unit. Syntactically, we will assume that every transaction contains: –
one “begin” instruction
– one “end” instruction
– one among “commit” (confirm what you have done on the database so far) and “rollback” (undo what you have done on the
database so far)
As we will see, each transaction should enjoy a set of properties (called
ACID)

begin
writeln(’Inserire importo, conto di partenza, conto di arrivo’);
read (Importo, contoPartenza, contoArrivo);
EXEC SQL
select Saldo into :saldoCorrente
from ContiCorrenti
where Numero = :contoPartenza
if saldoCorrente < Importo
then begin
writeln(’Saldo Insufficiente’);
ABORT;
end;
else begin
EXEC SQL
UPDATE ContiCorrenti
set Saldo=:saldoCorrente - :Importo
where Numero = :contoPartenza;
writeln(‘Operazione eseguita con successo’);
COMMIT;
end;
end;

Let DB be a database
Let T be a transaction on DB
Effect (or result) of T = state of DB after the execution of T
As we shall see, every transaction must enjoy a set of properties
(called ACID properties) that deal with the effect of the transaction

Concurrency
The throughput of a system is the number of transactions per second
(tps) accepted by the system
In a DBMS, we want the throughput to be approximately 100-1000tps
This means that the system should support a high degree of
concurrency among the transactions that are executed

– Example: If each transaction needs 0.1 seconds in the average for


its execution, then to get a throughput of 100tps, we must
ensure that 10 transactions are executed concurrently in the
average
Typical applications: banks, flight reservations, …
Concurrency: example
Suppose that the same program is executed concurrently by two
applications aiming at reserving a seat in the same flight
The following temporal evolution is possible:
Application 1 Application 2
1. Find seat
2. Find seat
3. Book seat
4. Book seat

The result is that we have two reservations for the same seat!

Isolation of transactions
The DBMS deals with this problem by ensuring the so-called
“isolation” property for the transactions
This property for a transaction essentially means that it is
executed like it was the only one in the system, i.e., without
concurrent transactions
While isolation is essential, other properties are important as
Well

Desirable properties of transactions


The desirable properties in transaction management are called the
ACID properties. They are:
1. Atomicity: for each transaction execution, either all or none
of its actions are executed
2. Consistency: each transaction execution brings the
database to a correct state
3. Isolation: each transaction execution is independent of any
other concurrent transaction executions
4. Durability: if a transaction execution succeeds, then its
effects are registered permanently in the database

Schedules and serial schedules


Given a set of transactions T1,T2,…,Tn, a sequence S of executions of
actions of such transactions respecting the order within each
transaction (i.e., such that if action a is before action b in Ti, then a is
before b also in S) is called schedule on T1,T2,…,Tn, or simply
schedule.
A schedule on T1,T2,…,Tn that does not contain all the actions of all
transactions T1,T2,…,Tn is called partial
A schedule S is called serial if the actions of each transaction in S
come before every action of a different transaction in S, i.e., if in S
the actions of different transactions do not interleave.

Purpose of Backup and Recovery

As a backup administrator, your principal duty is to devise, implement, and manage a backup and recovery strategy. In
general, the purpose of a backup and recovery strategy is to protect the database against data loss and reconstruct the
database after data loss. Typically, backup administration tasks include the following:
∙ Planning and testing responses to different kinds of failures
∙ Configuring the database environment for backup and recovery
∙ Setting up a backup schedule
∙ Monitoring the backup and recovery environment
∙ Troubleshooting backup problems
∙ Recovering from data loss if the need arises

As a backup administrator, you may also be asked to perform other duties that are related to backup and recovery:

∙ Data preservation, which involves creating a database copy for long-term storage
∙ Data transfer, which involves moving data from one database or one host to another

The purpose of this manual is to explain how to perform the preceding tasks.

Data Protection

As a backup administrator, your primary job is making and monitoring backups for data protection. A backup is a copy of data of
a database that you can use to reconstruct data. A backup can be either a physical backup or a logical backup.

Physical backups are copies of the physical files used in storing and recovering a database. These files include data files, control
files, and archived redo logs. Ultimately, every physical backup is a copy of files that store database information to another
location, whether on disk or on offline storage media such as tape.

Logical backups contain logical data such as tables and stored procedures. You can use Oracle Data Pump to export logical data
to binary files, which you can later import into the database. The Data Pump command-line clients expdp and impdp use the
DBMS_DATAPUMP and DBMS_METADATA PL/SQL packages.

Physical backups are the foundation of any sound backup and recovery strategy. Logical backups are a useful supplement to
physical backups in many circumstances but are not sufficient protection against data loss without physical backups.

Unless otherwise specified, the term backup as used in the backup and recovery documentation refers to a physical backup.
Backing up a database is the act of making a physical backup. The focus in the backup and recovery documentation set is almost
exclusively on physical backups.

While several problems can halt the normal operation of an Oracle database or affect database I/O operations, only the
following typically require DBA intervention and data recovery: media failure, user errors, and application errors. Other failures
may require DBA intervention without causing data loss or requiring recovery from backup. For example, you may need to
restart the database after an instance failure or allocate more disk space after statement failure because of a full data file.

Media Failures

A media failure is a physical problem with a disk that causes a failure of a read from or write to a disk file that is required to run
the database. Any database file can be vulnerable to a media failure. The appropriate recovery technique following a media
failure depends on the files affected and the types of backup available.

One particularly important aspect of backup and recovery is developing a disaster recovery strategy to protect against
catastrophic data loss, for example, the loss of an entire database host.

User Errors

User errors occur when, either due to an error in application logic or a manual mistake, data in a database is changed or deleted
incorrectly. User errors are estimated to be the greatest single cause of database downtime.
Data loss due to user error can be either localized or widespread. An example of localized damage is deleting the wrong person
from the employees table. This type of damage requires surgical detection and repair. An example of widespread damage is a
batch job that deletes the company orders for the current month. In this case, drastic action is required to avoid a extensive
database downtime.

While user training and careful management of privileges can prevent most user errors, your backup strategy determines how
gracefully you recover the lost data when user error does cause data loss.

Application Errors

Sometimes a software malfunction can corrupt data blocks. In a physical corruption, which is also called a media corruption, the
database does not recognize the block at all: the checksum is invalid, the block contains all zeros, or the header and footer of
the block do not match. If the corruption is not extensive, then you can often repair it easily with block media recovery.

You might also like