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

Database Notes by Hassaan

Data base important notes by Hassaan
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)
33 views

Database Notes by Hassaan

Data base important notes by Hassaan
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/ 20

Data Definition Language (DDL)

Data Definition Language (DDL) is a subset of SQL (Structured Query Language) used to define, manage, and
manipulate database structures. DDL commands are used to create, alter, and delete database objects like
tables, indexes, views, and schemas. Here’s a comprehensive guide covering the theory, syntax, and examples
of each DDL command.

Key Concepts of DDL

1. Database Schema: The overall structure or organization of the database.

2. Table: A collection of related data entries that consists of columns and rows.

3. Index: A performance-tuning method to allow faster retrieval of records.

4. View: A virtual table based on the result-set of an SQL statement.

5. Constraints: Rules enforced on data columns on tables.

Major DDL Commands

1. CREATE: Used to create a new database object.

2. ALTER: Used to modify an existing database object.

3. DROP: Used to delete an existing database object.

4. TRUNCATE: Used to remove all records from a table, including all spaces allocated for the records.

5. RENAME: Used to rename a database object.

Detailed Explanation and Examples

1. CREATE

The CREATE command is used to create a new table, index, view, or database.

Syntax:

CREATE TABLE table_name (

column1 datatype constraint,

column2 datatype constraint,

);

Example:

CREATE TABLE Employees (


EmployeeID int PRIMARY KEY,

FirstName varchar(255) NOT NULL,

LastName varchar(255) NOT NULL,

BirthDate date,

HireDate date

);

2. ALTER

The ALTER command is used to modify an existing database object, like a table.

Syntax:

ALTER TABLE table_name

ADD column_name datatype constraint;

ALTER TABLE table_name

MODIFY column_name datatype constraint;

ALTER TABLE table_name

DROP COLUMN column_name;

Example:

ALTER TABLE Employees

ADD Email varchar(255);

ALTER TABLE Employees

MODIFY Email varchar(255) NOT NULL;

ALTER TABLE Employees

DROP COLUMN BirthDate;

3. DROP
The DROP command is used to delete an existing database object.

Syntax:

DROP TABLE table_name;

DROP INDEX index_name;

DROP VIEW view_name;

DROP DATABASE database_name;

Example:

DROP TABLE Employees;

DROP INDEX idx_EmployeeID;

DROP VIEW EmployeeView;

DROP DATABASE CompanyDB;

4. TRUNCATE

The TRUNCATE command is used to remove all records from a table, including all spaces allocated for the
records.

Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE Employees;

5. RENAME

The RENAME command is used to rename an existing database object.

Syntax:

RENAME TABLE old_table_name TO new_table_name;

Example:

RENAME TABLE Employees TO Staff;

Constraints

Constraints are used to specify rules for data in a table. The following are commonly used constraints:

1. NOT NULL: Ensures that a column cannot have a NULL value.


2. UNIQUE: Ensures that all values in a column are unique.

3. PRIMARY KEY: A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table.

4. FOREIGN KEY: Uniquely identifies a row/record in another table.

5. CHECK: Ensures that all values in a column satisfy a specific condition.

6. DEFAULT: Sets a default value for a column if no value is specified.

Syntax and Example:

CREATE TABLE Employees (

EmployeeID int PRIMARY KEY,

FirstName varchar(255) NOT NULL,

LastName varchar(255) NOT NULL,

BirthDate date,

HireDate date,

Email varchar(255) UNIQUE,

Salary decimal(10, 2) CHECK (Salary > 0),

DepartmentID int,

FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)

);

Views

A view is a virtual table based on the result-set of an SQL statement. It contains rows and columns, just like a
real table. The fields in a view are fields from one or more real tables in the database.

Syntax:

CREATE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example:

CREATE VIEW EmployeeView AS


SELECT FirstName, LastName, HireDate

FROM Employees

WHERE HireDate > '2020-01-01';

Indexes

Indexes are used to retrieve data from the database more quickly than otherwise. The users cannot see the
indexes; they are just used to speed up searches/queries.

Syntax:

CREATE INDEX index_name

ON table_name (column1, column2, ...);

Example:

CREATE INDEX idx_LastName

ON Employees (LastName);

Summary

 CREATE: Creates objects (tables, indexes, views).

 ALTER: Modifies existing objects (add, modify, drop columns).

 DROP: Deletes objects.

 TRUNCATE: Removes all records from a table.

 RENAME: Changes the name of an object.

DDL is a crucial part of database management as it defines the schema and structure of the data within the
database. Proper use of DDL commands ensures efficient data organization, integrity, and retrieval.

Data Manipulation Language (DML)


Data Manipulation Language (DML) is a subset of SQL (Structured Query Language) used to manage and
manipulate data in a database. DML commands are primarily used to retrieve, insert, update, and delete data
in database tables. Here’s a comprehensive guide covering the theory, syntax, and examples of each DML
command.

Key Concepts of DML

1. Data Retrieval: Fetching data from a database.

2. Data Insertion: Adding new data to a database.


3. Data Updating: Modifying existing data in a database.

4. Data Deletion: Removing data from a database.

Major DML Commands

1. SELECT: Used to retrieve data from a database.

2. INSERT: Used to add new records to a table.

3. UPDATE: Used to modify existing records in a table.

4. DELETE: Used to remove records from a table.

Detailed Explanation and Examples

1. SELECT

The SELECT command is used to retrieve data from one or more tables. It can select specific columns, filter
records, sort results, and join tables.

Syntax:

SELECT column1, column2, ...

FROM table_name

WHERE condition

ORDER BY column1, column2, ...;

Example:

SELECT FirstName, LastName, HireDate

FROM Employees

WHERE DepartmentID = 1

ORDER BY LastName;

 SELECT * FROM table_name: Selects all columns.

 WHERE: Filters records based on a condition.

 ORDER BY: Sorts the result-set in ascending or descending order.

2. INSERT

The INSERT command is used to add new records to a table.

Syntax:
INSERT INTO table_name (column1, column2, ...)

VALUES (value1, value2, ...);

Example:

INSERT INTO Employees (FirstName, LastName, BirthDate, HireDate, DepartmentID)

VALUES ('John', 'Doe', '1980-01-15', '2022-05-01', 1);

 INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...): Specifies the columns
and values for the new record.

 INSERT INTO table_name VALUES (value1, value2, ...): If all columns are provided in order.

3. UPDATE

The UPDATE command is used to modify existing records in a table.

Syntax:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

Example:

UPDATE Employees

SET HireDate = '2023-06-01'

WHERE EmployeeID = 1;

 SET column1 = value1, column2 = value2, ...: Specifies the columns and new values.

 WHERE condition: Specifies which records to update (omit for all records).

4. DELETE

The DELETE command is used to remove records from a table.

Syntax:

DELETE FROM table_name

WHERE condition;

Example:

DELETE FROM Employees


WHERE EmployeeID = 1;

 DELETE FROM table_name WHERE condition: Deletes records matching the condition.

 DELETE FROM table_name: Deletes all records (use with caution).

Advanced Features in DML

1. Joins

Joins are used to combine rows from two or more tables, based on a related column between them.

Types of Joins:

 INNER JOIN: Returns records with matching values in both tables.

 LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table and matched records from the
right table.

 RIGHT JOIN (or RIGHT OUTER JOIN): Returns all records from the right table and matched records from
the left table.

 FULL JOIN (or FULL OUTER JOIN): Returns records when there is a match in either left or right table.

Syntax and Example:

SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName

FROM Employees

INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName

FROM Employees

LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

2. Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value. Common aggregate
functions include COUNT, SUM, AVG, MAX, and MIN.

Syntax and Example:

SELECT COUNT(*), AVG(Salary), MAX(Salary), MIN(Salary)

FROM Employees

WHERE DepartmentID = 1;
SELECT DepartmentID, COUNT(*), AVG(Salary)

FROM Employees

GROUP BY DepartmentID;

 COUNT: Returns the number of rows.

 SUM: Returns the total sum of a numeric column.

 AVG: Returns the average value of a numeric column.

 MAX: Returns the maximum value in a set.

 MIN: Returns the minimum value in a set.

 GROUP BY: Groups rows that have the same values into summary rows.

3. Subqueries

A subquery is a query within another query. The subquery is executed first, and its result is used by the main
query.

Syntax and Example:

SELECT FirstName, LastName

FROM Employees

WHERE DepartmentID = (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'Sales');

SELECT EmployeeID, FirstName, LastName

FROM Employees

WHERE Salary > (SELECT AVG(Salary) FROM Employees);

Summary

 SELECT: Retrieves data.

 INSERT: Adds new records.

 UPDATE: Modifies existing records.

 DELETE: Removes records.

 Joins: Combines rows from multiple tables.


 Aggregate Functions: Perform calculations on sets of values.

 Subqueries: Nest one query within another.

DML commands are crucial for interacting with and manipulating the data stored within a database. Proper
understanding and usage of these commands allow for efficient and accurate data management.

Data Retrieval Language (DRL)


Data Retrieval Language (DRL) is not a distinct subset of SQL like Data Definition Language (DDL) or Data
Manipulation Language (DML). Instead, DRL typically refers to the set of SQL commands and techniques used
primarily for retrieving data from databases. The primary SQL command for data retrieval is SELECT, but there
are several clauses, functions, and techniques that enhance data retrieval capabilities. Here's a comprehensive
guide covering the theory, syntax, and examples of data retrieval in SQL.

Key Concepts of Data Retrieval

1. Data Selection: Choosing specific data to retrieve from one or more tables.

2. Filtering: Narrowing down data to meet certain criteria.

3. Sorting: Ordering the retrieved data.

4. Joining Tables: Combining data from multiple tables.

5. Aggregating Data: Summarizing data using aggregate functions.

6. Subqueries: Using queries within queries to refine data retrieval.

Major SQL Components for Data Retrieval

1. SELECT: Main command used to query data from a database.

2. FROM: Specifies the table(s) to retrieve data from.

3. WHERE: Filters records based on specified conditions.

4. ORDER BY: Sorts the result set.

5. GROUP BY: Groups rows sharing a property so that aggregate functions can be applied.

6. HAVING: Filters groups based on specified conditions.

7. JOIN: Combines rows from two or more tables based on related columns.

8. Subqueries: Nested queries within a main query.

9. Functions: Built-in SQL functions for various data manipulations.

Detailed Explanation and Examples


1. SELECT

The SELECT statement is the cornerstone of SQL queries, used to specify the columns to be retrieved from the
database.

Syntax:

SELECT column1, column2, ...

FROM table_name;

Example:

SELECT FirstName, LastName, HireDate

FROM Employees;

 SELECT * FROM table_name: Retrieves all columns from the specified table.

2. FROM

The FROM clause specifies the table(s) from which to retrieve data.

Example:

SELECT FirstName, LastName

FROM Employees;

3. WHERE

The WHERE clause filters records that meet specific conditions.

Syntax:

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example:

SELECT FirstName, LastName

FROM Employees

WHERE DepartmentID = 1;

 Operators: =, <>, >, <, >=, <=, BETWEEN, LIKE, IN, IS NULL.

4. ORDER BY
The ORDER BY clause sorts the result set by one or more columns.

Syntax:

SELECT column1, column2, ...

FROM table_name

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

Example:

SELECT FirstName, LastName

FROM Employees

ORDER BY LastName ASC, FirstName DESC;

 ASC: Ascending order (default).

 DESC: Descending order.

5. GROUP BY

The GROUP BY clause groups rows that have the same values in specified columns into summary rows.

Syntax:

SELECT column1, aggregate_function(column2)

FROM table_name

GROUP BY column1;

Example:

SELECT DepartmentID, COUNT(*)

FROM Employees

GROUP BY DepartmentID;

 Aggregate Functions: COUNT, SUM, AVG, MAX, MIN.

6. HAVING

The HAVING clause filters groups based on specified conditions (similar to WHERE but for groups).

Syntax:

SELECT column1, aggregate_function(column2)

FROM table_name
GROUP BY column1

HAVING condition;

Example:

SELECT DepartmentID, COUNT(*)

FROM Employees

GROUP BY DepartmentID

HAVING COUNT(*) > 5;

7. JOIN

The JOIN clause combines rows from two or more tables based on related columns.

Types of Joins:

 INNER JOIN: Returns records with matching values in both tables.

 LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table and matched records from the
right table.

 RIGHT JOIN (or RIGHT OUTER JOIN): Returns all records from the right table and matched records from
the left table.

 FULL JOIN (or FULL OUTER JOIN): Returns records when there is a match in either left or right table.

Syntax and Example:

SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName

FROM Employees

INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName

FROM Employees

LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

8. Subqueries

A subquery is a query nested within another query. It can be used in SELECT, FROM, WHERE, and HAVING
clauses.

Syntax and Example:


SELECT FirstName, LastName

FROM Employees

WHERE DepartmentID = (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'Sales');

SELECT EmployeeID, FirstName, LastName

FROM Employees

WHERE Salary > (SELECT AVG(Salary) FROM Employees);

9. Functions

SQL provides built-in functions to perform calculations and manipulations on data.

 String Functions: CONCAT, SUBSTRING, LENGTH, UPPER, LOWER.

 Numeric Functions: ROUND, CEIL, FLOOR, ABS.

 Date Functions: NOW, CURDATE, DATEDIFF, DATE_ADD, DATE_SUB.

Examples:

SELECT CONCAT(FirstName, ' ', LastName) AS FullName

FROM Employees;

SELECT ROUND(Salary, 2)

FROM Employees;

SELECT DATEDIFF(NOW(), HireDate) AS DaysWorked

FROM Employees;

Advanced Data Retrieval Techniques

1. Pagination: Fetching a subset of records for display in pages.

o Syntax (MySQL):

SELECT column1, column2, ...

FROM table_name

LIMIT offset, row_count;


o Example:

SELECT FirstName, LastName

FROM Employees

LIMIT 0, 10;

2. Using Aliases: Renaming tables and columns for ease of use.

o Syntax:

SELECT column1 AS alias1, column2 AS alias2

FROM table_name AS alias_name;

o Example:

SELECT e.FirstName AS First, e.LastName AS Last, d.DepartmentName AS Dept

FROM Employees AS e

INNER JOIN Departments AS d ON e.DepartmentID = d.DepartmentID;

3. Case Statements: Conditional logic within SQL queries.

o Syntax:

SELECT column1,

CASE

WHEN condition1 THEN result1

WHEN condition2 THEN result2

ELSE result3

END AS alias

FROM table_name;

o Example:

SELECT FirstName, LastName,

CASE

WHEN Salary > 50000 THEN 'High'

WHEN Salary BETWEEN 30000 AND 50000 THEN 'Medium'

ELSE 'Low'
END AS SalaryLevel

FROM Employees;

Summary

 SELECT: Main command for data retrieval.

 FROM: Specifies the source table(s).

 WHERE: Filters records based on conditions.

 ORDER BY: Sorts the result set.

 GROUP BY: Groups rows for aggregation.

 HAVING: Filters groups based on conditions.

 JOIN: Combines data from multiple tables.

 Subqueries: Nested queries for refined data retrieval.

 Functions: Built-in SQL functions for data manipulation.

 Pagination: Limiting results for display purposes.

 Aliases: Simplifies complex queries.

 Case Statements: Implements conditional logic.

Proper understanding and usage of these components and techniques are crucial for efficient and accurate
data retrieval from databases.

Data Control Language (DCL)


Data Control Language (DCL) is a subset of SQL used to control access to data in a database. DCL commands
manage permissions and other controls related to data access. The two primary DCL commands are GRANT
and REVOKE. Here’s a comprehensive guide covering the theory, syntax, and examples of DCL.

Key Concepts of DCL

1. Permissions: Rights given to users to perform specific actions on database objects.

2. Privileges: Specific rights granted to users or roles, such as SELECT, INSERT, UPDATE, DELETE.

3. Roles: Named groups of related privileges that can be granted to users or other roles.

4. Users: Individuals or entities that have access to the database.

Major DCL Commands


1. GRANT: Grants specific privileges to users or roles.

2. REVOKE: Removes specific privileges from users or roles.

Detailed Explanation and Examples

1. GRANT

The GRANT command is used to give users or roles specific privileges.

Syntax:

GRANT privilege [, privilege ...]

ON object

TO {user | role} [, {user | role} ...]

[WITH GRANT OPTION];

 privilege: The specific privilege to be granted (e.g., SELECT, INSERT, UPDATE, DELETE).

 object: The database object on which the privilege is to be granted (e.g., table, view).

 user: The user to whom the privilege is granted.

 role: The role to which the privilege is granted.

 WITH GRANT OPTION: Allows the user or role to grant the specified privilege to others.

Example:

-- Grant SELECT and INSERT privileges on the Employees table to user 'JohnDoe'

GRANT SELECT, INSERT

ON Employees

TO JohnDoe;

-- Grant SELECT privilege on the Employees table to role 'HR_Role'

GRANT SELECT

ON Employees

TO HR_Role;
-- Grant ALL privileges on the Employees table to user 'AdminUser' with the ability to grant these privileges to
others

GRANT ALL PRIVILEGES

ON Employees

TO AdminUser

WITH GRANT OPTION;

2. REVOKE

The REVOKE command is used to remove specific privileges from users or roles.

Syntax:

REVOKE privilege [, privilege ...]

ON object

FROM {user | role} [, {user | role} ...];

 privilege: The specific privilege to be revoked (e.g., SELECT, INSERT, UPDATE, DELETE).

 object: The database object from which the privilege is to be revoked (e.g., table, view).

 user: The user from whom the privilege is revoked.

 role: The role from which the privilege is revoked.

Example:

-- Revoke SELECT and INSERT privileges on the Employees table from user 'JohnDoe'

REVOKE SELECT, INSERT

ON Employees

FROM JohnDoe;

-- Revoke SELECT privilege on the Employees table from role 'HR_Role'

REVOKE SELECT

ON Employees

FROM HR_Role;
-- Revoke ALL privileges on the Employees table from user 'AdminUser'

REVOKE ALL PRIVILEGES

ON Employees

FROM AdminUser;

Roles and User Management

Roles simplify the management of user permissions by grouping related privileges together. Instead of
granting and revoking privileges individually for each user, you can grant and revoke roles.

Creating Roles:

CREATE ROLE role_name;

Granting Roles:

sql

Copy code

GRANT role_name

TO user_name;

Revoking Roles:

REVOKE role_name

FROM user_name;

Examples:

-- Create a new role 'HR_Manager'

CREATE ROLE HR_Manager;

-- Grant SELECT and UPDATE privileges on the Employees table to the 'HR_Manager' role

GRANT SELECT, UPDATE

ON Employees

TO HR_Manager;

-- Grant the 'HR_Manager' role to user 'JaneDoe'


GRANT HR_Manager

TO JaneDoe;

-- Revoke the 'HR_Manager' role from user 'JaneDoe'

REVOKE HR_Manager

FROM JaneDoe;

Additional Considerations

 Database Security: DCL commands are essential for database security, ensuring that only authorized
users have access to perform specific actions on database objects.

 Granting Privileges with Hierarchies: Privileges can be granted hierarchically, meaning a user with the
WITH GRANT OPTION can grant the privilege to other users.

 Cascading Revokes: When a privilege is revoked, all subsequent privileges that were granted based on
the revoked privilege are also revoked.

Summary

 GRANT: Grants specific privileges to users or roles.

 REVOKE: Removes specific privileges from users or roles.

 Roles: Named groups of related privileges that simplify user permission management.

 Database Security: Ensures that only authorized users have access to specific database objects and
actions.

DCL commands are crucial for managing database security and access control, ensuring that data is protected
and only accessible to authorized users. Proper use of GRANT and REVOKE commands allows for effective
management of user permissions and roles in a database environment.

You might also like