DBMS (Unit2)
DBMS (Unit2)
SYSTEM
BCS501
B. TECH V SEM
UNIT 1
SQL is the standard language for relational database management and manipulation. It allows for
defining, querying, updating, and managing data within a relational database.
Key Characteristics:
Advantages of SQL
• Easy to Learn and Use: SQL has a simple syntax and uses English-like commands,
making it accessible for users without extensive programming experience.
• Standardized Language: SQL is an ANSI and ISO standard, ensuring consistency
across various database systems and allowing SQL skills to be transferable across
platforms.
• Efficient Data Management: SQL allows for powerful data querying, updating,
insertion, and deletion, enabling efficient management of large datasets with minimal
code.
• Supports Complex Queries: SQL can handle complex data retrieval through
features like joins, nested queries, and subqueries, allowing users to access and
analyze data in various ways.
• Data Integrity and Security: SQL enforces data integrity through constraints (like
primary keys, foreign keys, and unique constraints) and provides security through
permissions and access control.
• Scalability: SQL is designed to handle large volumes of data and can be optimized
with indexing, views, and efficient query planning for faster data processing.
• Flexibility with Procedural Extensions: SQL extensions like PL/SQL (Oracle) and
T-SQL (SQL Server) allow for more complex business logic and procedural
operations within databases.
• Interactive and Dynamic: SQL supports interactive querying and can be modified
dynamically, making it ideal for ad-hoc analysis and reporting.
SQL Data Types
It contains any value that holds the letters and numbers including the binary data, image or audio
files. It basically used to store the textual data such as names, designations, addresses etc. The String
Data types allow both fixed and variable length strings.
1. CHAR(size): It holds maximum 255 characters and allows a fixed length string. Here, the
size is the number of characters to store. Specifying the length is not compulsory, and the
default size is 1.
3. Binary Large Objects (BLOB) or TEXT: It allows a string with a maximum length of
65,535 characters. No need to specify a length with BLOB or TEXT. These data types are
used to store large amounts of binary data, such as images or other types of files. Here, BLOB
is case sensitive, whereas TEXT is not case sensitive.
It allows both the signed and the unsigned integers. It is basically used to store data like marks, price,
salary etc.
1. INT: It allows signed integers from -2147483638 to 214747483637 and unsigned integers
from 0 to 4294967925. We can specify a width of up to 11 digits. It requires 4 bytes for
storage.
1. DATE: It holds the date values in the format - YYYY-MM-DD - where the supported range
is 1000-01-01 to 9999-12-31. It only accepts valid dates between the mentioned supported
ranges. It takes 3 bytes for storage.
2. DATETIME: It holds a combination of date and time values in the format - YYYY-MM-
DD HH:MI:SS - where the supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'. It takes 5 bytes plus fractional seconds for storage.
3. TIME: It stores the time in an HH:MM:SS format, where the supported range is-838:59:59
to 838:59:59. It takes 3 bytes plus fractional seconds for storage.
4. YEAR: The YEAR data type is used to store a four-digit year value in the YYYY format or
two-digit year value in the YY format. The default length is 4. If the length is specified as 2
(for example YEAR(2)), YEAR can be between 1970 and 2069 (70 and 69). If the length is
specified as 4, then YEAR can be 1901 to 2155. It takes 1 byte for storage.
SQL Literals
Literals are constant values used within SQL statements. Common types include:
1. String Literals: Represent text strings and are enclosed in single quotes (e.g., 'Hello', 'SQL
Example').
2. Numeric Literals: Represent numbers without quotes (e.g., 100, 3.14).
3. Date Literals: Represent dates in a format recognized by SQL, typically 'YYYY-MM-DD'
(e.g., '2023-11-09').
4. Time Literals: Represent time values, usually in the format 'HH:MM:SS' (e.g., '12:30:00').
5. Boolean Literals: Represent true or false values, often TRUE or FALSE or 1 and 0.
SQL Commands
SQL commands are categorized into five main types based on their functionality. Each type serves
a specific purpose in database management:
• Manages transactions in SQL, allowing for a set of SQL operations to be grouped together
and controlled as a single unit.
• Commands:
o COMMIT: Saves all changes made during the current transaction to the database
permanently.
o ROLLBACK: Reverts changes made during the current transaction, restoring the
database to its last committed state.
o SAVEPOINT: Sets a point within a transaction that can be rolled back to without
affecting the entire transaction.
SQL Operators
1. Arithmetic Operators
Example:
SELECT salary + bonus AS total_compensation FROM employees;
2. Comparison Operators
• Purpose: Used to compare values and filter data based on specific conditions.
• Operators:
o = (Equal to)
o != or <> (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
Example:
3. Logical Operators
Example:
SELECT * FROM employees WHERE department = 'Sales' AND salary > 50000;
4. Bitwise Operators
Example:
SELECT 5 & 3; -- This will perform a bitwise AND on binary representations of 5 and 3.
5. Set Operators
Example:
6. String Operators
Example:
7. Other Operators
Example:
Order of Precedence
When multiple operators are used in a single SQL statement, they follow a certain order:
The fundamental storage unit in a relational database, a table stores data in rows and columns. Each
table consists of columns that define the data types and constraints and rows that contain the actual
data.
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
Views
• Purpose: A virtual table that provides a way to look at data in one or more tables without
storing the data separately. Views are often used to simplify complex queries, enhance
security, and organize data presentation.
• Characteristics:
o Views are generated dynamically from the underlying tables each time they are
accessed.
o They don’t store data themselves; they just provide a saved SQL query that can be
executed to display data.
o Views can hide complex joins or filters and limit the data visible to specific users,
offering a layer of security.
• Types of Views:
o Simple View: Based on a single table, without group functions.
o Complex View: Based on multiple tables and may include group functions.
Example:
• Benefits:
o Simplifies access to complex queries.
o Enhances data security by restricting access to specific columns.
o Provides a customized view of data tailored to different users.
Indexes
• Purpose: A performance optimization structure that helps speed up the retrieval of data in
tables. Indexes provide a fast lookup mechanism, similar to an index in a book.
• Characteristics:
o Created on one or more columns to improve the speed of data retrieval for specific
queries.
o Indexes do add overhead because they require storage space and need to be updated
when the underlying table data changes.
• Types of Indexes:
o Unique Index: Ensures that all values in the indexed column(s) are unique.
o Non-Unique Index: Does not enforce uniqueness but speeds up data access.
o Composite Index: An index based on multiple columns, helping with multi-column
queries.
o Full-Text Index: Used for full-text search in large textual fields.
Example:
Storage Stores actual data Virtual table, no data stored Stores pointers to data
Data
Direct access to data Access data indirectly Speeds up data retrieval
Access
Data Can directly Updates reflect changes in Updated when table data
Update add/update/delete data tables changes
Aggregate function
Aggregate functions in SQL are powerful tools that allow you to perform calculations on multiple
rows of data to return a single result. Here are some of the most commonly used aggregate functions:
1. COUNT
o Counts the number of rows in a column or the table, often with a condition.
o Example: SELECT COUNT(*) FROM employees; – Counts all employees.
2. SUM
o Adds up all the values in a specified column.
o Example: SELECT SUM(salary) FROM employees; – Totals all salaries.
3. AVG
o Calculates the average value of a numeric column.
o Example: SELECT AVG(salary) FROM employees; – Finds the average salary.
4. MIN
o Returns the minimum value in a column.
o Example: SELECT MIN(salary) FROM employees; – Finds the lowest salary.
5. MAX
o
Returns the maximum value in a column.
Example: SELECT MAX(salary) FROM employees; – Finds the highest salary.
o
6. GROUP_CONCAT (MySQL specific)
o Concatenates values from multiple rows into a single string, with optional separators.
o Example: SELECT GROUP_CONCAT(name) FROM employees; – Lists employee
names separated by commas.
Aggregate functions are often used with the GROUP BY clause to summarize data by specific
categories or groups.
Example:
HAVING is used to filter groups after aggregation (like WHERE, but for aggregated data).
Example:
This query returns only departments where the average salary is greater than $50,000.
Cursor
A cursor in SQL is a database object that allows row-by-row processing of a result set. Unlike
standard SQL operations that work with entire sets of rows at once, a cursor allows you to work with
individual rows sequentially, making it useful for complex row-level tasks that require specific
processing on each row.
Key Concepts of Cursors
1. Declaration
• Cursors are declared with the DECLARE statement. When declaring, you specify the query
that will select the rows for the cursor.
2. Opening
• The cursor is opened with the OPEN statement, which executes the query and makes the
result set available for row-by-row processing.
3. Fetching
• FETCH retrieves the next row from the cursor into specified variables, allowing you to work
with the data in that row.
4. Processing
• You can process each row by performing operations based on the values in the current row.
• The cursor is closed with the CLOSE statement, releasing the row set. DEALLOCATE
removes the cursor definition, freeing memory.
Types of Cursors
1. Implicit Cursors
o Automatically created by SQL for simple SELECT, INSERT, UPDATE, and
DELETE operations.
2. Explicit Cursors
o Defined explicitly by the user for more complex row-by-row processing.
Trigger
Types of Triggers
1. BEFORE Triggers
o Executed before the event occurs, allowing the trigger to inspect and modify data
before it is written to the table.
o Often used for data validation or transformation.
2. AFTER Triggers
o Executed after the event has occurred, useful for logging actions or enforcing
constraints that depend on the data already being committed.
o Commonly used to log changes or update related tables.
3. INSTEAD OF Triggers
o Executed in place of the specified action, often used with views to control what
happens during INSERT, UPDATE, or DELETE on the view.
o Useful when you want to customize data modification behavior on complex views or
when direct data modification on a table is restricted.
A procedure is a named block of SQL code that performs a specific task in SQL or PL/SQL
(Procedural Language/SQL). Procedures allow for reusable code and can be called multiple times
with different parameters. They provide a way to encapsulate logic for operations that need to be
executed repeatedly.
Types of Procedures
1. Stored Procedure (SQL): A set of SQL statements that can be executed in the database.
They are stored in the database itself and are executed by calling the procedure.
2. PL/SQL Procedure (Oracle-specific): A type of stored procedure specific to Oracle
databases, using PL/SQL (Procedural Language/SQL), which allows more complex logic,
loops, exception handling, and more advanced features.
Difference between SQL and PL/SQL
SQL PL/SQL
It interacts with the database server. It cannot interact with the database server.