0% found this document useful (0 votes)
31 views

DBMS (Unit2)

dbms
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

DBMS (Unit2)

dbms
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

DATABASE MANAGEMENT

SYSTEM
BCS501

B. TECH V SEM
UNIT 1

Relational data Model and Language


Relational Data Model Concepts, Integrity Constraints, Entity
Integrity, Referential Integrity, Keys Constraints, Domain
Constraints, Relational Algebra, Relational Calculus, Tuple and
Domain Calculus. Introduction on SQL: Characteristics of SQL,
Advantage of SQL. SQL Data Type and Literals. Types of SQL
Commands. SQL Operators and Their Procedure. Tables, Views
and Indexes. Queries and Sub Queries. Aggregate Functions.
Insert, Update and Delete Operations, Joins, Unions, Intersection,
Minus, Cursors, Triggers, Procedures in SQL/PL SQL
Introduction to SQL (Structured Query Language)

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:

1. Declarative: Focuses on what data to retrieve rather than how.


2. High-Level and User-Friendly: Uses simple commands like SELECT, INSERT,
UPDATE, and DELETE.
3. Portable: Standardized by ANSI and ISO, allowing for cross-platform compatibility.
4. Supports Complex Queries: Can handle nested queries, joins, and subqueries.
5. Versatile: Supports Data Definition (DDL), Data Manipulation (DML), Data Control
(DCL), and Transaction Control (TCL).
6. Relational and Set-Based: Operates on tables and supports relational concepts.
7. Data Integrity and Security: Enforces constraints and access control.
8. Efficient and Scalable: Designed for large datasets, with indexing and optimization
options.

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

String 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.

2. VARCHAR(size): It is a variable-length string between 1 and 255 characters in length. Here,


the size is the number of characters to store. You must define a length when creating a
VARCHAR field. Whenever we have a variable length data, Varchar is more appropriate as
compared to the Char data type, as it saves memory.

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.

Numeric data types

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.

2. FLOAT (M,D) or DOUBLE (M,D): FLOAT is a single-precision floating point number


and DOUBLE is a double-precision floating point number. These data types are also known
as "Floating-Point" data types. Here, (M,D) means that values can be stored with up to M
digits in total, of which D digits may be after the decimal point.

Date and Time data types


This data type enables us to mention the date, time, and also the combination of date and time.
MySQL supports the following Date and Time data types:

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:

1. Data Definition Language (DDL)

• Used to define, alter, and manage database structure and schema.


• Commands:
o CREATE: Creates a new database, table, index, or view.
o ALTER: Modifies an existing database object, such as adding or removing columns
in a table.
o DROP: Deletes an existing database, table, index, or view.
o TRUNCATE: Removes all records from a table without deleting the table itself
(unlike DROP).
2. Data Manipulation Language (DML)

• Used to retrieve and modify data within tables.


• Commands:
o SELECT: Retrieves data from one or more tables.
o INSERT: Adds new records to a table.
o UPDATE: Modifies existing records in a table.
o DELETE: Removes records from a table based on a condition.

3. Data Query Language (DQL)

• Primarily focused on data retrieval.


• Commands:
o SELECT: The primary command in DQL, used to query and fetch data based on
specific conditions.

4. Data Control Language (DCL)

• Manages permissions and access control for database security.


• Commands:
o GRANT: Gives specific user(s) permissions on database objects.
o REVOKE: Removes previously granted permissions from user(s).

5. Transaction Control Language (TCL)

• 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

• Purpose: Used to perform basic arithmetic calculations.


• Operators:
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Modulus)

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:

SELECT * FROM products WHERE price > 100;

3. Logical Operators

• Purpose: Combine multiple conditions in a query.


• Operators:
o AND: Both conditions must be true.
o OR: At least one condition must be true.
o NOT: Reverses the result of a condition.

Example:

SELECT * FROM employees WHERE department = 'Sales' AND salary > 50000;

4. Bitwise Operators

• Purpose: Perform bit-level operations.


• Operators:
o & (Bitwise AND)
o | (Bitwise OR)
o ^ (Bitwise XOR)
o ~ (Bitwise NOT)

Example:

SELECT 5 & 3; -- This will perform a bitwise AND on binary representations of 5 and 3.

5. Set Operators

• Purpose: Combine the results of multiple queries.


• Operators:

1. UNION: Combines results from two queries, removing duplicates.


2. UNION ALL: Combines results, including duplicates.
3. INTERSECT: Returns only the common rows between two queries.
4. EXCEPT: Returns only the rows in the first query that are not in the second.

Example:

SELECT name FROM employees_a


UNION
SELECT name FROM employees_b;

6. String Operators

• Purpose: Perform operations on string data.


• Operators:
o || or + (Concatenation)
o LIKE: Used for pattern matching.
o IN: Checks if a value is within a set.

Example:

SELECT first_name || ' ' || last_name AS full_name FROM employees;

7. Other Operators

• Purpose: These are unique to SQL for specific operations.


• Operators:
o IS NULL: Checks if a value is NULL.
o IS NOT NULL: Checks if a value is not NULL.
o BETWEEN: Checks if a value is within a range.
o EXISTS: Checks for the existence of rows in a subquery.

Example:

SELECT * FROM employees WHERE salary BETWEEN 50000 AND 100000;

Order of Precedence

When multiple operators are used in a single SQL statement, they follow a certain order:

1. Arithmetic operators (+, -, *, /)


2. Comparison operators (=, !=, >, <, etc.)
3. Logical operators (NOT, AND, OR)
Tables

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.

CREATE TABLE employees (

id INT PRIMARY KEY,

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:

CREATE VIEW high_salary_employees AS


SELECT first_name, last_name, department, salary
FROM employees
WHERE salary > 60000;

• 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:

CREATE INDEX idx_department_salary ON employees(department, salary);

Differences Between Tables, Views, and Indexes


Feature Tables Views Indexes

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

Organize, simplify, secure Improve query


Purpose Fundamental storage unit
data access performance

Data Can directly Updates reflect changes in Updated when table data
Update add/update/delete data tables changes

Supports primary, foreign No constraints; based on Does not enforce


Constraints
keys, etc. table constraints constraints

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.

Using Aggregate Functions with GROUP BY

Aggregate functions are often used with the GROUP BY clause to summarize data by specific
categories or groups.

Example:

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id;

This query returns the average salary for each department.

Using Aggregate Functions with HAVING

HAVING is used to filter groups after aggregation (like WHERE, but for aggregated data).

Example:

SELECT department_id, AVG(salary)


FROM employees
GROUP BY department_id
HAVING AVG(salary) > 50000;

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.

5. Closing and Deallocating

• 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

A trigger is a stored procedure in a database that is automatically invoked whenever a specified


event occurs on a table or view. Triggers are useful for automating tasks, enforcing complex data
integrity rules, or logging changes to tables.

Key Characteristics of Triggers

• Event-Based: Triggers are activated by specific database operations, such as INSERT,


UPDATE, or DELETE.
• Automatic Execution: Unlike procedures that require manual calls, triggers run
automatically when triggered by a specified event.
• Row-Level or Statement-Level: Triggers can run once for every row affected (row-level)
or once for the entire SQL statement (statement-level).
• Declarative Logic: Triggers are written in SQL and stored in the database, where they
operate independently of application code.

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.

Procedures in SQL/PL SQL

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

SQL is a single query that performs the DML


PL/SQL is the block of codes that are used to
(Data manipulation language) and DDL
write the whole program function.
(Data Definition Language) operations easily.

PL/SQL is a procedural language that defines


SQL is a declarative database.
how things will execute.

A single statement is executed at a time in A whole block is executed at a time in the


Structure Query Language. PL/SQL.

Structure Query Language is used to


PL/SQL creates the applications.
manipulate the data.

It interacts with the database server. It cannot interact with the database server.

PL/SQL is the extension of SQL, so it contains


SQL cannot contain the code of PL/SQL.
SQL inside it.

You might also like