Wa0002
Wa0002
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
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
INSERT
INSERT INTO employees (id, name, age, department_id)
VALUES (1, 'John Doe', 30, 1),
(2, 'Jane Smith', 35, 2);
DELETE
DELETE FROM employees
WHERE id = 1;
OUTPUT:
UPDATE
UPDATE employees
SET department_id = 2
WHERE name = 'John Doe';
BEFORE OUTPUT:
AFTER UPDATING:
SELECT
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 SELECT privilege on the customers table to the analyst user
GRANT SELECT ON example_db.customers TO 'analyst'@'localhost';
//-- 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;
//-- 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
);
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;
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)
);
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
);
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
);
QUERY
CREATE PROCEDURE calculateTotalSalary(@dept_id INT)
AS
BEGIN
SELECT SUM(salary) AS TotalSalary
FROM employee
OUTPUT
FUNCTION
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),
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 (
QUERY
import java.sql.*;
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/company", "username",
"password");
// Create statement object
Statement stmt = conn.createStatement();
}
System.out.println();
// 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
OUTPUT
Before update:
employee_id: 1
first_name: John
last_name: Doe
salary: 5000
employee_id: 1
first_name: John
last_name: Doe
salary: 5500 (increased by 10%)
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
);
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
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:
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;"
Console.ReadLine()
End Sub
End Module
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
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;
UPDATE Bank_Accounts
SET Balance = Balance - 100, Last_Transaction_Date = CURRENT_DATE
WHERE Account_Number = 1;
COMMIT;