db_ms_merged_removed
db_ms_merged_removed
db_ms_merged_removed
:- 02
Name of Experiment :- Introduction to SQL, DDL, DDL, DCL queries and constraints.
Populating and manipulating database tables using DML statements.
Introduction to SQL :-
A Brief History of SQL -
The history of SQL begins in an IBM laboratory in San Jose, California, where SQL was
developed in the late 1970s. The initials stand for Structured Query Language, and the language
itself is often referred to as "sequel." It was originally developed for IBM's DB2 product (a
relational database management system, or RDBMS, that can still be bought today for various
platforms and environments). In fact, SQL makes an RDBMS possible. SQL is a nonprocedural
language, in contrast to the procedural or third- generation languages (3GLs) such as COBOL
and C that had been created up to that time.
The characteristic that differentiates a DBMS from an RDBMS is that the RDBMS provides a
set-oriented database language. For most RDBMSs, this set-oriented database language is
SQL. Set oriented means that SQL processes sets of data in groups.
An Overview of SQL
SQL is the de facto standard language used to manipulate and retrieve data from these
relational databases. SQL enables a programmer or database administrator to do the following:
TCL stands for transaction control language which is used to control the
transactions just performed? In this we are basically using two commands, ie.
Commit and rollback. Commit is used to save the transactions and rollback is
used to unsave the transaction and it backs to its original position.
DCL stands for data control language. It is used to control the data access by the
user. If u don’t want to give permission to anybody to access any data in that we
can. It includes basically two commands that are grant and revoke.
Components of SQL
What is DDL?
DDL, which stands for Data Definition Language, is a subset of SQL (Structured Query
Language) commands used to define and modify the database structure. These commands are
used to create, alter, and delete database objects like tables, indexes, and schemas.
1. CREATE: This command is used to create a new database object. For example, creating
a new table, a view, or a database.
Syntax for creating a table: CREATE TABLE table_name (column1 datatype,
column2 datatype, ...);
2. ALTER: This command is used to modify an existing database object, such as adding,
deleting, or modifying columns in an existing table.
Syntax for adding a column in a table: ALTER TABLE table_name ADD
column_name datatype;
Syntax for modifying a column in a table: ALTER TABLE table_name MODIFY
COLUMN column_name datatype;
3. DROP: This command is used to delete an existing database object like a table, a view,
or other objects.
Syntax for dropping a table: DROP TABLE table_name;
4. TRUNCATE: This command is used to delete all data from a table, but the structure of
the table remains. It’s a fast way to clear large data from a table.
Syntax: TRUNCATE TABLE table_name;
5. COMMENT: Used to add comments to the data dictionary.
Syntax: COMMENT ON TABLE table_name IS 'This is a comment.';
6. RENAME: Used to rename an existing database object.
Syntax: RENAME TABLE old_table_name TO new_table_name;
DDL commands play a crucial role in defining the database schema.
Data Manipulation Language (DML) is a subset of SQL commands used for adding (inserting),
deleting, and modifying (updating) data in a database. DML commands are crucial for managing
the data within the tables of a database.
Data Control Language (DCL) is a subset of SQL commands used to control access to data in a
database. DCL is crucial for ensuring security and proper data management, especially in multi-
user database environments.
1. GRANT: This command is used to give users access privileges to the database. These
privileges can include the ability to select, insert, update, delete, and so on, over database
objects like tables and views.
Syntax: GRANT privilege_name ON object_name TO user_name;
For example, GRANT SELECT ON employees TO user123; gives user123 the
permission to read data from the employees table.
2. REVOKE: This command is used to remove previously granted access privileges from a
user.
Syntax: REVOKE privilege_name ON object_name FROM user_name;
For example, REVOKE SELECT ON employees FROM user123; would
remove user123‘s permission to read data from the employees table.
Database administrators typically use DCL commands. When using these commands, it’s
important to carefully manage who has access to what data, especially in environments
where data sensitivity and user roles vary significantly.
In some systems, DCL functionality also encompasses commands like DENY (specific to
certain database systems like Microsoft SQL Server), which explicitly denies specific
permissions to a user, even if those permissions are granted through another role or user
group.
Remember, the application and syntax of DCL commands can vary slightly between
different SQL database systems, so it’s always good to refer to specific.
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 have to
be performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.
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.
Example:
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.
Example:
Example:
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.
Example:
Modifying the structure of tables – DDL Commands
Renaming tables,
Dropping table structure – Alter Table,
Rename, Drop, Truncate Commands
The structure of a table can be modified by using the ALTER TABLE it is possible to add or
delete columns, create or destroy indexes, change the data of existing columns orrename
columns or the table itself.
This command is used to add anew column at the end of the structure of an existingtable.
Output:
Output:
Output:
RENAMING TABLES
RENAME command is used to change the old name of any table to a new one.
Syntax: RENAME <OldTableName> TO <NewTableName>;
Output:
DESTROYING TABLES
DROP TABLE command is used to delete/discard any table.
Output:
TRUNCATING TABLES
TRUNCATE TABLE command deletes all the rows of any table.
It is similar to a DELETE statement for deleting all rows but there are some differencesalso:
Truncate operations drop & re-create the table.
<ColumnName2>=<Expression2>;
ROLL_NO=‘CS/05/119’;
EXPERIMENT NO. :- 03
Name of Experiment :- Selecting data from tables : SELECT statement, where clause,
having clause, group by, order by, selecting NULL values, use of IN and DISTINCT
keywords.
Output:
name roll_no
John Doe 101
Jane Smith 102
AAA 103
Ex: WHERE clause can be used with CREATE, SELECT, DELETE & UPDATE
commands.
Output:
Output:
This clause is used to filter data. This clause creates a data set , containing
several setsof records grouped together based on a condition.
Syntax:
SELECT <ColumnName1>, <ColumnName2>,
<ColumnName1>, Aggregate_Function
(<Expression>) GROUP BY <ColumnName1>, <ColumnName2>,
<ColumnNameN>;
Output:
This can be used in conjunction with the GROUP BY clause. Having imposes
(puts) acondition on the GROUP BY clause, which further filters the groups
created by the Group By clause.
Syntax:
SELECT <ColumnName1>, <ColumnName2>,
<ColumnName1>,Aggregate_Function (<Expression>) GROUP BY
<ColumnName1>, <ColumnName2>,<ColumnNameN> HAVING <Condition>;
Output: 25 Student
This clause is used to filter data. This clause creates a data set , containing
several setsof records grouped together based on a condition.
Syntax:
SELECT
<ColumnName1>,<ColumnName2>,<ColumnName1>,Aggregate_Function
(<Expression>) GROUP BY <ColumnName1>, <ColumnName2>,
<ColumnNameN>;
This can be used in conjunction with the GROUP BY clause. Having imposes
(puts) acondition on the GROUP BY clause, which further filters the groups
created by the Group By clause.
Syntax:
SELECT <ColumnName1>, <ColumnName2>,
<ColumnName1>,Aggregate_Function (<Expression>) GROUP BY
<ColumnName1>, <ColumnName2>, <ColumnNameN> HAVING <Condition>;
Name of Experiment :- Study the use of SQL string, date, arithmetic and
aggregate functions with examples.
String Functions:
String functions in SQL allow manipulation and modification of string data. Some commonly
used string functions include:
Example:
2. Date Functions:
Date functions in SQL are used for manipulating date and time values. Some commonly used
date functions include:
Example:
3. Arithmetic Operations:
Arithmetic operations in SQL are used for mathematical calculations. Common arithmetic
operators include:
+ (Addition)
Subtraction)
(Multiplication)
/ (Division)
Example:
SELECT 5 + 3 AS addition_result;
SELECT 10 - 4 AS subtraction_result;
SELECT 6 * 2 AS multiplication_result;
SELECT 20 / 4 AS division_result;
4. Aggregate Functions:
Aggregate functions in SQL operate on a set of values and return a single value. Commonly used
aggregate functions include:
Example:
Example :-
This SQL file creates a table of employees with columns for employee ID, name, hire date, and
salary. It then inserts some sample data.
Output :-
emp_info
------------------------------
John Doe is hired since 2020-01-15
Jane Smith is hired since 2019-05-20
Michael Johnson is hired since 2021-03-10
Emily Davis is hired since 2022-07-05
David Wilson is hired since 2023-02-28
2. Extracting year from date using date functions:
emp_name hire_year
John Doe 2020
Jane Smith 2019
Michael Johnson 2021
Emily Davis 2022
David Wilson 2023
avg_salary
----------
53000.00
EXPERIMENT NO. :- 05
Name of Experiment :- JOINS : study the use of joining tables using natural, inner, outer
joins.
Inner Join:
An inner join returns only the rows from both tables that satisfy the join condition. It combines
rows from two tables based on a related column (or columns) by comparing the values and
includes only the rows where the condition is true.
Syntax:
SELECT column_list
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
Example :-
Inner join returns rows when there is at least one match in both tables. Consider two tables,
"Employees" and "Departments":
Employees Table:
EmployeeID Name DepartmentID
1 John 1
2 Alice 2
3 Bob 1
4 Mary NULL
Departments Table:
DepartmentID DepartmentName
1 HR
2 IT
3 Finance
Outer Join:
Outer joins return all the rows from at least one of the tables specified in the FROM
clause, as long as the join condition is met.
There are three types of outer joins: LEFT OUTER JOIN, RIGHT OUTER JOIN, and
FULL OUTER JOIN.
Syntax:
SELECT column_list FROM table1 LEFT OUTER JOIN table2 ON table1.column =
table2.column;
SELECT column_list FROM table1 RIGHT OUTER JOIN table2 ON table1.column =
table2.column;
SELECT column_list FROM table1 FULL OUTER JOIN table2 ON table1.column =
table2.column;
Example :-
Outer joins return all rows from one table and matching rows from the other table. If there is no
match, NULL values are returned. There are three types: LEFT, RIGHT, and FULL.
Example SQL Query for Left Outer Join:
Name DepartmentName
John HR
Alice IT
Bob HR
Mary NULL
Natural Join:
A natural join is a type of join that automatically matches columns with the same name in both
tables. It eliminates the need to explicitly specify the columns to join on, but it can be risky if the
column names are not unique across tables.
Syntax:
SELECT column_list FROM table1 NATURAL JOIN table2;
Example :-
Natural join automatically matches columns with the same name in both tables. Consider the
same tables as before.
Example SQL Query for Natural Join:
SELECT Employees.Name, Employees.DepartmentID, Departments.DepartmentName
FROM Employees
NATURAL JOIN Departments;
Output:
Name DepartmentID DepartmentName
John 1 HR
Alice 2 IT
Bob 1 HR
Example of SQL Query – Inner Join , Natural Join , Outer Join
-- Create the Employee table
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Department_id VARCHAR(100) );
-- Insert sample data into the Employee table
INSERT INTO Employee (EmployeeID, Name, Department_id)
VALUES
(1, 'piyush', 'cs-1'),
(2, 'bonika', 'cs-2'),
(3, 'pradeep', 'civil-1'),
(4, 'prakash', 'ee-5');
-- Create the Department table
CREATE TABLE Department (
Department_id VARCHAR(100) PRIMARY KEY,
Name VARCHAR(100) );
-- Insert sample data into the Department table
INSERT INTO Department (Department_id, Name)
VALUES
('cs-1', 'Computer Science'),
('cs-2', 'Computer Science'),
('civil-1', 'Civil Engineering'),
('ee-5', 'Electrical Engineering');
-- Perform inner join
SELECT Employee.Name AS EmployeeName, Department.Name AS DepartmentName
FROM Employee
INNER JOIN Department ON Employee.Department_id = Department.Department_id;
-- Perform left join
SELECT Employee.EmployeeID, Employee.Name AS EmployeeName, Department.Name AS
DepartmentName
FROM Employee
LEFT JOIN Department ON Employee.Department_id = Department.Department_id;
-- Perform natural join (not recommended, but for demonstration)
SELECT Employee.Name AS EmployeeName, Employee.Department_id, Department.Name
AS DepartmentName
FROM Employee
NATURAL JOIN Department;
Output :-
Inner join
Natural Join :-
EXPERIMENT NO. :- 06
Name of Experiment :- Subqueries and set operations : Study the use of nested queries and
how to apply them in database.
Subqueries :
A subquery, also known as a nested query or inner query, is a query nested within another query.
It allows you to break down complex problems into smaller, more manageable parts. Subqueries
can be used in various clauses like SELECT, FROM, WHERE, etc.
SELECT name
FROM employees
WHERE department_id = (SELECT department_id FROM departments WHERE name =
'Sales');
In this example, the inner query (SELECT department_id FROM departments WHERE name =
'Sales') retrieves the department ID for the department named 'Sales'. This result is then used in
the outer query to find the names of employees who belong to the 'Sales' department.
Set Operations :
Set operations in SQL (Structured Query Language) are used to combine the results of two or
more SELECT queries. There are three main set operations: UNION, INTERSECT, and
EXCEPT (or MINUS, depending on the SQL dialect).
1. UNION: It combines the results of two or more SELECT statements into a single result set.
It removes duplicate rows by default.
2. INTERSECT: It returns only the rows that appear in both result sets of two SELECT
statements.
Example:
Let's say we have two tables, employees and managers. We want to find the names of all
employees who are not managers. We can use the EXCEPT operator for this.
This will give us the names of all employees who are not managers by subtracting the set of
manager names from the set of all employee names.
Example :-
-- Create employees table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50),
department_id INT,
salary DECIMAL(10, 2)
);
Output :-
1. Subqueries:
a. Basic Subquery:
b. Correlated Subquery:
2. Set Operations:
a. UNION:
b. INTERSECT:
name
John Doe
Jane Smith
c. EXCEPT:
EXPERIMENT NO. :- 07
Name of Experiment :- Views : Study the use of inline and external views.
VIEWS :-
A view is often referred to as a virtual table. Views are created by using the
CREATE VIEW statement. After the view has been created, you can use the
following SQL commands to refer to that view:
SELECT
INSERT
INPUT
UPDATE
DELETE
Views can be created using CREATE
VIEW.
The syntax for the CREATE VIEW
statement is
Syntax:
CREATE VIEW <view_name> AS
SELECT columnname, columnname
FROM <table_name>
Where columnname = expression list;
Group By grouping criteria
Having predicate
Syntax:
Select columnname, columnname
From viewname;
Updating views :
Views can also be used for data manipulation(i.e. the user can perform the Insert,
Update and Delete operations).
Views on which data manipulation can be done are called Updatable Views.
When you give an updatable view name in the Update, Insert or Delete SQL
statement, modifications to data will be passed to the underlying table.
If the user want to Insert records with the help of a view, then the Primary
Key column/s and all the NOT
NULL columns must be included in the view.
The user can Update, Delete records with the help of a view even if
the Primary Key column and NOT
NULL column/s are excluded from the view definition.
In this case even though the Primary Key column/s as well as NOT NULL
columns are included in the View definition the view’s behavior will be as
follows:
In this case even though the Primary Key and NOT NULL columns are included in
the View definition the view’s behavior will be as follows:
• An Insert operation is not allowed.
• The Delete or Modify do not affect the Master Table.
• The view can be used to Modify the columns of the detail table included in the
view.
• If a Delete operation is executed on the view, the corresponding records from
the detail table will be deleted.
Destroying a view:
Example :-
Name VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);
DepartmentName VARCHAR(50) );
(2, 'HR'),
(3, 'Finance');
FROM (
FROM Employees
FROM Employees
Output :-
EXPERIMENT NO 8
Name of Experiment - Introduction to PL/ SQL : Pl/ SQL block, PL/ SQL statements, if else
statements, looping statements.
A procedure has a header and a body. The header consists of the name of the procedure
and the parameters or variables passed to the procedure. The body consists or
declaration section, execution section and exception section similar to a general PL/SQL
Block. A procedure is similar to an anonymous PL/SQL Block but it is named for
repeated usage.
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any value.
General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE [schema.]procedure name
(argument {IN, OUT, IN OUT} data type,…){Is, AS}
variable declaration;
constant declaration;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception PL/SQL block;
END;
Keywords and Parameters:
REPLACE – recreates the procedure if it already exists.
schema – is the schema to contain the procedure. The Oracle engine takes the default
schema to be the current schema, if it is omitted.
argument – is the name of an argument to the procedure. Parantheses can be omitted if
no arguments are present.
IN – specifies that a value for the argument must be specified when calling the
procedure.
OUT – specifies that the procedure passes a value for this argument back to its calling
environment after execution.
IN OUT – specifies tha a value for the argument must be specified when calling the
procedure and that the procedure passes a value for this argument back to its calling
environment after execution. By default it takes IN.
Data type – is the data type of an argument.
PL/SQL subprogram body is the definition of procedure consisting of PL/SQL
statements.
IS - marks the beginning of the body of the procedure and is similar to DECLARE in
anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration
section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR
REPLACE together the procedure is created if no other procedure with the same name
exists or the existing procedure is replaced with the current code.
The below example creates a procedure ‘employer_details’ which gives the details of
the employee.
1> CREATE OR REPLACE PROCEDURE employer_details
2> IS
3>CURSORemp_cur IS
4>SELECTfirst_name, last_name, salary FROM emp_tbl;
5>emp_recemp_cur%rowtype;
6> BEGIN
7>FORemp_rec in sales_cur
8> LOOP
9>dbms_Output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
10> || ' ' ||emp_cur.salary);
11> END LOOP;
12>END;
13> /
Output:
SET SERVEROUTPUT ON
DECLARE
i NUMBER;
counter NUMBER;
n NUMBER;
k NUMBER;
BEGIN
i := 2;
counter := 0;
n := 50;
k := n/2;
FOR i IN 1..k LOOP
IF (n%i := 0 ) THEN
counter := 1;
END IF;
IF (counter := 0) THEN
DBMS_OUTPUT.PUT_LINE(n||' is prime number');
END IF;
END LOOP;
END;
declare
a number;
rev number;
d number;
begin
a:=&a;
rev:=0;
while a>0
loop
d:=mod(a,10);
rev:=(rev*10)+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('no is'|| rev);
end;
/
OUTPUT:
SQL> @ REVERSE2.sql
Enter value for a: 536
old 6: a:=&a;
new 6: a:=536;
no is 635
declare
n number(4):=&n;
s number(4):=0;
r number(4);
begin
while n>0
loop
r:=mod(n,10);
s:=(s*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line(‘the reverse number is:’);
dbms_output.put_line(s);
end;
/
Execution:
SQL> @e:\plsql\rev.sql
Enter value for n: 457
old 2: n number(4):=&n;
new 2: n number(4):=457;
Conclusion:
apl/sql program is successfully executed to generate reverse number for given number.
1. IN
mysql> CREATE PROCEDURE in_2(IN value INT )BEGIN SELECT value; SET
value =100;SE
LECT value;END//
Query OK, 0 rows affected (0.00 sec)
+ +
| value |
+ +
| 100 |
+ +
1 row in set (0.00 sec)
Implicit cursors:
These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed. They are also created when a SELECT statement that
returns just one row is executed.
Explicit cursors:
They must be created when you are executing a SELECT statement that returns more
than one row. Even though the cursor stores multiple records, only one record can be
processed at a time, which is called as current row. When you fetch a row the current
row position moves to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way
they are accessed.
Output :-
EXPERIMENT NO – 10
Name of Experiment - Functions and procedures : Study the use of functions and procedures in
PL/ SQL programs.
Stored Procedures
What is a Stored Procedure?
A stored procedure or in simple a proc is a named PL/SQL block which performs one
or more specific task.
Declare
a number;
b number;
c number;
Begin
dbms_output.put_line('Enter a:');
a:=&a;
dbms_output.put_line('Enter b:');
b:=&b;
dbms_output.put_line('Enter c:');
c:=&C;
if (a>b) and (a>c)
then
dbms_output.put_line('A is GREATEST'||A);
elsif (b>a) and (b>c)
then
dbms_output.put_line('B is GREATEST'||B);
else
dbms_output.put_line('C is GREATEST'||C);
end if;
End;
DECLARE
n number(3);
s number(3):=0;
t number(3);
BEGIN
n:=&n;
t:=n;
while t>0 loop
s:=s+power((t mod 10),3);
t:=trunc(t/10);
end loop;
if(s=n) then
dbms_output.put_line('The Given Number ' || n || ' is an Armstrong Number');
else
dbms_output.put_line('The Given Number ' || n || ' is Not an Armstrong Number');
end if;
END;
OUTPUT:
Triggers
Triggers are simply stored procedures that are ran automatically by the database
whenever some event (usually a table update) happens.
Triggers are basically PL/SQL procedures that are associated with tables, and are called
whenever a certain modification (event) occurs. The modification statements may
include INSERT, UPDATE, and DELETE.
END;
where:
Example:
Sample Table to be Triggered
Before we begin playing with triggers, let’s create a simple table with which we can
experiment:
The above creates a PERSON table with an ID, a NAME and a DOB columns (fields).
Whatever triggers we define in these notes will relate to this table.
Viewing Triggers
You can see all your user defined triggers by doing a select statement on
USER_TRIGGERS.
For example:
SELECT TRIGGER_NAME FROM USER_TRIGGERS;
Which produces the names of all triggers. You can also select more columns to get more
detailed trigger information.
Dropping Triggers
You can DROP triggers just like anything. The general format would be something like:
(a) Create a trigger before/after update on employee table for each row/statement
SET serveroutput ON
DECLARE
CURSOR cur_emp
IS\
(b) Create a trigger before/after delete on employee table for each row/statement
creates a DML trigger that uses conditional predicates to determine which of its four
possible triggering statements fired it.
(c) Create a trigger before/after insert on employee table for each row/statement.
creates a log table and a trigger that inserts a row in the log table after any UPDATE
statement affects the SALARY column of the EMPLOYEES table, and then updates
EMPLOYEES.SALARY and shows the log table.
IF v_count = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee does not exist');
END IF;
END;
/
BEGIN
INSERT INTO salaries (salary_id, employee_id, salary_amount) VALUES (1, 1001,
50000);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/
Output :-