Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Dbms SQL Queries

Uploaded by

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

Dbms SQL Queries

Uploaded by

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

1.

Data Definition Language (DDL)


DDL commands are used to define and manage all database objects, including tables,
indexes, and schemas. These commands typically deal with the structure of the
database.

Common DDL Commands:


CREATE: Creates a new database object (e.g., table, view, index).

CREATE TABLE Employees (


EmpID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
ALTER: Modifies an existing database object.

ALTER TABLE Employees ADD COLUMN Salary DECIMAL(10, 2);


DROP: Deletes an existing database object.
sql
Copy code
DROP TABLE Employees;
TRUNCATE: Removes all records from a table but keeps the structure intact.

TRUNCATE TABLE Employees;


2. Data Manipulation Language (DML)
DML commands are used for managing data within database objects. These commands are
used to insert, update, delete, and retrieve data.

Common DML Commands:


INSERT: Adds new records to a table.

INSERT INTO Employees (EmpID, FirstName, LastName) VALUES (1, 'John', 'Doe');
UPDATE: Modifies existing records in a table.

UPDATE Employees SET Salary = 60000 WHERE EmpID = 1;


DELETE: Removes records from a table.

DELETE FROM Employees WHERE EmpID = 1;


SELECT: Retrieves records from one or more tables.

SELECT * FROM Employees;


3. Data Control Language (DCL)
DCL commands are used to control access to data in the database. These commands are
used to grant or revoke permissions.

Common DCL Commands:


GRANT: Gives a user access privileges to the database.

GRANT SELECT, INSERT ON Employees TO User1;


REVOKE: Removes access privileges from a user.

REVOKE INSERT ON Employees FROM User1;


4. Transaction Control Language (TCL)
TCL commands are used to manage transactions in the database. These commands ensure
that a group of operations is completed successfully or none at all, maintaining
data integrity.

Common TCL Commands:


COMMIT: Saves all changes made in the current transaction.
COMMIT;
ROLLBACK: Undoes all changes made in the current transaction.

ROLLBACK;
SAVEPOINT: Sets a point within a transaction to which you can later roll back.

SAVEPOINT SavePoint1;
Summary
DDL (Data Definition Language): Deals with the structure of the database (e.g.,
CREATE, ALTER, DROP).
DML (Data Manipulation Language): Deals with the manipulation of data within
database objects (e.g., INSERT, UPDATE, DELETE, SELECT).
DCL (Data Control Language): Deals with the permissions and access controls (e.g.,
GRANT, REVOKE).
TCL (Transaction Control Language): Deals with transaction management (e.g.,
COMMIT, ROLLBACK, SAVEPOINT).

1. Parent Table (Departments):


This table has a Primary Key on DepartmentID:

CREATE TABLE Departments (


DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);

The DepartmentID uniquely identifies each department.


This table contains a list of departments.

2. Child Table (Employees):


This table contains a Foreign Key that references DepartmentID in the Departments
table:

CREATE TABLE Employees (


EmpID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT,
Salary DECIMAL(10, 2),
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);

EmpID is the primary key of the Employees table.


DepartmentID is a foreign key in this table, linking employees to their respective
departments.

How Foreign Keys Work:


Referential Integrity:

The DepartmentID in the Employees table must match an existing DepartmentID in the
Departments table.
If you try to insert a record into Employees with a DepartmentID that does not
exist in the Departments table,
SQL Server will prevent the insertion.
Cascading Actions:

ON DELETE CASCADE: If a record in the Departments table is deleted, all related


records in the Employees table will also be deleted.
ON UPDATE CASCADE: If the DepartmentID in the Departments table is updated, the
DepartmentID in the Employees table will automatically update
to reflect the change.

Example: Foreign Key Constraint in Action


Insert Valid Data (Works Fine):

-- Insert department
INSERT INTO Departments (DepartmentID, DepartmentName) VALUES
(1, 'HR'),
(2, 'IT');

-- Insert additional departments


INSERT INTO Departments (DepartmentID, DepartmentName) VALUES
(3, 'Sales'),
(4, 'Finance'),
(5, 'Marketing'),
(6, 'Operations'),
(7, 'Legal'),
(8, 'R&D'),
(9, 'Customer Support'),
(10, 'Procurement');

-- Insert employee with a valid DepartmentID (Works fine)


INSERT INTO Employees (EmpID, FirstName, LastName, DepartmentID, Salary)
VALUES (101, 'John', 'Doe', 2, 60000);

-- Insert additional employees


INSERT INTO Employees (EmpID, FirstName, LastName, DepartmentID, Salary) VALUES
(102, 'Jane', 'Smith', 1, 55000),
(103, 'Mike', 'Brown', 3, 45000),
(104, 'Emily', 'Davis', 4, 70000),
(105, 'Sam', 'Wilson', 2, 62000),
(106, 'Tom', 'Hanks', 3, 40000),
(107, 'Sara', 'Jones', 1, 52000),
(108, 'Adam', 'Lee', 2, 63000),
(109, 'Nancy', 'White', 4, 71000),
(110, 'Steve', 'Miller', 3, 46000),
(111, 'Linda', 'Taylor', 1, 53000),
(112, 'David', 'Garcia', 5, 48000),
(113, 'Jessica', 'Moore', 6, 52000),
(114, 'Daniel', 'Anderson', 7, 65000),
(115, 'James', 'Harris', 8, 62000),
(116, 'Sophia', 'Clark', 9, 47000),
(117, 'Henry', 'Johnson', 10, 55000),
(118, 'Ella', 'Martinez', 5, 54000),
(119, 'Ethan', 'Perez', 6, 51000),
(120, 'Olivia', 'Kim', 7, 60000);

Insert Invalid Data (Fails Due to Foreign Key Constraint):

-- Try to insert an employee with a non-existing DepartmentID (Error)


INSERT INTO Employees (EmpID, FirstName, LastName, DepartmentID, Salary)
VALUES (102, 'Jane', 'Smith', 5, 50000);

-- Error: The INSERT statement conflicted with the FOREIGN KEY constraint
-- "FK_Employees_Departments". The conflict occurred in database "yourDB",
-- table "Departments", column 'DepartmentID'.

Cascading Actions Example:


Cascading Delete:
Let's say the IT department (DepartmentID = 2) gets deleted:

-- Enable cascading delete when creating the foreign key


ALTER TABLE Employees
ADD CONSTRAINT FK_Employees_Departments
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
ON DELETE CASCADE;

-- Delete the IT department (2)


DELETE FROM Departments WHERE DepartmentID = 2;

After this, all employees linked to the IT department in the Employees table will
also be automatically deleted.

Example of Cascading Update Using the Departments and Employees Tables:


To demonstrate the Cascading Update, we'll modify the foreign key constraint in the
Employees table to include ON UPDATE CASCADE.
This means that if the DepartmentID in the Departments table is updated, all
corresponding records in the Employees table will
also be updated automatically.

1. Modify Foreign Key with Cascading Update:

-- First, drop the existing foreign key constraint


ALTER TABLE Employees
DROP CONSTRAINT FK_Employees_Departments;

-- Add the foreign key constraint again with ON UPDATE CASCADE


ALTER TABLE Employees
ADD CONSTRAINT FK_Employees_Departments
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
ON UPDATE CASCADE;

Steps to Drop Cascading Update/Delete:


1. Drop the Foreign Key Constraint (with Cascade):
First, you need to drop the foreign key constraint that includes the cascading
actions

ALTER TABLE Employees


DROP CONSTRAINT FK_Employees_Departments;

This removes the foreign key constraint, effectively dropping the cascading
behavior.

2. Recreate the Foreign Key Constraint (without Cascade):


After dropping the old constraint, re-create the foreign key constraint without
cascading actions.
This means that any updates or deletions in the parent table (e.g., Departments)
will not propagate automatically to the child table (Employees).

ALTER TABLE Employees


ADD CONSTRAINT FK_Employees_Departments
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID);

Checking Existing Constraints:


If you're not sure what the foreign key constraint is named (as it might be
automatically named by the system), you can look it up using:

-- Check the foreign key constraints on the Employees table


SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'Employees' AND CONSTRAINT_TYPE = 'FOREIGN KEY';

This query will return the name of the foreign key constraint, which you can use in
the DROP CONSTRAINT statement.

1. Add Constraint for Text-Only Columns


To allow only alphabetic characters in a column (e.g., names or other string data),
you can use a CHECK constraint with regular expressions (in some databases) or
string functions like LIKE.

Example: Only Allow Alphabetic Characters in FirstName

ALTER TABLE Employees


ADD CONSTRAINT chk_FirstName
CHECK (FirstName NOT LIKE '%[^a-zA-Z]%' AND LEN(FirstName) > 0);

Explanation:
LIKE '%[^a-zA-Z]%' ensures that only letters (uppercase and lowercase) are allowed
in the FirstName column.
LEN(FirstName) > 0 ensures that the FirstName column is not empty.

ALTER TABLE Employees


ADD CONSTRAINT chk_Salary
CHECK (Salary NOT LIKE '%[^0-9]%');

ALTER TABLE Employees


ADD CONSTRAINT chk_SalaryRange
CHECK (Salary >= 30000 AND Salary <= 1000000);

Dropping the chk_Salary Constraint:

ALTER TABLE Employees


DROP CONSTRAINT chk_SalaryRange;

Example: Creating a View


Let’s assume we have the following tables:

Departments: (as defined earlier)


Employees: (as defined earlier)
Now, let’s create a view that shows the names of employees along with their
department names.

Step 1: Create a View to Show Employee Names and Department Names

CREATE VIEW EmployeeDepartmentView AS


SELECT
e.EmpID,
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
JOIN
Departments d ON e.DepartmentID = d.DepartmentID;

You might also like