Dbms Notes Unit 3 - Set 2
Dbms Notes Unit 3 - Set 2
operations,
SQL functions(Date and Time, Numeric, String conversion).Creating tables with relationship, implementation
of key and integrity constraints, nested queries, sub queries, grouping, aggregation, ordering, implementation of
different types of joins, view(updatable and non-updatable), relational set operations.
Basic SQL Querying: SELECT and PROJECT using WHERE Clause
SELECT → Retrieves specific columns (projection).
[Link]@[Link]
Output
name age
Bob 35
Query
SELECT name, department FROM employees WHERE department = 'Sales' OR department = 'Marketing';
Output
name department
David Sales
Eve Marketing
[Link]@[Link]
Charlie IT
Bob HR
[Link]@[Link]
1. Single Row, Single Column:
o It has only one row and one column (DUMMY) containing the value 'X'.
o Run:
SELECT * FROM dual;
Output:
DUMMY
-----
X
2. Used for Function Calls & Expressions:
o Since it contains a single row, any function or calculation using DUAL returns just one result.
o Example:
SELECT SYSDATE FROM dual;
Output (Example):
SYSDATE
---------
11-MAR-25
3. Virtual Table (No Storage Needed):
o Oracle automatically optimizes queries on DUAL, making it efficient for quick calculations.
Common Uses of DUAL Table:
Use Case Example Output (Sample)
Get Current Date SELECT SYSDATE FROM dual; 11-MAR-25
Evaluate Expressions SELECT 10 * 5 FROM dual; 50
Get System User SELECT USER FROM dual; HR
Convert Strings SELECT TO_DATE('2025-12-31', 'YYYY-MM-DD') FROM dual; 31-DEC-25
Note: In Oracle 21c and later, DUAL is no longer needed for function calls;
SELECT SYSDATE;
works directly.
[Link]@[Link]
SYSTIMESTAMP Returns the current SELECT SYSTIMESTAMP 11-MAR-25
timestamp with time FROM dual; [Link].123456
zone +05:30
CURRENT_DATE Returns the current SELECT CURRENT_DATE 11-MAR-25
date in the session's FROM dual;
time zone
CURRENT_TIMESTAMP Returns the current SELECT 11-MAR-25
timestamp with CURRENT_TIMESTAMP [Link].123456
session's time zone FROM dual; +05:30
3. Date Arithmetic
Function Description Example Output
(Sample)
ADD_MONTHS(date, n) Adds n months SELECT ADD_MONTHS(SYSDATE, 3) 11-JUN-
to a date FROM dual; 25
NEXT_DAY(date, 'DAY') Returns the next SELECT NEXT_DAY(SYSDATE, 17-MAR-
occurrence of a 'Monday') FROM dual; 25
specific day
LAST_DAY(date) Returns the last SELECT LAST_DAY(SYSDATE) FROM 31-MAR-
day of the month dual; 25
MONTHS_BETWEEN(date1, Returns the SELECT 14.33
date2) number of MONTHS_BETWEEN(SYSDATE,
months between TO_DATE('2024-01-01', 'YYYY-MM-DD'))
two dates FROM dual;
[Link]@[Link]
4. Date Formatting with TO_CHAR
Format Description Example Output
(Sample)
'YYYY' Year (4 digits) SELECT TO_CHAR(SYSDATE, 'YYYY') FROM 2025
dual;
'MM' Month (2 digits) SELECT TO_CHAR(SYSDATE, 'MM') FROM dual; 03
'DD' Day (2 digits) SELECT TO_CHAR(SYSDATE, 'DD') FROM dual; 11
'DAY' Full day name SELECT TO_CHAR(SYSDATE, 'DAY') FROM dual; TUESDAY
'DY' Short day name SELECT TO_CHAR(SYSDATE, 'DY') FROM dual; TUE
'HH24:MI:SS' 24-hour time SELECT TO_CHAR(SYSDATE, 'HH24:MI:SS') [Link]
format FROM dual;
[Link]@[Link]
LOG(b, n) Returns log of n to base b SELECT LOG(10, 1000) FROM dual; 3
EXP(n) Returns e^n SELECT EXP(1) FROM dual; 2.7183
[Link]@[Link]
3. Convert Strings to Dates (TO_DATE)
Function Description Example Output
TO_DATE('2025-03-11', Converts string to SELECT TO_DATE('2025-03-11', 'YYYY- 11-MAR-
'YYYY-MM-DD') date MM-DD') FROM dual; 25
TO_DATE('11-MAR-25', 'DD- Converts another SELECT TO_DATE('11-MAR-25', 'DD- 11-MAR-
MON-YY') format MON-YY') FROM dual; 25
[Link]@[Link]
emp_name VARCHAR2(100) NOT NULL,
salary NUMBER(10,2),
dept_id NUMBER,
CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);
Foreign Key (dept_id) links to departments.dept_id, ensuring referential integrity.
[Link]@[Link]
emp_name VARCHAR2(100) NOT NULL,
dept_id NUMBER,
CONSTRAINT fk_dept FOREIGN KEY (dept_id) REFERENCES departments(dept_id) ON DELETE
CASCADE
);
If a department is deleted, all related employees will also be deleted.
Implementation of Keys and Integrity Constraints in Oracle
Oracle provides keys and integrity constraints to maintain data accuracy and consistency. These constraints
ensure that database rules are enforced.
[Link]@[Link]
CONSTRAINT fk_course FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
student_id and course_id must exist in the referenced tables (students and courses).
4. UNIQUE Constraint
Ensures all values in a column are unique (but allows NULLs).
Example:
CREATE TABLE customers (
customer_id NUMBER PRIMARY KEY,
email VARCHAR2(150) UNIQUE -- Each email must be unique
);
Duplicate emails are not allowed, but NULL is allowed.
5. CHECK Constraint
Enforces a condition on column values.
Example:
CREATE TABLE products (
product_id NUMBER PRIMARY KEY,
price NUMBER CHECK (price > 0) -- Price must be greater than 0
);
Prevents negative or zero prices.
6. DEFAULT Constraint
Assigns a default value when no value is provided.
[Link]@[Link]
Example:
CREATE TABLE orders (
order_id NUMBER PRIMARY KEY,
status VARCHAR2(20) DEFAULT 'Pending' -- Default status is 'Pending'
);
If no status is provided, it defaults to 'Pending'.
[Link]@[Link]
Nested Queries (Subqueries) in Oracle
A nested query (subquery) is a query inside another SQL query. It is used to fetch data based on the result
of another query.
[Link]@[Link]
The subquery calculates the overall average salary, and the outer query filters departments with
higher averages.
5. Correlated Subquery
Retrieves employees earning more than the average salary of their department.
SELECT emp_name, salary, dept_id
FROM employees e1
WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.dept_id = e2.dept_id);
The inner query depends on the outer query (correlated subquery).
7. IN with Subquery
Retrieves employees who work in HR or IT.
SELECT emp_name
FROM employees
WHERE dept_id IN (SELECT dept_id FROM departments WHERE dept_name IN ('HR', 'IT'));
The subquery returns department IDs, and the outer query selects employees from those departments.
[Link]@[Link]
Difference Between Nested Queries and Subqueries in Oracle
Feature Subquery Nested Query
Definition A query inside another query. A subquery inside another subquery.
Depth Single level of nesting. Multi-level nesting (subqueries within
subqueries).
Complexity Simpler, usually used once inside a query. More complex, with multiple layers of
subqueries.
Execution Inner query executes first, then outer Inner-most subquery executes first, then the next,
query. and so on.
Performance Generally faster and easier to optimize. Can be slower due to multiple levels of
execution.
Example WHERE, SELECT, FROM, HAVING, Advanced filtering, multi-step transformations.
Usage EXISTS, IN.
[Link]@[Link]
Innermost subquery: Calculates the company-wide average salary.
Middle subquery: Finds departments where the average salary is above the company average.
Outer query: Selects employees from those departments.
Note:
All nested queries are subqueries, but not all subqueries are nested queries.
Subqueries are used for single-level filtering.
Nested queries involve multiple subqueries for complex conditions.
[Link]@[Link]
Total Salary and Employee Count per Department
SELECT dept_id, COUNT(emp_id) AS emp_count, SUM(salary) AS total_salary
FROM employees
GROUP BY dept_id;
Output
dept_id emp_count total_salary
1 2 125000
2 2 127000
3 2 100000
[Link]@[Link]
Summary
Feature Query Example
Basic GROUP BY GROUP BY column_name
Multiple Columns GROUP BY col1, col2
Filtering Groups (HAVING) HAVING condition
Ordering Grouped Data ORDER BY aggregate_function()
COUNT(), SUM(), AVG() Aggregates values in groups.
ROLLUP Adds hierarchical totals.
CUBE Creates all possible combinations of grouping.
GROUPING SETS Custom grouping combinations.
[Link]@[Link]
4. COUNT() – Counting Records
Find the number of employees per department.
SELECT dept_id, COUNT(*) AS num_employees
FROM employees
GROUP BY dept_id;
COUNT(*) counts all rows, while COUNT(column) ignores NULL values.
[Link]@[Link]
SELECT COUNT(DISTINCT job_title) AS unique_jobs FROM employees;
COUNT(DISTINCT column) counts unique values.
[Link]@[Link]
102 Bob 60000
105 Emma 65000
104 David 72000
[Link]@[Link]
101 Alice 55000
102 Bob NULL
103 Charlie 48000
104 David NULL
105 Emma 65000
Sorting by salary (ASC):
SELECT emp_id, emp_name, salary FROM employees
ORDER BY salary ASC;
Output (NULLs Last by Default)
emp_id emp_name salary
103 Charlie 48000
101 Alice 55000
105 Emma 65000
102 Bob NULL
104 David NULL
Sorting NULLs first:
SELECT emp_id, emp_name, salary FROM employees
ORDER BY salary ASC NULLS FIRST;
Output (NULLs First)
emp_id emp_name salary
102 Bob NULL
104 David NULL
103 Charlie 48000
101 Alice 55000
105 Emma 65000
[Link]@[Link]
Implementation of Different Types of Joins in Oracle SQL
Joins in Oracle SQL are used to combine data from multiple tables based on a related column. There are
different types of joins:
[Link]@[Link]
-> Combines LEFT JOIN and RIGHT JOIN.
6. SELF JOIN
Joins a table with itself using aliases.
Example: Find each employee and their manager.
SELECT e1.emp_name AS employee, e2.emp_name AS manager
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.emp_id;
-> Employees and managers are both from the employees table.
Implementation of Different Types of Joins in Oracle SQL with Sample Tables and Output
Joins are used to combine data from multiple tables based on a related column.
Sample Tables
1. Employees Table
[Link]@[Link]
emp_id emp_name dept_id manager_id
101 Alice 1 103
102 Bob 2 104
103 Charlie NULL NULL
104 David 1 NULL
2. Departments Table
dept_id dept_name
1 HR
2 IT
3 Finance
[Link]@[Link]
3⃣ RIGHT JOIN (All Departments, Even Without Employees)
[Link]@[Link]
Alice HR
Alice IT
Alice Finance
Bob HR
Bob IT
Bob Finance
Charlie HR
Charlie IT
Charlie Finance
David HR
David IT
David Finance
Summary of Joins
Join Type Description Example Output
INNER Matches rows in both tables. Employees with departments.
JOIN
LEFT JOIN All left table rows + matched right table rows. All employees, even without
departments.
RIGHT All right table rows + matched left table rows. All departments, even without
JOIN employees.
[Link]@[Link]
FULL JOIN All rows from both tables (NULLs for no matches). All employees & all departments.
CROSS Every row from Table A with every row from Table All employee-department combinations.
JOIN B.
SELF JOIN Joins a table with itself. Employees and their managers.
1. Updatable Views
An updatable view allows INSERT, UPDATE, and DELETE operations.
Conditions for Updatable Views
Must be based on a single table.
Must not contain GROUP BY, DISTINCT, JOIN, or aggregate functions.
CREATE VIEW updatable_emp_view AS
SELECT emp_id, emp_name, dept_id
FROM employees
WHERE dept_id IS NOT NULL;
Updating Data Through the View
UPDATE updatable_emp_view
SET emp_name = 'Alice Cooper'
WHERE emp_id = 101;
[Link]@[Link]
This updates the original employees table.
Inserting Data
INSERT INTO updatable_emp_view (emp_id, emp_name, dept_id)
VALUES (105, 'Eve', 3);
A new row is added to employees.
Deleting Data
DELETE FROM updatable_emp_view WHERE emp_id = 102;
Deletes row from employees.
2. Non-Updatable Views
A non-updatable view does not allow INSERT, UPDATE, or DELETE operations.
Reasons for Non-Updatable Views
Uses multiple tables (JOINs).
Includes GROUP BY, DISTINCT, or aggregate functions like SUM, AVG.
CREATE VIEW dept_summary AS
SELECT d.dept_name, COUNT(e.emp_id) AS emp_count
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id
GROUP BY d.dept_name;
Querying the View
SELECT * FROM dept_summary;
Output
dept_name emp_count
HR 2
IT 1
Trying to Update Will Fail
UPDATE dept_summary SET emp_count = 10 WHERE dept_name = 'HR';
This will result in an error because non-updatable views cannot be modified.
[Link]@[Link]
Difference Between Updatable and Non-Updatable Views in Oracle
Feature Updatable View Non-Updatable View
Modification (INSERT, UPDATE, Allowed Not Allowed
DELETE)
Based on Multiple Tables No Yes (with JOINs)
Contains Aggregations (SUM, AVG, No Yes
COUNT, etc.)
Contains DISTINCT or GROUP BY No Yes
Contains Subqueries No Yes (Common in reporting)
Example Use Case Updating employee Generating department-wise
details employee count
Relational Set Operations in Oracle
Relational set operations combine results from multiple queries. Oracle supports the following set operations:
Operation Description
UNION Combines results from two queries, removing duplicates.
UNION ALL Combines results from two queries, keeping duplicates.
INTERSECT Returns common rows between two queries.
MINUS Returns rows from the first query that are not in the second query.
Example Tables
employees Table
emp_id emp_name dept_id
101 Alice 1
102 Bob 2
103 Charlie 3
104 David 4
managers Table
emp_id emp_name dept_id
102 Bob 2
103 Charlie 3
105 Emma 5
[Link]@[Link]
SELECT emp_id, emp_name FROM employees
UNION
SELECT emp_id, emp_name FROM managers;
Output
emp_id emp_name
101 Alice
102 Bob
103 Charlie
104 David
105 Emma
[Link]@[Link]
103 Charlie
3. SQL Functions
a) Date and Time Functions
NOW(), CURDATE(), CURTIME(), YEAR(), MONTH(), DAY(), DATE_ADD(), DATEDIFF().
Example:
SELECT NOW(), YEAR(CURDATE()), DATEDIFF('2025-01-01', CURDATE());
b) Numeric Functions
ABS(), ROUND(), CEIL(), FLOOR(), MOD(), POWER(), SQRT().
[Link]@[Link]
Example:
SELECT ROUND(25.678, 2), SQRT(16), MOD(10, 3);
c) String Conversion Functions
UPPER(), LOWER(), CONCAT(), SUBSTRING(), LENGTH(), TRIM().
Example:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
8. Joins in SQL
INNER JOIN: Returns matching records.
LEFT JOIN: Returns all records from the left table + matched ones from the right.
RIGHT JOIN: Returns all records from the right table + matched ones from the left.
FULL JOIN: Returns all records if a match is found in either table.
Example:
[Link]@[Link]
SELECT e.emp_name, d.dept_name
FROM Employee e INNER JOIN Department d ON e.dept_id = d.dept_id;
Conclusion:
-> Use SELECT, WHERE, GROUP BY, ORDER BY for basic queries.
-> Functions like ROUND(), CONCAT(), NOW() enhance SQL operations.
-> Joins and subqueries improve data retrieval.
-> Constraints (PK, FK, NOT NULL) maintain data integrity.
-> Views simplify complex queries.
-> Set operations (UNION, INTERSECT) help combine datasets.
[Link]@[Link]