0% found this document useful (0 votes)
5 views16 pages

Digital Assignment 1. Creating Tables

Uploaded by

K K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Digital Assignment 1. Creating Tables

Uploaded by

K K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

DIGITAL ASSIGNMENT

1. Creating Tables

Example: Creating the departments Table

sql
Copy code
CREATE TABLE departments (
dept_id NUMBER(5) PRIMARY KEY, -- Primary Key Constraint
dept_name VARCHAR2(50) UNIQUE -- Unique Constraint
);

Example: Creating the employees Table with Constraints

sql
Copy code
CREATE TABLE employees (
emp_id NUMBER(5) PRIMARY KEY, -- Primary Key Constraint
first_name VARCHAR2(20) NOT NULL, -- NOT NULL Constraint
last_name VARCHAR2(20) NOT NULL, -- NOT NULL Constraint
salary NUMBER(10, 2) CHECK (salary > 5000), -- CHECK Constraint
dob DATE NOT NULL, -- Date of Birth
dept_id NUMBER(5), -- Foreign Key Column
CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES
departments(dept_id) -- Foreign Key Constraint
);

2. Inserting Data

Example: Adding Records to Tables

sql
Copy code
-- Insert into departments
INSERT INTO departments VALUES (1, 'HR');
INSERT INTO departments VALUES (2, 'IT');
INSERT INTO departments VALUES (3, 'Finance');

-- Insert into employees


INSERT INTO employees VALUES (101, 'Alice', 'Johnson', 6000.00,
TO_DATE('1990-06-15', 'YYYY-MM-DD'), 1);
INSERT INTO employees VALUES (102, 'Bob', 'Smith', 7500.00, TO_DATE('1985-
09-20', 'YYYY-MM-DD'), 2);
INSERT INTO employees VALUES (103, 'Charlie', 'Brown', 8000.00,
TO_DATE('1992-11-30', 'YYYY-MM-DD'), 3);

3. Querying Data

Basic Query

Retrieve names and salaries of all employees.


sql
Copy code
SELECT first_name, last_name, salary FROM employees;

4. Joins

INNER JOIN

Combine employees and departments to get department names for each employee.

sql
Copy code
SELECT
e.first_name,
e.salary,
d.dept_name
FROM
employees e
INNER JOIN
departments d
ON
e.dept_id = d.dept_id;

SELF JOIN

Find colleagues of Alice in the same department.

sql
Copy code
SELECT
e1.first_name AS employee,
e2.first_name AS colleague
FROM
employees e1
JOIN
employees e2
ON
e1.dept_id = e2.dept_id
WHERE
e1.first_name = 'Alice' AND e1.emp_id != e2.emp_id;

5. ALTER TABLE Operations

a. Add a Column

sql
Copy code
ALTER TABLE employees ADD hire_date DATE;

b. Modify a Column

Change the datatype or constraints of an existing column.


sql
Copy code
ALTER TABLE employees MODIFY salary NUMBER(12, 2);

c. Drop a Column

Remove a column from a table.

sql
Copy code
ALTER TABLE employees DROP COLUMN bonus;

d. Rename a Column

Rename an existing column (supported in databases like MySQL and PostgreSQL).

sql
Copy code
ALTER TABLE employees RENAME COLUMN hire_date TO joining_date;

e. Add a Constraint

Add a new constraint to a column.

sql
Copy code
ALTER TABLE employees ADD CONSTRAINT chk_salary CHECK (salary <= 20000);

f. Drop a Constraint

Remove an existing constraint.

sql
Copy code
ALTER TABLE employees DROP CONSTRAINT chk_salary;

g. Rename the Table

Rename an entire table.

sql
Copy code
RENAME employees TO employee_data;

6. Constraints

a. NOT NULL

Ensures a column cannot have NULL values.

sql
Copy code
ALTER TABLE employees MODIFY first_name VARCHAR2(20) NOT NULL;

b. UNIQUE

Ensures all values in a column are unique.

sql
Copy code
ALTER TABLE employees ADD CONSTRAINT unique_last_name UNIQUE (last_name);

c. PRIMARY KEY

Ensures a column (or set of columns) uniquely identifies each row.

sql
Copy code
ALTER TABLE employees ADD CONSTRAINT pk_emp_id PRIMARY KEY (emp_id);

d. FOREIGN KEY

Links a column to another table’s column, maintaining referential integrity.

sql
Copy code
ALTER TABLE employees ADD CONSTRAINT fk_dept FOREIGN KEY (dept_id)
REFERENCES departments(dept_id);

e. CHECK

Ensures values meet specific conditions.

sql
Copy code
ALTER TABLE employees ADD CONSTRAINT chk_salary_positive CHECK (salary >
0);

f. DEFAULT

Assigns a default value to a column when no value is provided.

sql
Copy code
ALTER TABLE employees ADD hire_date DATE DEFAULT SYSDATE;

7. Aggregate Functions

Calculate Total and Average Salary

sql
Copy code
SELECT
AVG(salary) AS average_salary,
SUM(salary) AS total_salary
FROM employees;

Group by Department

sql
Copy code
SELECT
d.dept_name,
SUM(e.salary) AS total_salary,
AVG(e.salary) AS average_salary
FROM
employees e
INNER JOIN
departments d
ON
e.dept_id = d.dept_id
GROUP BY
d.dept_name;

8. Date Functions

Calculate Employee Ages

sql
Copy code
SELECT
first_name,
FLOOR(MONTHS_BETWEEN(SYSDATE, dob) / 12) AS age
FROM employees;

Filter by Hire Date

Retrieve employees hired after January 1, 2020.

sql
Copy code
SELECT first_name, hire_date
FROM employees
WHERE hire_date > TO_DATE('2020-01-01', 'YYYY-MM-DD');

9. Subqueries

Employees Earning Above the Average Salary

sql
Copy code
SELECT first_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

10. Views
Create a View for High-Salary Employees

sql
Copy code
CREATE VIEW high_salary_employees AS
SELECT first_name, last_name, salary
FROM employees
WHERE salary > 7000;

Drop the View

sql
Copy code
DROP VIEW high_salary_employees;

11. Summary Table

Operation Purpose Example


ALTER TABLE Add new columns to a ALTER TABLE employees ADD hire_date
Add table DATE;
ALTER TABLE Modify existing column ALTER TABLE employees MODIFY salary
Modify properties NUMBER(12, 2);
ALTER TABLE ALTER TABLE employees DROP COLUMN
Drop Remove a column bonus;
ALTER TABLE Add a foreign key ALTER TABLE employees ADD CONSTRAINT
Add FK constraint fk_dept ...;
ALTER TABLE ALTER TABLE employees ADD CONSTRAINT
Add CK Add a check constraint chk_salary ...;

INNER JOIN Combine rows from JOIN employees ON dept_id = dept_id


multiple tables
Compare rows within the JOIN employees e1 ON e1.dept_id =
SELF JOIN
same table e2.dept_id

GROUP BY Group rows for aggregate GROUP BY dept_name


calculations
HAVING
Filter groups after HAVING SUM(salary) > 15000
aggregation
Perform date-based MONTHS_BETWEEN(SYSDATE, dob)
DATE Functions
calculations
VIEW Create reusable virtual CREATE VIEW high_salary_employees ...;
tables
PL/SQL
Basic PL/SQL Syntax
sql
Copy code
BEGIN
-- Your PL/SQL code here
END;
/

Declaring Variables
sql
Copy code
DECLARE
v_salary NUMBER; -- Declaring a variable
BEGIN
v_salary := 1000; -- Assigning a value
DBMS_OUTPUT.PUT_LINE('Salary is: ' || v_salary); -- Printing output
END;
/

Working with Tables

Example Table: employee


sql
Copy code
CREATE TABLE employee (
empno NUMBER PRIMARY KEY,
empname VARCHAR2(50),
age NUMBER,
salary NUMBER,
department VARCHAR2(50)
);

-- Insert Sample Data


INSERT INTO employee VALUES (1, 'John Doe', 30, 3000, 'HR');
INSERT INTO employee VALUES (2, 'Jane Smith', 45, 5000, 'Finance');
INSERT INTO employee VALUES (3, 'Alice Johnson', 40, 4000, 'IT');
INSERT INTO employee VALUES (4, 'Bob Brown', 35, 4500, 'IT');
COMMIT;

Basic SELECT and Assignment

Fetch data from the table and assign it to a variable.


sql
Copy code
DECLARE
v_salary NUMBER;
v_name VARCHAR2(50);
BEGIN
SELECT salary, empname
INTO v_salary, v_name
FROM employee
WHERE empno = 1;

DBMS_OUTPUT.PUT_LINE('Name: ' || v_name || ', Salary: ' || v_salary);


END;
/

Control Structures

IF-ELSE
sql
Copy code
DECLARE
v_salary NUMBER := 3000;
BEGIN
IF v_salary > 4000 THEN
DBMS_OUTPUT.PUT_LINE('High salary');
ELSE
DBMS_OUTPUT.PUT_LINE('Low salary');
END IF;
END;
/

Loops

FOR Loop

sql
Copy code
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END;
/

WHILE Loop

sql
Copy code
DECLARE
i NUMBER := 1;
BEGIN
WHILE i <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
i := i + 1;
END LOOP;
END;
/

Cursors

Implicit Cursor Example

Oracle uses an implicit cursor for single SQL operations like SELECT, INSERT, UPDATE.

sql
Copy code
DECLARE
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employee;
DBMS_OUTPUT.PUT_LINE('Total Employees: ' || v_count);
END;
/

Explicit Cursor

An explicit cursor allows row-by-row processing for queries returning multiple rows.

Example: Fetch Employee Data

sql
Copy code
DECLARE
CURSOR emp_cursor IS SELECT empname, salary FROM employee;
v_name VARCHAR2(50);
v_salary NUMBER;
BEGIN
OPEN emp_cursor;

LOOP
FETCH emp_cursor INTO v_name, v_salary;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_name || ', Salary: ' ||
v_salary);
END LOOP;

CLOSE emp_cursor;
END;
/

Procedures

What is a Procedure?

A procedure is a named PL/SQL block stored in the database that performs a specific task.

Create Procedure

sql
Copy code
CREATE OR REPLACE PROCEDURE get_employee_salary (p_empno IN NUMBER) IS
v_salary NUMBER;
BEGIN
SELECT salary INTO v_salary FROM employee WHERE empno = p_empno;
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);
END;
/

Call the Procedure

sql
Copy code
BEGIN
get_employee_salary(1); -- Replace 1 with the desired employee number
END;
/

Functions

What is a Function?

A function is similar to a procedure but returns a value.

Create Function

sql
Copy code
CREATE OR REPLACE FUNCTION get_department_count(p_department IN VARCHAR2)
RETURN NUMBER IS
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employee WHERE department =
p_department;
RETURN v_count;
END;
/

Call the Function

sql
Copy code
DECLARE
v_count NUMBER;
BEGIN
v_count := get_department_count('IT');
DBMS_OUTPUT.PUT_LINE('Number of employees in IT: ' || v_count);
END;
/

Triggers

What is a Trigger?

A trigger is a stored PL/SQL block that automatically executes in response to an event on a


table.
Trigger Types

1. BEFORE INSERT
2. AFTER INSERT
3. BEFORE UPDATE
4. AFTER DELETE

Example Trigger: Log Employee Deletion

Create a Log Table

sql
Copy code
CREATE TABLE employee_log (
empno NUMBER,
empname VARCHAR2(50),
action VARCHAR2(20),
action_date DATE
);

Create the Trigger

sql
Copy code
CREATE OR REPLACE TRIGGER log_employee_deletion
AFTER DELETE ON employee
FOR EACH ROW
BEGIN
INSERT INTO employee_log (empno, empname, action, action_date)
VALUES (:OLD.empno, :OLD.empname, 'DELETE', SYSDATE);
END;
/

Test the Trigger

sql
Copy code
DELETE FROM employee WHERE empno = 1;
SELECT * FROM employee_log; -- Check the log table

Exception Handling

Handle Errors Gracefully


sql
Copy code
DECLARE
v_salary NUMBER;
BEGIN
SELECT salary INTO v_salary FROM employee WHERE empno = 999; -- Non-
existent empno
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Query returned multiple rows.');
END;
/

CODES

1. Reverse Counting from 100 to 1

This program demonstrates the use of a loop to count in reverse.

sql
Copy code
SET SERVEROUTPUT ON;
BEGIN
FOR i IN REVERSE 1..100 LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
/

2. Fibonacci Series

This program generates a Fibonacci sequence up to n terms.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
a NUMBER := 0;
b NUMBER := 1;
n NUMBER := &n; -- Number of terms
c NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE(a); -- First term
DBMS_OUTPUT.PUT_LINE(b); -- Second term

FOR i IN 3..n LOOP


c := a + b;
DBMS_OUTPUT.PUT_LINE(c);
a := b;
b := c;
END LOOP;
END;
/

3. Factorial of a Number

This program calculates the factorial of a given number n.


sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
n NUMBER := &n; -- Input number
factorial NUMBER := 1;
BEGIN
FOR i IN 1..n LOOP
factorial := factorial * i;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Factorial of ' || n || ' is: ' || factorial);
END;
/

4. Check if a Number is Prime

This program checks if a number is prime.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := &num; -- Input number
is_prime BOOLEAN := TRUE;
BEGIN
IF num <= 1 THEN
is_prime := FALSE;
ELSE
FOR i IN 2..FLOOR(SQRT(num)) LOOP
IF MOD(num, i) = 0 THEN
is_prime := FALSE;
EXIT;
END IF;
END LOOP;
END IF;

IF is_prime THEN
DBMS_OUTPUT.PUT_LINE(num || ' is a prime number.');
ELSE
DBMS_OUTPUT.PUT_LINE(num || ' is not a prime number.');
END IF;
END;
/

5. Sum of Digits of a Number

This program calculates the sum of the digits of a number.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := &num; -- Input number
digit NUMBER;
sum_digits NUMBER := 0;
BEGIN
WHILE num > 0 LOOP
digit := MOD(num, 10); -- Extract the last digit
sum_digits := sum_digits + digit;
num := TRUNC(num / 10); -- Remove the last digit
END LOOP;

DBMS_OUTPUT.PUT_LINE('Sum of digits is: ' || sum_digits);


END;
/

6. Check Even or Odd

This program checks whether a number is even or odd.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := &num; -- Input number
BEGIN
IF MOD(num, 2) = 0 THEN
DBMS_OUTPUT.PUT_LINE(num || ' is even.');
ELSE
DBMS_OUTPUT.PUT_LINE(num || ' is odd.');
END IF;
END;
/

7. Greatest of Three Numbers

This program finds the largest of three numbers.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
a NUMBER := &a; -- First number
b NUMBER := &b; -- Second number
c NUMBER := &c; -- Third number
greatest NUMBER;
BEGIN
greatest := CASE
WHEN a > b AND a > c THEN a
WHEN b > c THEN b
ELSE c
END;

DBMS_OUTPUT.PUT_LINE('The greatest number is: ' || greatest);


END;
/

8. Sum of Series: 1 + 3 + 5 + ... + n

This program calculates the sum of an odd number series up to n.


sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
n NUMBER := &n; -- Last term in the series
sum NUMBER := 0;
i NUMBER := 1;
BEGIN
WHILE i <= n LOOP
sum := sum + i;
i := i + 2; -- Move to the next odd number
END LOOP;

DBMS_OUTPUT.PUT_LINE('Sum of series is: ' || sum);


END;
/

9. Reverse a Number

This program reverses a given number.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := &num; -- Input number
reverse_num NUMBER := 0;
digit NUMBER;
BEGIN
WHILE num > 0 LOOP
digit := MOD(num, 10); -- Extract the last digit
reverse_num := reverse_num * 10 + digit;
num := TRUNC(num / 10); -- Remove the last digit
END LOOP;

DBMS_OUTPUT.PUT_LINE('Reversed number is: ' || reverse_num);


END;
/

10. Generate Multiplication Table

This program generates the multiplication table for a number.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := &num; -- Input number
BEGIN
FOR i IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(num || ' x ' || i || ' = ' || (num * i));
END LOOP;
END;
/
11. Check Palindrome Number

This program checks whether a number is a palindrome.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
num NUMBER := &num; -- Input number
original_num NUMBER := num;
reverse_num NUMBER := 0;
digit NUMBER;
BEGIN
WHILE num > 0 LOOP
digit := MOD(num, 10); -- Extract the last digit
reverse_num := reverse_num * 10 + digit;
num := TRUNC(num / 10); -- Remove the last digit
END LOOP;

IF reverse_num = original_num THEN


DBMS_OUTPUT.PUT_LINE(original_num || ' is a palindrome.');
ELSE
DBMS_OUTPUT.PUT_LINE(original_num || ' is not a palindrome.');
END IF;
END;
/

12. Calculate the Sum of First n Natural Numbers

This program calculates the sum of the first n natural numbers.

sql
Copy code
SET SERVEROUTPUT ON;
DECLARE
n NUMBER := &n; -- Input number
sum NUMBER := 0;
BEGIN
FOR i IN 1..n LOOP
sum := sum + i;
END LOOP;

DBMS_OUTPUT.PUT_LINE('Sum of first ' || n || ' natural numbers is: ' ||


sum);
END;
/

You might also like