UNIT III – BSC CS
1. Data Management and Retrieval
Data Manipulation Language (DML) in SQL
DML commands are used to manipulate data within SQL tables. The primary DML commands
include INSERT, UPDATE, DELETE, and SELECT. Below is a detailed explanation of these
operations:
1. Adding a New Row/Record (INSERT INTO)
Syntax:
Sql:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
Sql:
INSERT INTO employees (employee_id, first_name, last_name, salary)
VALUES (101, 'John', 'Doe', 50000);
Explanation:
Operation: The INSERT INTO command adds a new row/record to a table.
In this example: A new record is added to the employees table with employee_id as
101, first_name as 'John', last_name as 'Doe', and salary as 50,000.
2. Customized Prompts – Using INSERT INTO with User Input
Customized prompts involve dynamically inserting data into a table, often through user input.
This can be done in environments that support user interaction, such as SQL scripts or
applications.
Example:
Sql:
INSERT INTO employees (employee_id, first_name, last_name, salary)
VALUES (&emp_id, '&first_name', '&last_name', &salary);
Explanation:
Operation: The & symbol is used in SQL scripts (like Oracle SQL*Plus) to prompt the
user to input the values during execution.
In this example: When the script runs, it prompts the user to enter emp_id, first_name,
last_name, and salary, and then inserts those values into the employees table.
3. Updating an Existing Row/Record (UPDATE)
Syntax:
Sql:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
Sql:
UPDATE employees
SET salary = 55000
WHERE employee_id = 101;
Explanation:
Operation: The UPDATE command modifies existing data in a table.
In this example: The salary of the employee with employee_id 101 is updated to
55,000. The WHERE clause specifies which record to update. Without the WHERE clause, all
rows in the table would be updated.
4. Deleting an Existing Row/Record (DELETE)
Syntax:
Sql:
DELETE FROM table_name WHERE condition;
Example:
Sql:
DELETE FROM employees
WHERE employee_id = 101;
Explanation:
Operation: The DELETE command removes existing records from a table.
In this example: The record of the employee with employee_id 101 is deleted from the
employees table. The WHERE clause specifies which record to delete. Without the WHERE
clause, all records in the table would be deleted.
5. Retrieving Data from a Table (SELECT)
Syntax:
Sql:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
Sql:
SELECT first_name, last_name, salary
FROM employees
WHERE salary > 50000;
Explanation:
Operation: The SELECT command retrieves data from a table.
In this example: The query retrieves the first_name, last_name, and salary of
employees whose salary is greater than 50,000. The WHERE clause filters the results to
include only those rows that meet the specified condition.
These DML commands are fundamental for managing and interacting with data stored in SQL
tables, allowing for the insertion, updating, deletion, and retrieval of data effectively.
e. Arithmetic Operations
Explanation:
o Arithmetic operations can be performed directly within SQL queries to
manipulate data during retrieval.
1. Addition (+)
Syntax:
Sql:
SELECT column_name1 + column_name2 AS result_column_name FROM table_name;
Example:
Sql:
SELECT salary + bonus AS total_income FROM employees;
Explanation:
Operation: The addition operator (+) adds two numerical values.
In this example: The query adds the salary and bonus columns for each employee. The
result of this addition is labeled as total_income in the output. If an employee has a
salary of 50,000 and a bonus of 5,000, the total_income would be 55,000.
2. Subtraction (-)
Syntax:
Sql:
SELECT column_name1 - column_name2 AS result_column_name FROM table_name;
Example:
Sql:
SELECT price - discount AS final_price FROM products;
Explanation:
Operation: The subtraction operator (-) subtracts one numerical value from another.
In this example: The query subtracts the discount from the price for each product.
The result of this subtraction is labeled as final_price in the output. If a product's
price is 100 and the discount is 20, the final_price would be 80.
3. Multiplication (*)
Syntax:
Sql:
SELECT column_name1 * column_name2 AS result_column_name FROM table_name;
Example:
Sql:
SELECT quantity * unit_price AS total_cost FROM orders;
Explanation:
Operation: The multiplication operator (*) multiplies two numerical values.
In this example: The query multiplies the quantity of items by the unit_price for
each order. The result of this multiplication is labeled as total_cost in the output. If an
order has a quantity of 10 and a unit_price of 15, the total_cost would be 150.
4. Division (/)
Syntax:
Sql:
SELECT column_name1 / column_name2 AS result_column_name FROM table_name;
Example:
Sql:
SELECT total_amount / number_of_items AS price_per_item FROM sales;
Explanation:
Operation: The division operator (/) divides one numerical value by another.
In this example: The query divides the total_amount by the number_of_items for
each sale. The result of this division is labeled as price_per_item in the output. If a sale
has a total_amount of 300 and number_of_items is 3, the price_per_item would be
100.
5. Modulus (%)
Syntax:
Sql:
SELECT column_name1 % column_name2 AS result_column_name FROM table_name;
Example:
Sql:
SELECT employee_id % 2 AS remainder FROM employees;
Explanation:
Operation: The modulus operator (%) returns the remainder of a division operation
between two numerical values.
In this example: The query calculates the remainder when employee_id is divided by 2.
The result is labeled as remainder in the output. This operation is often used to
determine whether a number is even or odd. If an employee_id is 5, the remainder
would be 1, indicating that the number is odd..
f. Restricting Data with WHERE Clause
Explanation:
o The WHERE clause is used to filter records that meet a specific condition.
o Syntax:
Sql:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
o Example:
Sql:
SELECT * FROM Employees
WHERE HireDate > '2023-01-01';
o Application:
Used to restrict data retrieval to a specific subset, such as retrieving
records for employees hired after a certain date.
g. Sorting
Explanation:
o The ORDER BY clause is used to sort the result set by one or more columns, either
in ascending (ASC) or descending (DESC) order.
o Syntax:
Sql:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC];
o Example:
Sql:
SELECT * FROM Products
ORDER BY Price DESC;
o Application:
Used to sort data, such as listing products by price or employees by their
hire date.
h. Revisiting Substitution Variables
Explanation:
o Substitution variables allow for dynamic queries where values can be input by the
user at runtime.
o Syntax:
Sql:
SELECT * FROM table_name
WHERE column_name = '&variable_name';
o Example:
Sql:
SELECT * FROM Employees
WHERE Department = '&dept_name';
o Application:
Useful in environments where queries need to be run multiple times with
different input values.
i. DEFINE Command
Explanation:
o The DEFINE command allows you to create a substitution variable that can be
reused in multiple places within your SQL script.
o Syntax:
Sql:
DEFINE variable_name = value;
o Example:
Sql:
DEFINE dept_name = 'Marketing';
SELECT * FROM Employees
WHERE Department = '&dept_name';
o Application:
Simplifies complex queries by allowing the reuse of commonly used
variables.
j. CASE Structure
Explanation:
o The CASE structure is used to implement conditional logic within SQL queries,
allowing different outputs based on specific conditions.
o Syntax:
Sql:
SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE resultN
END AS alias_name
FROM table_name;
o Example:
Sql:
SELECT EmployeeID, FirstName,
CASE
WHEN Department = 'Sales' THEN 'Sales Department'
WHEN Department = 'Marketing' THEN 'Marketing Department'
ELSE 'Other Department'
END AS DeptDescription
FROM Employees;
o Application:
Ideal for creating custom output based on varying conditions, such as
classifying employees into different department groups.
2. Functions and Grouping
a. Built-in Functions
Explanation:
o SQL provides various built-in functions that allow users to perform calculations
on data, such as averaging values, finding minimums or maximums, and counting
records.
o Syntax:
Sql:
SELECT function_name(column_name)
FROM table_name;
o Example:
Sql:
SELECT AVG(Price) AS AveragePrice, MAX(Price) AS MaxPrice
FROM Products;
o Application:
Used for data analysis, such as calculating average prices of products,
finding the highest salary in a department, etc.
b. Grouping Data
Explanation:
o The GROUP BY clause is used to group rows that have the same values in specified
columns into summary rows, like aggregating data within categories.
o Syntax:
Sql:
SELECT column1, function_name(column2)
FROM table_name
GROUP BY column1;
o Example:
Sql:
SELECT Department, COUNT(*) AS EmployeeCount
FROM Employees
GROUP BY Department;
o Application:
Useful for generating reports that require data aggregation, like total sales
per region or employee count per department.
3. Multiple Table - JOINS
Joins in SQL are used to combine rows from two or more tables based on a related column
between them. Joins are essential for querying data that is spread across multiple tables, allowing
you to retrieve meaningful information.
Types of Joins
1. INNER JOIN
2. LEFT JOIN (or LEFT OUTER JOIN)
3. RIGHT JOIN (or RIGHT OUTER JOIN)
4. FULL JOIN (or FULL OUTER JOIN)
5. CROSS JOIN
6. SELF JOIN
Let's explore each type with its syntax, an example, and an explanation:
1. INNER JOIN
Syntax:
Sql:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example:
Sql:
SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
Explanation:
Operation: INNER JOIN returns only the rows where there is a match between the
columns in both tables.
In this example: The query retrieves the first_name and last_name of employees
along with their department_name. It only includes employees who have a
corresponding department_id in the departments table.
2. LEFT JOIN (or LEFT OUTER JOIN)
Syntax:
Sql:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example:
Sql:
SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;
Explanation:
Operation: LEFT JOIN returns all rows from the left table (table1), and the matched rows
from the right table (table2). If there is no match, NULL values are returned for columns
from the right table.
In this example: The query retrieves all employees' first_name, last_name, and their
department_name. If an employee doesn't belong to any department (i.e., no matching
department_id in the departments table), the department_name will be NULL.
3. RIGHT JOIN (or RIGHT OUTER JOIN)
Syntax:
Sql:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example:
Sql:
SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
Explanation:
Operation: RIGHT JOIN returns all rows from the right table (table2), and the matched
rows from the left table (table1). If there is no match, NULL values are returned for
columns from the left table.
In this example: The query retrieves all department_names along with the first_name
and last_name of employees. If a department has no employees, the first_name and
last_name will be NULL.
4. FULL JOIN (or FULL OUTER JOIN)
Syntax:
Sql:
SELECT column_name(s)
FROM table1
FULL JOIN table2
ON table1.column_name = table2.column_name;
Example:
Sql:
SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
FULL JOIN departments
ON employees.department_id = departments.department_id;
Explanation:
Operation: FULL JOIN returns all rows when there is a match in either table. It combines
the results of both LEFT JOIN and RIGHT JOIN. If there is no match, NULL values are
returned for columns from the table without a match.
In this example: The query retrieves the first_name and last_name of employees
along with their department_name, showing all possible matches and including rows
with NULL where no match exists in either table.
5. CROSS JOIN
Syntax:
Sql:
SELECT column_name(s)
FROM table1
CROSS JOIN table2;
Example:
SqL:
SELECT employees.first_name, departments.department_name
FROM employees
CROSS JOIN departments;
Explanation:
Operation: CROSS JOIN returns the Cartesian product of the two tables, meaning every
row in table1 is combined with every row in table2.
In this example: The query retrieves all combinations of employees' first_name with
every department_name. If there are 10 employees and 5 departments, the result will
contain 50 rows (10 x 5).
6. SELF JOIN
Syntax:
Sql:
SELECT a.column_name, b.column_name
FROM table_name a, table_name b
WHERE a.common_column = b.common_column;
Example:
Sql:
SELECT e1.first_name AS Employee, e2.first_name AS Manager
FROM employees e1
INNER JOIN employees e2
ON e1.manager_id = e2.employee_id;
Explanation:
Operation: SELF JOIN is a regular join but the table is joined with itself. It's useful when
you want to compare rows within the same table.
In this example: The query retrieves the first_name of employees and their respective
managers. Here, the employees table is joined with itself to find which employee is
managed by whom.
Summary
INNER JOIN: Returns only the matching rows from both tables.
LEFT JOIN: Returns all rows from the left table and matching rows from the right table
(with NULLs if no match).
RIGHT JOIN: Returns all rows from the right table and matching rows from the left
table (with NULLs if no match).
FULL JOIN: Returns all rows when there is a match in either table (with NULLs if no
match).
CROSS JOIN: Returns the Cartesian product of the two tables.
SELF JOIN: Joins a table with itself to compare rows within the same table.
Each type of join serves a specific purpose and is useful for different scenarios in data retrieval
and analysis.
b. Set Operations
Set operations in SQL are used to combine the results of two or more SELECT queries. The
primary set operations are UNION, UNION ALL, INTERSECT, and EXCEPT (or MINUS in some
databases). These operations allow you to perform comparisons between the result sets of
different queries.
1. UNION
The UNION operator combines the result sets of two or more SELECT queries into a single result
set, excluding duplicate rows.
Syntax:
Sql:
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
Example:
Sql:
SELECT first_name FROM employees
UNION
SELECT first_name FROM customers;
Explanation:
Operation: The UNION operator returns the combined result set of the SELECT statements,
removing duplicates.
In this example: The query retrieves all unique first_names from both the employees
and customers tables.
2. UNION ALL
The UNION ALL operator is similar to UNION, but it includes all duplicates.
Syntax:
Sql:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Example:
Sql:
SELECT first_name FROM employees
UNION ALL
SELECT first_name FROM customers;
Explanation:
Operation: The UNION ALL operator returns the combined result set of the SELECT
statements, including all duplicates.
In this example: The query retrieves all first_names from both the employees and
customers tables, including any duplicates.
3. INTERSECT
The INTERSECT operator returns only the rows that are common to both SELECT queries.
Syntax:
Sql:
SELECT column_name(s) FROM table1
INTERSECT
SELECT column_name(s) FROM table2;
Example:
Sql:
SELECT first_name FROM employees
INTERSECT
SELECT first_name FROM customers;
Explanation:
Operation: The INTERSECT operator returns only the rows that are present in both result
sets.
In this example: The query retrieves first_names that appear in both the employees
and customers tables.
4. EXCEPT (or MINUS)
The EXCEPT (or MINUS) operator returns the rows from the first SELECT query that are not present
in the second SELECT query.
Syntax:
Sql:
SELECT column_name(s) FROM table1
EXCEPT
SELECT column_name(s) FROM table2;
Example:
Sql:
SELECT first_name FROM employees
EXCEPT
SELECT first_name FROM customers;
Explanation:
Operation: The EXCEPT operator returns only the rows from the first result set that do not
appear in the second result set.
In this example: The query retrieves first_names that are in the employees table but
not in the customers table.
Summary
UNION: Combines result sets from multiple SELECT queries, removing duplicates.
UNION ALL: Combines result sets from multiple SELECT queries, including duplicates.
INTERSECT: Returns only the rows common to all SELECT queries.
EXCEPT (or MINUS): Returns the rows from the first SELECT query that are not in the
second SELECT query.
Each set operation is useful for different scenarios in data retrieval, allowing you to compare and
combine results from multiple queries.