0% found this document useful (0 votes)
7 views31 pages

Wa0002

The document outlines SQL commands for creating tables, inserting data, and managing views, including examples for employee and department tables. It also covers data manipulation commands such as INSERT, DELETE, UPDATE, and SELECT, along with the use of GRANT and REVOKE for data control. Additionally, it discusses PL/SQL and Transact-SQL procedures, functions, cursors, triggers, and embedded SQL for database connectivity.

Uploaded by

kaviraj281103
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)
7 views31 pages

Wa0002

The document outlines SQL commands for creating tables, inserting data, and managing views, including examples for employee and department tables. It also covers data manipulation commands such as INSERT, DELETE, UPDATE, and SELECT, along with the use of GRANT and REVOKE for data control. Additionally, it discusses PL/SQL and Transact-SQL procedures, functions, cursors, triggers, and embedded SQL for database connectivity.

Uploaded by

kaviraj281103
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/ 31

1.

CREATION OF BASE TABLE AND VIEWS

CREATING TABLE
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT,
salary DECIMAL(10, 2)
);
//TABLE CREATED

INSERTING SOME SAMPLE DATA INTO THE EMPLOYEES TABLE


INSERT INTO employees (employee_id, first_name, last_name, department_id, salary)
VALUES
(1, 'John', 'Doe', 101, 50000.00),
(2, 'Jane', 'Smith', 102, 60000.00),
(3, 'Mike', 'Johnson', 101, 55000.00),
(4, 'Emily', 'Brown', 103, 52000.00);

OUTPUT:

CREATING A VIEW
CREATE VIEW department_101_employees AS
SELECT *
FROM employees
WHERE department_id = 101;
OUTPUT:
2. Data Manipulation INSERT, DELETE and UPDATE in Tables. SELECT, Sub
Queries and JOIN

CREATE TABLE

CREATE TABLE employees (


id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
department_id INT
);

CREATE TABLE departments (


id INT PRIMARY KEY,
name VARCHAR(50),
location VARCHAR(50)
);

INSERT
INSERT INTO employees (id, name, age, department_id)
VALUES (1, 'John Doe', 30, 1),
(2, 'Jane Smith', 35, 2);

INSERT INTO departments (id, name, location)


VALUES (1, 'IT', 'New York'),
(2, 'HR', 'Los Angeles');

DELETE
DELETE FROM employees
WHERE id = 1;

OUTPUT:
UPDATE
UPDATE employees
SET department_id = 2
WHERE name = 'John Doe';

BEFORE OUTPUT:

AFTER UPDATING:

SELECT

SELECT * FROM employees;

OUTPUT:
SELECT SUBQURIES
SELECT name
FROM employees
WHERE department_id IN (SELECT id FROM departments WHERE location = 'New York');

JOIN
SELECT employees.name, departments.name AS department_name
FROM employees
JOIN departments ON employees.department_id = departments.id;

OUTPUT:
3. DATA CONTROL COMMANDS

• GRANT
• REVOKE

GRANT:
The GRANT statement in SQL is used to grant specific privileges or permissions to database
users. These privileges can include the ability to SELECT, INSERT, UPDATE, DELETE, or other
operations on tables and views, as well as the ability to create or drop tables, among others.

QUERY

GRANT privileges ON object TO user;


Let's assume we have a database called example_db with a table called customers containing
sensitive information such as names, addresses, and phone numbers. We want to grant SELECT
privilege on this table to a user called analyst.
QUERY:
//-- Create a sample database
CREATE DATABASE example_db;

//-- Switch to the created database


USE example_db;

//-- Create a sample table


CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
address VARCHAR(255),
phone VARCHAR(15)
);

//-- Insert some sample data


INSERT INTO customers (name, address, phone) VALUES
('John Doe', '123 Main St, Anytown', '555-1234'),
('Jane Smith', '456 Elm St, Othertown', '555-5678');
//-- Create a user
CREATE USER 'analyst'@'localhost' IDENTIFIED BY 'password';

//-- Grant SELECT privilege on the customers table to the analyst user
GRANT SELECT ON example_db.customers TO 'analyst'@'localhost';

• We create a database called example_db.


• We create a table called customers within the example_db database to store customer
information.
• We insert some sample data into the customers table.
• We create a user called analyst with the password 'password'.
• Finally, we grant the SELECT privilege on the customers table within the example_db
database to the analyst user.

//-- Log in as the analyst user


mysql -u analyst -p

//-- After entering the password, the analyst can run the following query to select data from the
customers table
SELECT * FROM example_db.customers;

OUTPUT:

REVOKE
The REVOKE command is used to revoke privileges that have been previously granted to a user
or role. Building upon the previous example, let's revoke the SELECT privilege from the analyst
user on the customers table.
COMMAND
REVOKE SELECT, INSERT ON table_name FROM user_name;

QUERY
//-- Create a sample database
CREATE DATABASE example_db;

//-- Switch to the created database


USE example_db;

//-- Create a sample table


CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
address VARCHAR(255),
phone VARCHAR(15)
);
//-- Insert some sample data
INSERT INTO customers (name, address, phone) VALUES
('John Doe', '123 Main St, Anytown', '555-1234'),
('Jane Smith', '456 Elm St, Othertown', '555-5678');

//-- Create a user


CREATE USER 'analyst'@'localhost' IDENTIFIED BY 'password';

//-- Grant SELECT privilege on the customers table to the analyst user
GRANT SELECT ON example_db.customers TO 'analyst'@'localhost';

//-- Revoke SELECT privilege on the customers table from the analyst user
REVOKE SELECT ON example_db.customers FROM 'analyst'@'localhost';

In this command, we specify that we want to revoke the SELECT privilege on the customers
table from the analyst user.

After running this command, if the analyst tries to select data from the customers table again,
they will receive an error indicating that they no longer have permission to access the table.
//-- Log in as the analyst user
mysql -u analyst -p

//-- After entering the password, the analyst tries to select data from the customers table
SELECT * FROM example_db.customers;

OUTPUT
4. HIGH LEVEL LANGUAGE EXTENSIONS: PL/SQL PACKAGE TRANSACT SQL

PL/SQL
//-- Creating a sample employees table
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
name VARCHAR2(100),
salary NUMBER
);

//-- Inserting some sample data


INSERT INTO employees VALUES (1, 'John Doe', 50000);
INSERT INTO employees VALUES (2, 'Jane Smith', 60000);
INSERT INTO employees VALUES (3, 'Michael Johnson', 70000);

//-- Creating a procedure to get employee details by ID


CREATE OR REPLACE PROCEDURE GetEmployeeDetails (emp_id IN NUMBER) IS
emp_name VARCHAR2(100);
emp_salary NUMBER;

BEGIN

SELECT name, salary INTO emp_name, emp_salary FROM employees WHERE employee_id = emp_id;
IF emp_name IS NOT NULL AND emp_salary IS NOT NULL THEN
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_id || ', Name: ' || emp_name || ', Salary: ' ||
emp_salary);
ELSE
DBMS_OUTPUT.PUT_LINE('Employee with ID ' || emp_id || ' not found.');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee with ID ' || emp_id || ' not found.');
END;
/

// To see the output for the last program, you would need to execute the procedures with valid
employee IDs. Let's assume we want to get the details for an employee with ID 2:
//-- Enable DBMS_OUTPUT to see the output in Oracle SQL Developer or SQL*Plus
SET SERVEROUTPUT ON;

//-- Call the procedure with an existing employee ID

BEGIN
GetEmployeeDetails(2);
END;
/

OUTPUT

TRANSACT SQL
//-- Creating a sample employees table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
salary DECIMAL(10, 2)
);

//-- Inserting some sample data


INSERT INTO employees VALUES (1, 'John Doe', 50000);
INSERT INTO employees VALUES (2, 'Jane Smith', 60000);
INSERT INTO employees VALUES (3, 'Michael Johnson', 70000);

//-- Creating a procedure to get employee details by ID


CREATE PROCEDURE GetEmployeeDetails (@emp_id INT) AS
BEGIN
DECLARE @emp_name VARCHAR(100);
DECLARE @emp_salary DECIMAL(10, 2);
SELECT @emp_name = name, @emp_salary = salary FROM employees WHERE employee_id
= @emp_id;
IF @emp_name IS NOT NULL AND @emp_salary IS NOT NULL
PRINT 'Employee ID: ' + CAST(@emp_id AS VARCHAR) + ', Name: ' + @emp_name + ',
Salary: ' + CAST(@emp_salary AS VARCHAR);
ELSE
PRINT 'Employee with ID ' + CAST(@emp_id AS VARCHAR) + ' not found.';
END;

//-- Call the procedure with an existing employee ID


EXEC GetEmployeeDetails 2;

OUTPUT
5. Use of Cursors, Procedures and Functions 6. Embedded SQL or Database
Connectivity.

CURSORS
A cursor in SQL is a database object used to retrieve and manipulate data row by
row. It allows sequential processing of query results, making it useful when
dealing with a result set that needs to be processed one row at a time.

QUERY
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2),
department_id INT

);

INSERT INTO employee (id, name, salary, department_id) VALUES


(1, 'John Doe', 50000.00, 101),
(2, 'Jane Smith', 60000.00, 102),
(3, 'Alice Johnson', 55000.00, 101),
(4, 'Bob Brown', 62000.00, 102),
(5, 'Charlie Lee', 53000.00, 101);

QUERY
DECLARE emp_cursor CURSOR FOR
SELECT name, salary FROM employee;
OPEN emp_cursor;
FETCH NEXT FROM emp_cursor;

OUTPUT

PROCEDURES
A stored procedure in SQL is a set of SQL statements that can be stored and executed as a
single unit. It allows for better code organization, reusability, and security.

QUERY
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2),

department_id INT
);

INSERT INTO employee (id, name, salary, department_id) VALUES


(1, 'John Doe', 50000.00, 101),

(2, 'Jane Smith', 60000.00, 102),


(3, 'Alice Johnson', 55000.00, 101),
(4, 'Bob Brown', 62000.00, 102),
(5, 'Charlie Lee', 53000.00, 101);

QUERY
CREATE PROCEDURE calculateTotalSalary(@dept_id INT)
AS
BEGIN
SELECT SUM(salary) AS TotalSalary
FROM employee

WHERE department_id = @dept_id;


END;

OUTPUT

FUNCTION
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),

salary DECIMAL(10, 2),


department_id INT
);

INSERT INTO employee (id, name, salary, department_id) VALUES

(1, 'John Doe', 50000.00, 101),


(2, 'Jane Smith', 60000.00, 102),
(3, 'Alice Johnson', 55000.00, 101),
(4, 'Bob Brown', 62000.00, 102),

(5, 'Charlie Lee', 53000.00, 101);

QUERY
CREATE FUNCTION calculateBonus(@salary DECIMAL)
RETURNS DECIMAL

AS
BEGIN
DECLARE @bonus DECIMAL;
IF @salary > 50000
SET @bonus = @salary * 0.1;

ELSE
SET @bonus = 0;
RETURN @bonus;
END;

SELECT calculateBonus(60000);

OUTPUT
EMBEDDED SQL
QUERY
CREATE TABLE employee (

id INT PRIMARY KEY,


name VARCHAR(50),
salary DECIMAL(10, 2),
department_id INT
);

INSERT INTO employee (id, name, salary, department_id) VALUES


(1, 'John Doe', 50000.00, 101),
(2, 'Jane Smith', 60000.00, 102),
(3, 'Alice Johnson', 55000.00, 101),

(4, 'Bob Brown', 62000.00, 102),


(5, 'Charlie Lee', 53000.00, 101);

QUERY
import java.sql.*;

public class EmployeeDetails {


public static void main(String[] args) {
try {
// Establish database connection

Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/company", "username",
"password");
// Create statement object
Statement stmt = conn.createStatement();

// Display employee table


System.out.println("Employee Table:");
System.out.println("-----------------");
ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
while (rs.next()) {

System.out.println(rs.getInt("id") + " | " + rs.getString("name") + " | " +


rs.getDouble("salary") + " | " + rs.getInt("department_id"));

}
System.out.println();

// Execute SQL query to retrieve employee details


rs = stmt.executeQuery("SELECT * FROM employee");

// Display employee details


System.out.println("Employee Details:");
System.out.println("-----------------");
while (rs.next()) {

System.out.println(rs.getString("name") + " | " + rs.getString("salary"));


}

// Close resources
rs.close();

stmt.close();
conn.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}

}
}

OUTPUT
6. ORACLE OR SQL SERVER TRIGGERS – BLOCK LEVEL – FORM LEVEL TRIGGERS
Oracle Block-Level Trigger

QUERY
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),

salary NUMBER
);
// let's create a block-level trigger in Oracle Forms that fires before an update on the salary
column and increases the salary by 10%:

QUERY
CREATE OR REPLACE TRIGGER increase_salary_trigger

BEFORE UPDATE OF salary ON employees


FOR EACH ROW
BEGIN
:new.salary := :old.salary * 1.1;
END;

OUTPUT
Before update:
employee_id: 1

first_name: John
last_name: Doe
salary: 5000

After update (with trigger):

employee_id: 1
first_name: John
last_name: Doe
salary: 5500 (increased by 10%)

SQL SERVER DML TRIGGER


CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name NVARCHAR(50),
last_name NVARCHAR(50),

salary DECIMAL(10, 2)
);
// We want to create a DML trigger that logs any changes made to the salary column into an
audit table:

QUERY
CREATE TABLE salary_audit (
audit_id INT IDENTITY(1,1) PRIMARY KEY,

employee_id INT,
old_salary DECIMAL(10, 2),
new_salary DECIMAL(10, 2),
change_date DATETIME
);

// create the DML trigger in SQL Server:


CREATE TRIGGER salary_audit_trigger
ON employees
AFTER UPDATE OF salary

AS
BEGIN
INSERT INTO salary_audit (employee_id, old_salary, new_salary, change_date)
SELECT
i.employee_id,

d.salary AS old_salary,
i.salary AS new_salary,
GETDATE() AS change_date
FROM
inserted i

INNER JOIN
deleted d ON i.employee_id = d.employee_id
WHERE
i.salary <> d.salary;
END;

// With this trigger in place, whenever the salary column is updated in the employees table, the
salary_audit_trigger will log the old and new salary values along with the change date into the
salary_audit table.

OUTPUT
Before update:
employee_id: 1

first_name: John
last_name: Doe
salary: 5000

After update (with trigger, assuming the salary is updated to 6000):

audit_id: 1 (generated by identity column in the audit table)


employee_id: 1
old_salary: 5000
new_salary: 6000
change_date: [current date/time]
7. Working With Forms, Menus And Report Writers For A Application Project In
Any Domain

QUERY
//-- Borrower table
CREATE TABLE Borrower (
ID INT PRIMARY KEY,
Name VARCHAR(100)
);

-- Book table
CREATE TABLE Book (
ID INT PRIMARY KEY,
Title VARCHAR(255),
Author VARCHAR(100),
ISBN VARCHAR(20),
Publication_Year INT,
Quantity INT
);

-- Borrow table
CREATE TABLE Borrow (
ID INT PRIMARY KEY,
Borrower_ID INT,
Book_ID INT,
Date_Borrowed DATE,
Date_Due DATE,
FOREIGN KEY (Borrower_ID) REFERENCES Borrower(ID),
FOREIGN KEY (Book_ID) REFERENCES Book(ID)
);

INSERTING VALUES:

-- Inserting sample data into Borrower table


INSERT INTO Borrower (ID, Name) VALUES
(1, 'John Doe'),
(2, 'Jane Smith'),
(3, 'Alice Johnson');
-- Inserting sample data into Book table
INSERT INTO Book (ID, Title, Author, ISBN, Publication_Year, Quantity) VALUES
(1, 'The Great Gatsby', 'F. Scott Fitzgerald', '978-0743273565', 1925, 5),
(2, 'To Kill a Mockingbird', 'Harper Lee', '978-0061120084', 1960, 7),
(3, 'Pride and Prejudice', 'Jane Austen', '978-0141439518', 1813, 10);

-- Inserting sample data into Borrow table


INSERT INTO Borrow (ID, Borrower_ID, Book_ID, Date_Borrowed, Date_Due) VALUES
(1, 1, 1, '2024-01-05', '2024-02-05'),
(2, 2, 2, '2024-01-10', '2024-02-10'),
(3, 3, 3, '2024-02-15', '2024-03-15');

EXECUTING THE QUERY:

SELECT
Borrower.Name AS Borrower_Name,
Book.Title AS Book_Title,
Borrow.Date_Borrowed,
Borrow.Date_Due
FROM
Borrow
JOIN
Borrower ON Borrow.Borrower_ID = Borrower.ID
JOIN
Book ON Borrow.Book_ID = Book.ID;

OUTPUT:
8. FRONT – END TOOLS – VISUAL BASIC/DEVELOPER 200

Imports System.Data.SqlClient

Module Module1

Sub Main()
' Connection string to your SQL Server database
Dim connectionString As String =
"Server=YourServerName;Database=YourDatabaseName;User
Id=YourUsername;Password=YourPassword;"

' SQL statements


Dim createTableQuery As String = "CREATE TABLE Employees (" &
"EmployeeID INT PRIMARY KEY IDENTITY(1,1)," &
"FirstName VARCHAR(50)," &
"LastName VARCHAR(50)," &
"Salary DECIMAL(10, 2));"

Dim insertDataQuery As String = "INSERT INTO Employees (FirstName, LastName, Salary)


VALUES " &
"('John', 'Doe', 50000.00)," &
"('Jane', 'Smith', 60000.00)," &
"('Alice', 'Johnson', 55000.00);"

Dim selectDataQuery As String = "SELECT * FROM Employees;"

' Create connection and command objects


Using connection As New SqlConnection(connectionString)
connection.Open()

' Create table


Using command As New SqlCommand(createTableQuery, connection)
command.ExecuteNonQuery()
Console.WriteLine("Table created successfully.")
End Using

' Insert data


Using command As New SqlCommand(insertDataQuery, connection)
command.ExecuteNonQuery()
Console.WriteLine("Data inserted successfully.")
End Using

' Query data


Using command As New SqlCommand(selectDataQuery, connection)
Using reader As SqlDataReader = command.ExecuteReader()
Console.WriteLine("EmployeeID | FirstName | LastName | Salary")
While reader.Read()
Console.WriteLine($"{reader("EmployeeID")} | {reader("FirstName")} |
{reader("LastName")} | {reader("Salary")}")
End While
End Using
End Using
End Using

Console.ReadLine()
End Sub

End Module

//--Replace "YourServerName", "YourDatabaseName", "YourUsername", and "YourPassword"


with your actual database server details.

This code performs the following steps:

Connects to the SQL Server database using the provided connection string.
Executes SQL commands to create the Employees table, insert sample data, and retrieve all
records from the table.
Displays the retrieved data in the console.
You can run this VB.NET code in Visual Studio or any other VB.NET development environment--
//

Output
9.query evaluation plan
QUERY

-- Creating the employees table


CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT,
salary DECIMAL(10, 2)
);

-- Inserting sample data into the employees table


INSERT INTO employees (employee_id, first_name, last_name, department_id, salary)
VALUES
(101, 'John', 'Smith', 1, 60000.00),
(102, 'Jane', 'Doe', 2, 65000.00),
(103, 'Michael', 'Johnson', 3, 55000.00),
(104, 'Emily', 'Brown', 1, 62000.00),
(105, 'David', 'Wilson', 2, 70000.00);

-- Query for retrieving information about employees and their departments


SELECT
e.employee_id,
e.first_name || ' ' || e.last_name AS full_name,
d.department_name
FROM
employees e
INNER JOIN
departments d ON e.department_id = d.department_id
WHERE
e.salary > 50000
ORDER BY
e.employee_id;
Output:
10. concurrency and transactional
QUERY
CREATE TABLE Bank_Accounts (
Account_Number INT PRIMARY KEY,
Balance DECIMAL(10, 2),
Last_Transaction_Date DATE
);

INSERT INTO Bank_Accounts (Account_Number, Balance, Last_Transaction_Date)


VALUES
(1, 1000.00, '2024-03-01'),
(2, 2000.00, '2024-03-05');

-- Start transaction 1: Transfer $200 from Account 1 to Account 2


BEGIN TRANSACTION;

UPDATE Bank_Accounts
SET Balance = Balance - 200, Last_Transaction_Date = CURRENT_DATE
WHERE Account_Number = 1;

UPDATE Bank_Accounts
SET Balance = Balance + 200, Last_Transaction_Date = CURRENT_DATE
WHERE Account_Number = 2;

COMMIT;

-- Start transaction 2: Withdraw $100 from Account 1


BEGIN TRANSACTION;

UPDATE Bank_Accounts
SET Balance = Balance - 100, Last_Transaction_Date = CURRENT_DATE
WHERE Account_Number = 1;

COMMIT;

SELECT * FROM Bank_Accounts;


OUTPUT

You might also like