Dbms Lab Procedure
Dbms Lab Procedure
Aim:
To study and execute the DDL Commands in RDBMS
Creating a Database
To create a database in RDBMS, create command is used. Following is the syntax,
The above command will create a database named dbms, which will be an empty
schema without any table.
To create tables in this newly created database, we can again use the create command.
Creating a Table
Create command can also be used to create tables. Now when we create a table, we have
to specify the details of the columns of the tables too. We can specify the names and
data types of various columns in the create command itself.
Following is the syntax,
create table command will tell the database system to create a new table with the given
table name and column information.
Using ALTER command we can add a column to any existing table. Following is the
syntax,
Using ALTER command we can even add multiple new columns to any existing table.
Following is the syntax,
ALTER command can also be used to modify data type of any existing column.
Following is the syntax,
Using ALTER command you can rename an existing column. Following is the syntax,
ALTER command can also be used to drop or remove columns. Following is the syntax,
RENAME query
RENAME command is used to set a new name for any existing table. Following is the
syntax,
RENAME TABLE old_table_name to new_table_name
TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not
destroy the table's structure. When we use TRUNCATE command on a table its (auto-
increment) primary key is also initialized. Following is its syntax,
DROP command
DROP command completely removes a table from the database. This command will also
destroy the table structure and the data stored in it. Following is its syntax,
Result : Table created successfully and applied all the DDL commands.
Ex no 1B SQL CONSTRAINTS
Aim:
To add and execute the constraints in create command
Procedure:
To practice basic SQL constraints like NOT NULL, primary key and check constraints.
Constraints:
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 constraints and the data action, the action is aborted.
Check Constraint
It works for numerical value conditions ensures that the values in a column satisfies a
specific condition
Syntax:
Create table tablename(column1 datatype1, column2 datatype, colunmn3
datatype3.....check condition);
Eg:
Create table person(id int NOT NULL,lastname varchar2(25) NOT NULL,Firstname
varchar2(25),age int check(age>=18));
NOT NULL constraints:
It ensures that a column cannot have a null value
Syntax:
Create table tablename(column1 not null,column2 not null,column3 not null);
Eg:
Create table person(id int NOT NULL,lastname varchar2(25) NOT NULL,firstname
varchar2(25) NOT NULL, age int );
Result:
Thus the SQL constraints like primary key,unique ,check and not null constraints are
executed successfully.
Aim:
To Create a set of tables, add foreign key constraints and incorporate referential integrity.
Procedure:
Referential Integrity
A referential integrity constraint is also known as foreign key constraint. A foreign key is
a key whose values are derived from the Primary key of another table.
The table from which the values are derived is known as Master or Referenced Table and
the Table in which values are inserted accordingly is known as Child or Referencing
Table, In other words, we can say that the table containing the foreign key is called the
child table, and the table containing the Primary key/candidate key is called the referenced
or parent table.
Parent Table:
Result:
Thus the Create a set of tables, add foreign key constraints and incorporate referential
integrity are executed successfully.
Ex:No: 3 WHERE CLUASE AND AGGREGATE FUNCTIONS
Aim:
Query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.
Procedure:
A WHERE clause in SQL is used with the SELECT query, which is one of the data
manipulation language commands. WHERE clauses can be used to limit the number of
rows to be displayed in the result set, it generally helps in filtering the records. It returns
only those queries which fulfill the specific conditions of the WHERE clause. WHERE
clause is used in SELECT, UPDATE, DELETE statement, etc.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example 1:
Write a query to retrieve all those records of an employee where employee salary is greater than 50000.
Query:
sql> SELECT * FROM employees WHERE Salary > 50000;
output:
AGGREGATE FUNCTIONS:
An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL
provides many aggregate functions that include avg, count, sum, min, max, etc. An aggregate function
ignores NULL values when it performs the calculation, except for the count function
COUNT(ENAME)
-------------------------
7
(iii)Find the Maximum age from employee table.
SQL> select max(age) from emp;
MAX(AGE)
-----------------
44
(iv)Find the Minimum age from employee table.
SQL> select min(age) from emp;
MIN(AGE) ----------------
22
(v)Display the Sum of age employee table.
SQL> select sum(age) from emp;
SUM(AGE)
----------------
220
7 rows selected.
(xi) Find salaries of employee in Descending Order.
SQL> select ename,salary from emp order by salary desc;
ENAME SALARY
-------------- ---------------
scott 10000
anu 9000
shane 8000
abhi 8000
tiger 8000
alex 7000
rohan 6000
7 rows selected.
(xii)Having Clause.
SQL> select ename,salary from emp where age
ENAME SALARY
----------- --------------
alex 7000
anu 9000
Result:
Thus the Query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.
Aim:
To Query the database tables and explore sub queries and simple join operations.
Procedure:
SQL - SELECT Query
The SQL SELECT statement is used to fetch the data from a database table which returns this data in the
form of a result table. These result tables are called result-sets.
Syntax
The basic syntax of the SELECT statement is as follows −
SELECT column1, column2, columnN FROM table_name;
While creating a database if we want to extract some information regarding the data in the database then
we use a Query. In other words, if we want to retrieve some data from a table or some tables that we
created earlier then we write/use a Query.
Sub Queries are very useful for selecting rows from a table having a condition that depends on the data of
the table itself. A Sub Query can also be called a Nested/Inner Query. These Sub Queries can be used
with:
• WHERE Clause
• SELECT Clause
• FROM Clause
SELECT <column, ...> FROM <table> WHERE expression operator ( SELECT <column, ...> FROM
<table> WHERE <condition> );
Nested Subquery:
A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one another.
A subquery is a SELECT statement that is nested within another SELECT statement and which return
intermediate results. SQL executes innermost subquery first, then next level
Join:
Join is the most powerful operation for merging information from multiple tables based on a common
field. There are various types of joins but an INNER JOIN is the common of them.
Syntax
SELECT col1, col2, col3... FROM table_name1, table_name2 WHERE table_name1.col2 =
table_name2.col1;
Eg:
CREATE TABLE Customer ( Cust_id Number(10) NOT NULL, Cust_name varchar2(20), Country
varchar2(20), Receipt_no Number(10), Order_id Number(10) NOT NULL, );
CREATE TABLE Orders ( Order_id Number(10), Item_ordered varchar2(20), Order_date date );
Using and ON clause
SELECT Cust_id, Cust_name, Country, item_Ordered, Order_date FROM Customer C JOIN Orders O
USING (Order_id);
SELECT Cust_id, Cust_name, Country, item_Ordered, Order_date FROM Customer C JOIN Orders O
ON (C.Order_id = O.Order_id);
Equi Join
An Equi join is used to get the data from multiple tables where the names are common and the columns
are specified. It includes the equal ("=") operator.
Example
SELECT Cust_id, Cust_name, item_Ordered, Order_date FROM Customer C, Orders O WHERE
C.Order_id = O.Order_id;
Result: Thus the Database Querying – Simple Queries, Nested Queries, Sub Queries and Joins are
executed successfully
Aim:
To create the tables and explore natural, equi and outer join
1. Inner Join An Inner Join retrieves the matching records, in other words it retrieves all the rows where
there is at least one match in the tables.
Example SELECT Cust_id, Cust_name, Country, item_ordered, Order_date
FROM Customer INNER JOIN Orders USING (Order_id);
2. Outer Join
The records that don't match will be retrieved by the Outer join. It is of the following three types:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join
4. Non-Equi Join A Non-Equi join is based on a condition using an operator other than equal to "=".
Example
SELECT Cust_id, Cust_name, Country, Item_ordered, Order_date FROM Customer C, Oredrs O
WHERE C. Order_id > O.Order_id;
5. Self-join When a table is joined to itself only then that condition is called a self-join.
Example
SELECT C1.Cust_id, C2.Cust_name, C1.Country, C2.Order_id FROM Customer C1, Customer C2
WHERE C. Cust_id > O.Order_id;
Aim:
To Write user defined functions and stored procedures in SQL.
Procedure:
A subprogram is a program unit/module that performs a particular task. These subprograms are combined
to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked by
another subprogram or program which is called the calling program.
Functions − These subprograms return a single value; mainly used to compute and return a value.
Creating a function
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
• Procedures − These subprograms do not return a value directly; mainly used to perform an action.
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World
PL/SQL procedure successfully completed.
The procedure can also be called from another PL/SQL block −
BEGIN
greetings;
END;
/
The above call will display −
Hello World
Deleting a Standalone Procedure
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a
procedure is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
DROP PROCEDURE greetings;
Parameters in Procedure:
IN-> It is the read only parameter. It is the default mode parameter of passing.
OUT-> returns a value to the calling function
INOUT-> passes an initial value to a subprogram and returns an updated value to the caller
Result:
AIM:
Procedure:
DCL COMMANDS
DCL stands for Data Control Language in Structured Query Language (SQL). As the name suggests these
commands are used to control privilege in the database. The privileges (Right to access the data) are
required for performing all the database operations like creating tables, views, or sequences.
DCL command is a statement that is used to perform the work related to the rights, permissions, and other
control of the database system
GRANT
This command is used to grant permission to the user to perform a particular operation on a particular
object. If you are a database administrator and you want to restrict user accessibility such as one who only
views the data or may only update the data. You can give the privilege permission to the users according
to your wish.
Syntax:
REVOKE
REVOKE
This command is used to take permission/access back from the user. If you want to return permission
from the database that you have granted to the users at that time you need to run REVOKE command.
Syntax:
TCL Commands
COMMIT command
COMMIT command is used to permanently save any transaction into the database. To avoid that, we use
the COMMIT command to mark the changes as permanent. Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last committed state. It is also used with SAVEPOINT command
to jump to a savepoint in an ongoing transaction.
Following is rollback command's syntax, ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that point
whenever required.
Following is savepoint command's syntax, SAVEPOINT savepoint_name;
Aim:
To Write SQL Triggers for insert, delete, and update operations in a database table.
PROCEDURE:
A PL/SQL trigger is a named database object that encapsulates and defines a set of actions that are to be
performed in response to an insert, update, or delete operation against a table. Triggers are created using
the PL/SQL CREATE TRIGGER statement.
General Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with the
trigger_name.
Insert/Update Trigger
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[OR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row
being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is
called a table level trigger.
WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is
valid only for row level triggers .
Result:
Thus the PL/SQL Trigger are executed successfully.
Procedure:
A view can contain all rows of a table or select rows from a table. A view can be created from one or
many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data in
such a way that a user can see and (sometimes)
modify exactly what they need and no more.
Summarize data from various tables which can be used to generate reports.
Creating Views
CREATE VIEW view_name AS SELECT column1, column2...
FROM table_name WHERE [condition];
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer
needed. The syntax is very simple and is given below −
drop view view_name;
INDEX
Indexes are used to find rows with specific column values quickly. Without an
index, SQL must begin with the first row and then read through the entire table to find
the relevant rows.
Syntax : CREATE INDEX index_name ON table_name (column_list)
The following command is used for displaying a particular data from the table by
the use of index.
Procedure:
XML schema is a language which is used for expressing constraint about XML documents. There
are so many schema languages which are used now a days for example Relax- NG and XSD
(XML schema definition).
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
The Schema above is interpreted like this:
Result:
Thus the Create an XML database and validate it using XML schema are executed successfully.