Professional Documents
Culture Documents
1919 Vichitar Dbms
1919 Vichitar Dbms
& MANAGEMENT
Sign
S.No Name of Program Date
Of
Facult
y
1. To study Data Definition language
4. To implement Views.
5. To implement Index
7.
To Study String Handling Functions with Usage.
CREATE – iss used to create the database or its objects (like table,index,
function, views, store procedure and triggers).
TRUNCATE– is used to remove all records from a table, including all spaces
allocated for the records are removed.
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.
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
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:-
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
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.
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.
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: 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,
Example:-
INSERT INTO Person (ID, LastName, FirstName, Age) VALUES (001, 'ssss', 'rrrrr',
'rrrrr' 24);
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:-
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
Less than.
< Any compatible data types >= Any compatible data types <= Any compatible data types <>
SYNTAX:-
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.
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
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.
(INNER) JOIN:: Returns records that have matching values in both tables
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
OUTPUT:-
OUTPUT:-
(c) Right Join
OUTPUT:-
+--------+----------+---------+
+--------+----------+---------+
|1 | Smith | John |
|2 | Doe | Jane |
|4 | Johnson | Bob |
+--------+----------+---------+
(d)Full Join
OUTPUT:-
(e)Natural Join
OUTPUT:-
+---------+------------+------------
------------+---------------+----------+--------+
+---------+------------+------------
------------+---------------+--------------+----------+
+---------+------------+------------
------------+---------------+--------------+----------+
(f)Theta Join
OUTPUT:-
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
OUTPUT:-
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
(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:
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
Output
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.
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.
MySQL comes with the following data types for storing a date or a date/time value in the database:
SQL Server comes with the following data types for storing a date or a date/time value in the database:
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
You can compare two dates easily if there is no time component involved!
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
Geitost 2008-
OrderId ProductName OrderDate
11-11
3 Mozzarella
2008-
di
11-11
Giovanni
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
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.
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.
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.
9. CONCAT_WS(): This function is used to add two words or strings with a symbol as concatenating symbol.
10. FIND_IN_SET(): This function is used to find a symbol from a set of symbols.
12. FORMAT(): This function is used to display a number in the given format.
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
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
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
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.