Primary Key

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

CREATE TABLE Student_details (ROLL_NO INT,NAME VARCHAR(25),ADDRESS

VARCHAR(25), PHONE INT , AGE INT);

INSERT INTO Student_details(ROLL_NO,NAME,ADDRESS,PHONE,AGE) VALUES


(1,'Ram','Delhi',94155,24),(2,'Ramesh','Gurgaon',94145,21),(3,'Sujit','Delhi',98155,20),
(4,'Suresh','Noida',91155,21),(5,'Kajal','Gurgaon',89155,28),(6,'Garima','Rohtak',70155,23);

TRUNCATE TABLE Student_details;

DROP TABLE Student_details;

PRIMARY KEY

CREATE TABLE Students (


student_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
date_of_birth DATE,
phone_number VARCHAR(20),
address VARCHAR(255)
);

INSERT INTO Students VALUES


(1, 'John', 'Doe', '2000-01-15', '123-456-7890', '123 Main St'),
(2, 'Jane', 'Smith', '2001-03-20', '987-654-3210', '456 Elm St'),
(3, 'Michael', 'Johnson', '1999-07-10', '555-123-4567', '789 Oak St'),
(4, 'Emily', 'Brown', '2002-05-05', '111-222-3333', '101 Pine St'),
(5, 'William', 'Davis', '2003-09-12', '444-555-6666', '202 Maple St'),
(6, 'Emma', 'Wilson', '2000-11-25', '777-888-9999', '303 Cedar St'),
(7, 'Daniel', 'Martinez', '1998-04-30', '666-777-8888', '404 Birch St'),
(8, 'Olivia', 'Taylor', '2001-08-18', '999-000-1111', '505 Walnut St'),
(9, 'Alexander', 'Anderson', '1997-12-08', '333-444-5555', '606 Pineapple St'),
(10, 'Sophia', 'Thomas', '2002-02-28', '222-111-9999', '707 Banana St');

i) To remove all rows of a table

DELETE FROM Students;

ii) removal of a specified row/s

Syntax: DELETE FROM table_name [WHERE Condition] mysql>

DELETE FROM Students WHERE first_name = 'Johnson';

• Deletes all the rows where the sname is ‘Ramesh’ keeps all the other rows.

iii) Update Statement: It is used to make changes to existing rows of the table.
Syntax: UPDATE table_name SET column_name1 = value1, column_name2 = value2, …..
[WHERE Condition] Example:

UPDATE Students SET first_name = 'Smith', last_name = 'Jane' WHERE student_id = 1;

iv) updating all rows

UPDATE Students SET first_name ='ISR';

v) updating seleted records.

UPDATE Students SET address ='Bang' WHERE student_id =5;

CREATE TABLE Employees (


emp_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
date_of_birth DATE,
department VARCHAR(50),
job_title VARCHAR(50),
salary DECIMAL(10, 2)
);

INSERT INTO Employees (emp_id, first_name, last_name, date_of_birth, department, job_title, salary)
VALUES
(1, 'John', 'Doe', '1985-05-10', 'Human Resources', 'HR Manager', 65000.00),
(2, 'Jane', 'Smith', '1990-09-20', 'Marketing', 'Marketing Coordinator', 55000.00),
(3, 'Michael', 'Johnson', '1988-03-15', 'Finance', 'Financial Analyst', 70000.00),
(4, 'Emily', 'Brown', '1992-07-25', 'Sales', 'Sales Representative', 60000.00),
(5, 'William', 'Davis', '1987-11-05', 'IT', 'Systems Administrator', 75000.00),
(6, 'Emma', 'Wilson', '1995-01-30', 'Engineering', 'Software Engineer', 80000.00),
(7, 'Daniel', 'Martinez', '1989-12-12', 'Operations', 'Operations Manager', 72000.00),
(8, 'Olivia', 'Taylor', '1993-04-18', 'Customer Service', 'Customer Service Representative',
50000.00),
(9, 'Alexander', 'Anderson', '1986-08-08', 'Research and Development', 'Research Scientist',
85000.00),
(10, 'Sophia', 'Thomas', '1991-06-28', 'Product Management', 'Product Manager', 90000.00);
1) Display all employees
2) Display employees in a specific department (e.g., IT)
3) Display employees earning more than a certain salary (e.g., $60,000):
4) Update the job title of an employee (e.g., change job title of employee with emp_id = 3 to 'Senior
Financial Analyst')
5) Update the salary of an employee (e.g., increase salary of employee with emp_id = 5 by $5000)
6) Delete an employee from the table (e.g., delete employee with emp_id = 7)
7) Display employees born after a certain date (e.g., after January 1, 1990)
8) Display employees whose first name starts with a certain letter (e.g., 'J')
9) Update the department of an employee (e.g., change department of employee with emp_id = 4 to
'Customer Relations')
10) Delete employees based on certain criteria (e.g., delete employees whose salary is less than $50,000)
11) Display employees ordered by their salary in descending order:
12) Display the count of employees in each department

SELECT * FROM Employees;


SELECT * FROM Employees WHERE department = 'IT';
SELECT * FROM Employees WHERE salary > 60000.00;
UPDATE Employees SET job_title = 'Senior Financial Analyst' WHERE emp_id = 3;
UPDATE Employees SET salary = salary + 5000.00 WHERE emp_id = 5;
DELETE FROM Employees WHERE emp_id = 7;
SELECT * FROM Employees WHERE date_of_birth > '1990-01-01';
SELECT * FROM Employees WHERE first_name LIKE 'J%';
UPDATE Employees SET department = 'Customer Relations' WHERE emp_id = 4;
DELETE FROM Employees WHERE salary < 50000.00;
SELECT * FROM Employees ORDER BY salary DESC;
SELECT department, COUNT(*) AS employee_count FROM Employees GROUP BY department;
ALTER TABLE - ADD Column

ALTER TABLE Employees ADD COLUMN email VARCHAR(100);

ALTER TABLE - DROP COLUMN


ALTER TABLE Employees DROP COLUMN email;

ALTER TABLE - RENAME COLUMN


ALTER TABLE Employees RENAME COLUMN department TO dept_name;

ALTER TABLE - RENAME TABLE


ALTER TABLE Employees RENAME TO Staff;

ALTER TABLE - ALTER/MODIFY DATATYPE


ALTER TABLE Employees ALTER COLUMN salary DECIMAL(12, 2);

CREATE TABLE Departments (


department_name VARCHAR(100),
dept_add varchar(100));

Make department_id as primary key

ALTER TABLE Departments


ADD CONSTRAINT department_name PRIMARY KEY (department_name);

MAKE dept_name as FOREIGN KEY in Employees


INSERT INTO Departments (department_name, dept_add)
VALUES ('Human Resources', 'PU'),
('Marketing', 'PU'),
('Finance', 'PU'),
('Sales', 'PU'),
('IT', 'PU'),
('Engineering', 'PU'),
('Operations', 'PU'),
('Customer Service', 'PU'),
('Research and Development', 'PU'),
('Product Management', 'PU');

ALTER TABLE Employees


ADD CONSTRAINT fk_dept_name
FOREIGN KEY (dept_name)
REFERENCES Departments(department_name);
CREATE TABLE STUDENT (
SNUM INT PRIMARY KEY,
SNAME VARCHAR (20) NOT NULL,
MAJOR VARCHAR (5) NOT NULL,
LEVEL CHAR (5), DOB DATE);

CREATE TABLE FACULTY (


FID INT PRIMARY KEY AUTO_INCREMENT,
FNAME VARCHAR (20) NOT NULL,
ADDRESS VARCHAR (20),
DEPTID INT);

CREATE TABLE COURSE (


CNAME VARCHAR (10) PRIMARY KEY,
MEETS_AT VARCHAR (10),
ROOM VARCHAR (5),
FID INTEGER, FOREIGN KEY(FID) REFERENCES FACULTY(FID) ON DELETE
CASCADE);

CREATE TABLE ENROLL(


SNUM INTEGER,
CNAME VARCHAR (10),
FOREIGN KEY (SNUM) REFERENCES STUDENT(SNUM) ON DELETE SET
NULL ON UPDATE CASCADE,
FOREIGN KEY (CNAME) REFERENCES COURSE(CNAME) ON DELETE SET
NULL ON UPDATE CASCADE);
CREATE TABLE ENROLL (S
NUM INTEGER,
CNAME VARCHAR (10),
PRIMARY KEY (SNUM, CNAME),
FOREIGN KEY(SNUM) REFERENCES STUDENT(SNUM) ON DELETE CASCADE,
FOREIGN KEY(CNAME) REFERENCES COURSE(CNAME) ON DELETE CASCADE);

ON DELETE CASCADE constraint is used in MySQL


to delete the rows from the child table automatically,
when the rows from the parent table are deleted.
A foreign key with "set null on delete" means that if a
record in the parent table is deleted, then the
corresponding records in the child table will have the
foreign key fields set to NULL. The records in the child
table will not be deleted in SQL Server.

INSERT INTO STUDENT (SNUM, SNAME, MAJOR, LEVEL, DOB)


VALUES
(1, 'Alice', 'CS', 'S', '2000-01-15'),
(2, 'Bob', 'Mat', 'J', '2001-05-20'),
(3, 'Charlie', 'Bio', 'S', '2002-09-10'),
(4, 'David', 'Phy', 'S', '1999-11-25'),
(5, 'Eve', 'Che', 'F', '2003-03-30');

INSERT INTO FACULTY (FNAME, ADDRESS, DEPTID)


VALUES
('Dr. John Smith', '123 Main St', 101),
('Prof. Emily Johnson', '456 Elm St', 102),
('Dr. Michael Williams', '789 Oak St', 103),
('Dr. Sarah Brown', '321 Pine St', 101),
('Prof. David Wilson', '654 Cedar St', 104);

INSERT INTO COURSE (CNAME, MEETS_AT, ROOM, FID)


VALUES
('CS101', 'Monday', 'Room1', 1),
('MATH202', 'Tuesday', 'Room2', 2),
('BIO101', 'Wednesday', 'Room3', 3),
('PHYSICS101', 'Thursday', 'Room4', 4),
('CHEM202', 'Friday', 'Room5', 5);

INSERT INTO ENROLL(SNUM, CNAME)


VALUES
(1, 'CS101'),
(2, 'MATH202'),
(3, 'BIO101'),
(4, 'PHYSICS101'),
(5, 'CHEM202');

i)Entity Integrity Constraint: Primary Key Value cannot be NULL and duplicate.
INSERT INTO STUDENT VALUES (NULL,'CHETHAN','CSE','2000-20-03',4);

INSERT INTO STUDENT(SNUM,SNAME,MAJOR,LEVEL,DOB) VALUES


(1,'CHETHAN','CSE','S','2000-05-03');
ii)DOMAIN Constraint: incorrect date format(‘YYYY-MM-DD’)
INSERT INTO STUDENT(SNUM,SNAME,MAJOR,LEVEL,DOB) VALUES
(6,'CHETHAN','CSE','S','03-04-2000');

INSERT INTO STUDENT(SNUM,SNAME,MAJOR,LEVEL,DOB) VALUES


(6,'CHETHAN','CSE',4,'03-04-2000');

iii)Referential Integrity Constraint:

INSERT INTO COURSE VALUES('PYTHON','MON','DGL01',123);


Suppose you are tasked with designing a database system for a retail
banking institution. The institution offers various banking services
such as savings accounts, loans, and employs staff across different
branches. Customers can open accounts, apply for loans, and interact
with employees for assistance. How would you design the database
schema to efficiently manage customer accounts, loans, branches, and
employees, ensuring data integrity and optimal performance?
Based on this scenario, you can proceed to design the tables with
appropriate attributes and establish relationships between them.
For example:
1. Customer:
Attributes: `customer_id` (unique identifier), `name`,
`email`, `phone`.
2. Account:
Attributes: `account_id` (unique identifier), `customer_id`
(foreign key referencing `customer_id` in `Customer` table),
`account_type`, `balance`.
3. Branch:
Attributes: `branch_id` (unique identifier), `name`,
`location`.
4. Loan:
Attributes: `loan_id` (unique identifier), `account_id`
(foreign key referencing `account_id` in `Account` table),
`amount`, `interest_rate`.
5. Employee:
-Attributes: `employee_id` (unique identifier), `name`,
`branch_id` (foreign key referencing `branch_id` in `Branch`
table).

ALTER TABLE Employees


ADD CONSTRAINT fk_dept_name
FOREIGN KEY (dept_name)
REFERENCES Departments(department_name);
-- Create Customer table
CREATE TABLE Customer (
customer_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(20)
);

-- Create Account table


CREATE TABLE Account (
account_id INT PRIMARY KEY,
customer_id INT,
account_type VARCHAR(50),
balance DECIMAL(15, 2),
FOREIGN KEY (customer_id) REFERENCES Customer(customer_id)
);

-- Create Branch table


CREATE TABLE Branch (
branch_id INT PRIMARY KEY,
name VARCHAR(100),
location VARCHAR(100)
);

-- Create Loan table


CREATE TABLE Loan (
loan_id INT PRIMARY KEY,
account_id INT,
amount DECIMAL(15, 2),
interest_rate DECIMAL(5, 2),
FOREIGN KEY (account_id) REFERENCES Account(account_id)
);

-- Create Employee table


CREATE TABLE Employee (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
branch_id INT,
FOREIGN KEY (branch_id) REFERENCES Branch(branch_id)
);

-- Inserting sample data into Customer table


INSERT INTO Customer (customer_id, name, email, phone)
VALUES
(1, 'John Doe', 'john@example.com', '123-456-7890'),
(2, 'Jane Smith', 'jane@example.com', '987-654-3210'),
(3, 'Michael Johnson', 'michael@example.com', '555-123-4567'),
(4, 'Emily Davis', 'emily@example.com', '444-789-0123'),
(5, 'Chris Brown', 'chris@example.com', '666-333-9999');

-- Inserting sample data into Account table


INSERT INTO Account (account_id, customer_id, account_type, balance)
VALUES
(101, 1, 'Savings', 5000.00),
(102, 2, 'Checking', 2500.00),
(103, 3, 'Savings', 10000.00),
(104, 4, 'Checking', 7500.00),
(105, 5, 'Savings', 3000.00);

-- Inserting sample data into Branch table


INSERT INTO Branch (branch_id, name, location)
VALUES
(201, 'Main Branch', 'New York, NY'),
(202, 'Downtown Branch', 'Los Angeles, CA'),
(203, 'Uptown Branch', 'Chicago, IL'),
(204, 'Eastside Branch', 'Miami, FL'),
(205, 'Westside Branch', 'Seattle, WA');

-- Inserting sample data into Loan table


INSERT INTO Loan (loan_id, account_id, amount, interest_rate)
VALUES
(301, 101, 10000.00, 5.25),
(302, 103, 20000.00, 6.00),
(303, 104, 15000.00, 4.75),
(304, 102, 5000.00, 4.50),
(305, 105, 8000.00, 5.75);

-- Inserting sample data into Employee table


INSERT INTO Employee (employee_id, name, branch_id)
VALUES
(401, 'Alex Johnson', 201),
(402, 'Sarah Wilson', 202),
(403, 'Ryan Martinez', 203),
(404, 'Emma Thompson', 204),
(405, 'David Garcia', 205);

SELECT Command:

SELECT count(*) AS "Total Number of Records" FROM student;


SELECT COUNT(*) AS "Total Number of Records" FROM student WHERE level ='s';

ALTER TABLE student ADD COLUMN marks INT;


UPDATE student SET marks = 10;
SELECT snum, sname, marks + 20 FROM student;

SELECT sname, (marks/500)*100 FROM student WHERE snum > 1;

SELECT DISTINCT sname FROM student;

Conditions based on a range

SELECT snum, sname FROM student WHERE snum BETWEEN 1 AND 5;

SELECT snum, sname FROM student WHERE snum LIKE "%3";

SELECT snum, sname FROM student WHERE sname LIKE "%D";

SELECT AVG(SNUM) AS AVG_SNUM FROM student GROUP BY department;


CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
date_of_birth DATE,
department VARCHAR(50),
job_title VARCHAR(50),
salary DECIMAL(10, 2)
);

INSERT INTO Employees (emp_id, first_name, last_name, date_of_birth, department, job_title, salary)
VALUES
(1, 'John', 'Doe', '1985-05-10', 'Human Resources', 'HR Manager', 65000.00),
(2, 'Jane', 'Smith', '1990-09-20', 'Marketing', 'Marketing Coordinator', 55000.00),
(3, 'Michael', 'Johnson', '1988-03-15', 'Finance', 'Financial Analyst', 70000.00),
(4, 'Emily', 'Brown', '1992-07-25', 'Sales', 'Sales Representative', 60000.00),
(5, 'William', 'Davis', '1987-11-05', 'IT', 'Systems Administrator', 75000.00),
(6, 'Emma', 'Wilson', '1995-01-30', 'Engineering', 'Software Engineer', 80000.00),
(7, 'Daniel', 'Martinez', '1989-12-12', 'Operations', 'Operations Manager', 72000.00),
(8, 'Olivia', 'Taylor', '1993-04-18', 'Customer Service', 'Customer Service Representative',
50000.00),
(9, 'Alexander', 'Anderson', '1986-08-08', 'Research and Development', 'Research Scientist',
85000.00),
(10, 'Sophia', 'Thomas', '1991-06-28', 'Product Management', 'Product Manager', 90000.00);

SELECT MAX(Salary) AS Max_Salary FROM EMPLOYEEs;


SELECT MIN(Salary) AS Min_Salary FROM EMPLOYEEs;
SELECT SUM(Salary) AS Total_Salary FROM EMPLOYEEs;
SELECT COUNT(emp_id) AS Employee_Count, AVG(Salary) AS Average_Salary FROM
EMPLOYEEs;
SELECT count(*) AS "Total Number of Records" FROM employees;
SELECT count(emp_id) AS "Total Number of Records" FROM employees;
SELECT count(emp_id) AS "Total Number of Records" FROM employees where first_name="Doe";
SELECT count(emp_id) AS "Total Number of Records" FROM employees where first_name="John";
SELECT emp_id, first_name, salary + 20 FROM employees;
SELECT emp_id, (salary/500)*100 FROM employees WHERE emp_id > 5;
SELECT emp_id, (salary/500)*100 as new_salary FROM employees WHERE emp_id > 5;
SELECT DISTINCT first_name FROM employees;

SELECT emp_id, salary FROM employees WHERE salary BETWEEN 65000 AND 75000;

SELECT emp_id, first_name, last_name, dept_name FROM employees WHERE first_name LIKE
"%M";
SELECT emp_id, first_name, last_name, dept_name FROM employees WHERE first_name LIKE "J
%";
SELECT * FROM employees WHERE first_name LIKE '_o__';

This query will select all rows from the employees table where the 'first_name' column has exactly
four characters and the second character is 'o'.
Remember, in SQL, the underscore character (_) matches any single character, and the percent sign
(%) matches any sequence of characters.
CREATE TABLE Students (
student_id INT PRIMARY KEY, first_name VARCHAR(50),
last_name VARCHAR(50), date_of_birth DATE, address VARCHAR(100),
city VARCHAR(50), state VARCHAR(50), country VARCHAR(50),
email VARCHAR(100), marks INT );

INSERT INTO Students


VALUES
(1, 'John', 'Doe', '2000-05-15', '123 Main St', 'New York', 'NY', 'USA', 'john@example.com', 85),
(2, 'Jane', 'Smith', '2001-08-20', '456 Elm St', 'Los Angeles', 'CA', 'USA', 'jane@example.com', 92),
(3, 'Michael', 'Johnson', '1999-12-10', '789 Oak St', 'Chicago', 'IL', 'USA', 'michael@example.com',
78),
(4, 'Emily', 'Williams', '2000-04-25', '321 Pine St', 'Houston', 'TX', 'USA', 'emily@example.com', 88),
(5, 'David', 'Brown', '2001-02-18', '654 Maple St', 'Phoenix', 'AZ', 'USA', 'david@example.com', 90),
(6, 'Sarah', 'Jones', '1999-09-05', '987 Cedar St', 'Philadelphia', 'PA', 'USA', 'sarah@example.com', 85),
(7, 'Christopher', 'Davis', '2000-07-12', '135 Walnut St', 'San Antonio', 'TX', 'USA',
'chris@example.com', 82),
(8, 'Jessica', 'Miller', '2001-01-30', '246 Birch St', 'San Diego', 'CA', 'USA', 'jessica@example.com',
95),
(9, 'Daniel', 'Wilson', '1999-11-08', '579 Spruce St', 'Dallas', 'TX', 'USA', 'daniel@example.com', 87),
(10, 'Amanda', 'Taylor', '2000-06-22', '753 Fir St', 'San Jose', 'CA', 'USA', 'amanda@example.com',
91),
(11, 'Matthew', 'Anderson', '2001-03-17', '159 Cherry St', 'Austin', 'TX', 'USA',
'matthew@example.com', 84),
(12, 'Ashley', 'Martinez', '1999-10-04', '357 Pineapple St', 'Jacksonville', 'FL', 'USA',
'ashley@example.com', 89),
(13, 'Andrew', 'Hernandez', '2000-08-09', '753 Mango St', 'Indianapolis', 'IN', 'USA',
'andrew@example.com', 88),
(14, 'Taylor', 'Young', '2001-04-26', '246 Peach St', 'San Francisco', 'CA', 'USA',
'taylor@example.com', 93),
(15, 'Lauren', 'Lee', '1999-12-15', '579 Banana St', 'Columbus', 'OH', 'USA', 'lauren@example.com',
86),
(16, 'Ryan', 'Gonzalez', '2000-05-28', '357 Orange St', 'Charlotte', 'NC', 'USA', 'ryan@example.com',
87),
(17, 'Brittany', 'Clark', '2001-02-03', '159 Lemon St', 'Fort Worth', 'TX', 'USA',
'brittany@example.com', 90),
(18, 'Nicholas', 'Lewis', '1999-09-20', '753 Grape St', 'Detroit', 'MI', 'USA', 'nicholas@example.com',
82),
(19, 'Kayla', 'Walker', '2000-07-07', '246 Kiwi St', 'Memphis', 'TN', 'USA', 'kayla@example.com', 91),
(20, 'Brandon', 'Hall', '2001-01-14', '579 Strawberry St', 'Boston', 'MA', 'USA',
'brandon@example.com', 88),
(21, 'John', 'Doe', '2000-05-15', '123 Main St', 'New York', 'NY', 'USA', 'john@example.com', NULL);

SELECT sum(marks) FROM students;


SELECT min(student_id), max(marks) FROM students;

SELECT ASCII('a');
SELECT ASCII('A');
SELECT ASCII('1');
SELECT ASCII('ABC');
SELECT LOWER('STRING FUNCTION');
SELECT UPPER(first_name) from students;
SELECT LENGTH('STRING FUNCTION');
SELECT LENGTH(first_name) from students;
SELECT LEFT('STRING FUNCTION', 6);
SELECT RIGHT('STRING FUNCTION', 6);
SELECT REVERSE('STRING FUNCTION');
SELECT REVERSE (first_name) from students;
SELECT SUBSTRING('STRING FUNCTION', 1, 6);
SELECT SUBSTRING('STRING FUNCTION', 8, 8);
It starts extracting from the 8th position ('F') and continues for a length of 8 characters,
resulting in 'FUNCTION'.
SELECT NOW();
SELECT SYSDATE();
Select first_name, state From Students Where state not in ('ny','ca','tx');
Select first_name, state From Students Where state in ('ny','ca','tx');
Select first_name, last_name From Students Where marks IS NULL;
Select first_name, last_name From Students Where marks IS NOT NULL;
SELECT state, AVG(marks) AS average_marks
FROM Students
GROUP BY state;

SELECT city, AVG(marks) AS average_marks


FROM Students
GROUP BY city;

SELECT city, AVG(marks) AS average_marks


FROM Students
GROUP BY city
HAVING AVG(marks) >= 85;

SELECT state, AVG(marks) AS average_marks


FROM Students
GROUP BY state
HAVING AVG(marks) > 85;

SELECT *
FROM Students
ORDER BY marks DESC;

SELECT state, AVG(marks) AS average_marks


FROM Students
GROUP BY state
ORDER BY average_marks DESC;
-- Create BRANCH table
CREATE TABLE BRANCH (
BR_NAME VARCHAR(20) PRIMARY KEY,
BR_CITY VARCHAR(20),
ASSETS REAL
);

-- Create ACCOUNT table


CREATE TABLE ACCOUNT (
ACCNO INT PRIMARY KEY,
BR_NAME VARCHAR(20),
BALANCE REAL,
FOREIGN KEY (BR_NAME) REFERENCES BRANCH(BR_NAME) ON DELETE CASCADE
);

-- Create CUSTOMER table


CREATE TABLE CUSTOMER (
CUST_NAME VARCHAR(20) PRIMARY KEY,
CUST_STREET VARCHAR(20),
CUST_CITY VARCHAR(20)
);

-- Create DEPOSITOR table


CREATE TABLE DEPOSITOR (
CUST_NAME VARCHAR(20),
ACCNO INT,
PRIMARY KEY (CUST_NAME, ACCNO),
FOREIGN KEY (CUST_NAME) REFERENCES CUSTOMER(CUST_NAME) ON DELETE
CASCADE,
FOREIGN KEY (ACCNO) REFERENCES ACCOUNT(ACCNO) ON DELETE CASCADE
);
-- Create LOAN table
CREATE TABLE LOAN (
LOAN_NO INT PRIMARY KEY,
BR_NAME VARCHAR(20),
AMOUNT REAL,
FOREIGN KEY (BR_NAME) REFERENCES BRANCH(BR_NAME) ON DELETE CASCADE
);

-- Create BORROWER table


CREATE TABLE BORROWER (
CUST_NAME VARCHAR(20),
LOAN_NO INT,
PRIMARY KEY (CUST_NAME, LOAN_NO),
FOREIGN KEY (CUST_NAME) REFERENCES CUSTOMER(CUST_NAME) ON DELETE
CASCADE,
FOREIGN KEY (LOAN_NO) REFERENCES LOAN(LOAN_NO) ON DELETE CASCADE
);

INSERT INTO BRANCH VALUES


('KORMANGALA' , 'BENGALURU' , 20500.3),
('SADASHIVANAGAR' , 'BENGALURU' , 154329.5),
('VITTALNAGAR' , 'HYDERABAD' , 350000),
('KASTHURINAGAR' , 'DELHI' , 125000),
('MARUTINAGAR' , 'HYDERABAD' , 212351.6),
('RAJANKUNTE' , 'MUMBAI' , 53535.8);

INSERT INTO ACCOUNT VALUES


(123456 , 'KORMANGALA' , 5000),
(123457 , 'SADASHIVANAGAR' , 35000),
(123458 , 'VITTALNAGAR' , 60000),
(123459 , 'KASTHURINAGAR' , 255600),
(123460 , 'VITTALNAGAR' , 37890),
(123461 , 'MARUTINAGAR' , 20000),
(123462 , 'SADASHIVANAGAR' , 40000);
INSERT INTO CUSTOMER VALUES
('KAVYA' , 'SADASHIVANAGAR' , 'BENGALURU'),
('ABHAY' , 'KAMALANAGAR' , 'TUMKUR'),
('SHEETAL' , 'KASTHURINAGAR' , 'BENGALURU'),
('KSHAMITHA' , 'MARUTILAYOUT' , 'TUMKUR'),
('LIKITH' , 'MADHURANAGAR' , 'HYDERABAD'),
('SACHIN' , 'VITTALNAGAR' , 'HYDERABAD');

INSERT INTO DEPOSITOR VALUES


('KAVYA' , 123457),
('ABHAY' , 123456),
('KAVYA' , 123456),
('KSHAMITHA' , 123458),
('KSHAMITHA' , 123460),
('LIKITH' , 123461),
('KAVYA' , 123462);

INSERT INTO LOAN VALUES


(231 , 'SADASHIVANAGAR' , 50500.5),
(232 , 'VITTALNAGAR' , 25000),
(233 , 'MARUTINAGAR' , 60300.3),
(234 , 'KASTHURINAGAR' , 45000.7),
(235 , 'KORMANGALA' , 25534);

INSERT INTO BORROWER VALUES


('KAVYA' , 231),
('KSHAMITHA' , 232),
('ABHAY' , 235),
('LIKITH' , 234),
('SACHIN' , 233);
1. Find bank accounts with a balance greater than 20000
SELECT * FROM ACCOUNT WHERE BALANCE > 20000;

2. Display results in increasing order of balance


SELECT * FROM ACCOUNT ORDER BY BALANCE;

3. Retrieve a list of all bank branch details, ordered by branch city, with each city’s branches
listed in reverse order of assets
SELECT BR_NAME, BR_CITY, ASSETS FROM BRANCH ORDER BY BR_CITY,
ASSETS DESC;

4. Find average balance of accounts at Sadashivanagar branch


SELECT AVG(BALANCE) FROM ACCOUNT WHERE BR_NAME= 'SADASHIVANAGAR';

5. Find the number of branches that currently have loans


SELECT COUNT(DISTINCT BR_NAME) FROM LOAN;

6. Find the number of branches that currently DONT have loans


7. Find branch names of Bengaluru city
8. Find number of accounts present in each branch
9. Find sum of balance of accounts at each branch
10. Find sum of balance of loan accounts at each branch
11. Find the city of a customer with account number 123456
SELECT CUST_CITY FROM CUSTOMER WHERE CUST_NAME = (SELECT
CUST_NAME FROM DEPOSITOR WHERE ACCNO = 123456);

12. Find branch names without account

13. Find the loan amount borrowed by a customer Abhay

14. Find the branch name and balance of a customer kavya with account number 123456

15. Find the loan amount taken by each customer

16. Display the loan details of a customer Kavya

17. Find the city of branch with loan number 100

18. Find the number of accounts of each customer

19. Find customers with an account but not a loan

20. Find all cities with more than two customers living in the city

21. Find all the customers who have at least two accounts at the main branch.

22. Demonstrate how you delete all account tuples at every branch located in a specific city.

23. Find all the customers who have an account at all the branches located in a specific city.

24. Find all the customers with more than one loan

25. Find branches with assets greater than all branches in Bangalore
1. SELECT * FROM ACCOUNT WHERE BALANCE > 20000;
2. SELECT * FROM ACCOUNT ORDER BY BALANCE;
3. SELECT BR_NAME, BR_CITY, ASSETS FROM BRANCH ORDER BY BR_CITY,
ASSETS DESC;
4. SELECT BR_NAME, BR_CITY, ASSETS FROM BRANCH ORDER BY BR_CITY,
ASSETS DESC;
5. SELECT COUNT(DISTINCT BR_NAME) FROM LOAN;
6. SELECT COUNT(*) FROM BRANCH WHERE BR_NAME NOT IN (SELECT BR_NAME
FROM LOAN);
7. SELECT BR_NAME FROM BRANCH WHERE BR_CITY = 'BENGALURU';
8. SELECT BR_NAME, COUNT(*) AS ACCOUNT_COUNT FROM ACCOUNT GROUP BY
BR_NAME;
9. SELECT BR_NAME, SUM(BALANCE) AS TOTAL_BALANCE FROM ACCOUNT
GROUP BY BR_NAME;
10. SELECT BR_NAME, SUM(AMOUNT) AS TOTAL_LOAN_BALANCE FROM LOAN
GROUP BY BR_NAME;
11. SELECT CUST_CITY FROM CUSTOMER WHERE CUST_NAME = (SELECT
CUST_NAME FROM DEPOSITOR WHERE ACCNO = 123456);
12. SELECT BR_NAME FROM BRANCH WHERE BR_NAME NOT IN (SELECT DISTINCT
BR_NAME FROM ACCOUNT);
13. SELECT SUM(AMOUNT) AS TOTAL_LOAN_AMOUNT FROM LOAN WHERE
LOAN_NO IN (SELECT LOAN_NO FROM BORROWER WHERE CUST_NAME =
'ABHAY');
14. SELECT BR_NAME, BALANCE
FROM ACCOUNT
WHERE ACCNO = 123456
AND BR_NAME = (SELECT BR_NAME FROM DEPOSITOR WHERE CUST_NAME =
'KAVYA' AND ACCNO = 123456);
15. SELECT CUST_NAME, SUM(AMOUNT) AS TOTAL_LOAN_AMOUNT
FROM LOAN
WHERE LOAN_NO IN (SELECT LOAN_NO FROM BORROWER WHERE
CUST_NAME = 'KAVYA' OR CUST_NAME = 'ABHAY')
GROUP BY CUST_NAME;
16. SELECT L.* FROM LOAN L JOIN BORROWER B ON L.LOAN_NO = B.LOAN_NO
WHERE B.CUST_NAME = 'KAVYA';
17. SELECT BR_CITY FROM BRANCH WHERE BR_NAME = (SELECT BR_NAME FROM
LOAN WHERE LOAN_NO = 100);
18. SELECT CUST_NAME, COUNT(*) AS ACCOUNT_COUNT FROM DEPOSITOR
GROUP BY CUST_NAME;
19. SELECT CUST_NAME FROM CUSTOMER WHERE CUST_NAME IN (SELECT
CUST_NAME FROM DEPOSITOR) AND CUST_NAME NOT IN (SELECT
CUST_NAME FROM BORROWER);
20. SELECT CUST_CITY FROM CUSTOMER GROUP BY CUST_CITY HAVING COUNT(*)
> 2;
21. SELECT CUST_NAME FROM DEPOSITOR WHERE BR_NAME = 'MAIN' GROUP BY
CUST_NAME HAVING COUNT(*) >= 2;
22. DELETE FROM ACCOUNT WHERE BR_NAME IN (SELECT BR_NAME FROM
BRANCH WHERE BR_CITY = 'CITY_NAME');
23. SELECT CUST_NAME
FROM DEPOSITOR
WHERE BR_NAME IN (SELECT BR_NAME FROM BRANCH WHERE BR_CITY =
'CITY_NAME')
GROUP BY CUST_NAME
HAVING COUNT(DISTINCT BR_NAME) = (SELECT COUNT(DISTINCT BR_NAME)
FROM BRANCH WHERE BR_CITY = 'CITY_NAME');

24. SELECT CUST_NAME


FROM BORROWER
GROUP BY CUST_NAME
HAVING COUNT(*) > 1;

25. SELECT BR_NAME, ASSETS


FROM BRANCH
WHERE ASSETS > ALL (SELECT ASSETS FROM BRANCH WHERE BR_CITY =
'BENGALURU');

To Study and Implement different types of Set


Operation in SQL.

UNION: This operation combines the results of two or more SELECT statements into a
single result set. It removes duplicate rows by default.
Example:
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;

Combine the list of branches and customers' cities.


SELECT BR_CITY FROM BRANCH
UNION
SELECT CUST_CITY FROM CUSTOMER;
UNION ALL: Similar to UNION, but it includes all rows from all tables, including
duplicates.
Example:
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;

Combine all cities from both tables, including duplicates.


SELECT BR_CITY FROM BRANCH
UNION ALL
SELECT CUST_CITY FROM CUSTOMER;

INTERSECT: This operation returns only the rows that appear in both result sets of two
SELECT statements.
Example:
SELECT column1 FROM table1
INTERSECT
SELECT column1 FROM table2;

Find the cities that appear in both the branch and customer tables.
SELECT BR_CITY FROM BRANCH
INTERSECT
SELECT CUST_CITY FROM CUSTOMER;

EXCEPT (or MINUS in some databases): This operation returns the rows that are present in
the first result set but not in the second result set.
Example:
SELECT column1 FROM table1
EXCEPT
SELECT column1 FROM table2;
Find the cities that are in the branch table but not in the customer table
SELECT BR_CITY FROM BRANCH
EXCEPT
SELECT CUST_CITY FROM CUSTOMER;

SELECT BR_NAME
FROM BRANCH
WHERE BR_NAME NOT IN (SELECT BR_NAME FROM LOAN);

CARTESIAN PRODUCT:
SELECT * FROM BRANCH CROSS JOIN CUSTOMER;

CREATE TABLE DEPARTMENT (


DEPT_ID INT PRIMARY KEY,
DEPT_NAME VARCHAR(20)
);
CREATE TABLE EMPLOYEE (
EMP_ID INT PRIMARY KEY,
EMP_NAME VARCHAR(20),
DEPT_NUM INT,
FOREIGN KEY (DEPT_NUM) REFERENCES DEPARTMENT (DEPT_ID) ON
DELETE CASCADE
);

INSERT INTO DEPARTMENT VALUES(1,'Accounting');


INSERT INTO DEPARTMENT VALUES(2,'Sales');
INSERT INTO DEPARTMENT VALUES(3,'Marketing');

INSERT INTO EMPLOYEE VALUES(1,'Alice',NULL);


INSERT INTO EMPLOYEE VALUES(2,'Bob',1);
INSERT INTO EMPLOYEE VALUES(3,'Charles',2);
INSERT INTO EMPLOYEE VALUES(4,'Dan',1);

EQUI JOIN OPERATION:

SELECT EMP_NAME, DEPT_NAME


FROM EMPLOYEE E
JOIN DEPARTMENT D ON E.DEPT_NUM= D.DEPT_ID;

JOIN WITH NOT EQUALITY OPERATOR(NON EQUI JOIN):

SELECT EMP_NAME, DEPT_NAME


FROM EMPLOYEE E
JOIN DEPARTMENT D ON E.DEPT_NUM <> D.DEPT_ID;
EQUI JOIN WITH SPECIFIED CONDITION:

SELECT EMP_NAME, DEPT_NAME


FROM EMPLOYEE E
JOIN DEPARTMENT D ON E.DEPT_NUM <> D.DEPT_ID
WHERE D.DEPT_NAME = 'MARKETING';

LEFT OUTER JOIN OR LEFT JOIN:

SELECT *
FROM EMPLOYEE E
LEFT JOIN
DEPARTMENT D ON E.DEPT_NUM = D.DEPT_ID;

RIGHT OUTER JOIN OR RIGHT JOIN:

SELECT * FROM EMPLOYEE E

RIGHT JOIN

DEPARTMENT D

ON E.DEPT_NUM=D.DEPT_ID;

COMBINATION OF SET AND JOIN OPERATIONS

SELECT * FROM EMPLOYEE E LEFT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID

UNION

SELECT * FROM EMPLOYEE E RIGHT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID;

NATURAL JOIN Operation:

ALTER TABLE EMPLOYEE


CHANGE COLUMN DEPT_NUM DEPT_ID INT;

SELECT * FROM DEPARTMENT NATURAL JOIN EMPLOYEE;

To study and implement Sub queries/Nested queries, Correlated nested queries in SQL.
CREATE TABLE Student (
sid INTEGER PRIMARY KEY,
sname VARCHAR(20),
major VARCHAR(20),
address VARCHAR(20),
level VARCHAR(20),
age INTEGER,
DOB DATE
);

CREATE TABLE Faculty (


fid INTEGER PRIMARY KEY,
fname VARCHAR(20),
address VARCHAR(20),
deptid INTEGER
);

CREATE TABLE Course (


cname VARCHAR(20) PRIMARY KEY,
meets_at VARCHAR(20),
room VARCHAR(20),
fid INTEGER,
FOREIGN KEY (fid) REFERENCES Faculty (fid)
);
CREATE TABLE Enrolled (
sid INTEGER,
cname VARCHAR(20),
FOREIGN KEY (sid) REFERENCES Student (sid),
FOREIGN KEY (cname) REFERENCES Course (cname)
);

INSERT INTO STUDENT (SID, SNAME, MAJOR, LEVEL, AGE, ADDRESS, DOB)
VALUES
(101, 'ABHI', 'CSE', 'JR', 19, 'BANGALORE', '1980-01-23'),
(102, 'ANIL', 'ISE', 'JR', 18, 'DAVANAGERE', '1984-02-12'),
(103, 'BHAVYA', 'ISE', 'SR', 20, 'CHITRADURGA', '1998-03-22'),
(104, 'CHETHAN', 'CSE', 'JR', 19, 'BELAGAVI', '1999-04-26'),
(105, 'SURESH', 'MECH', 'JR', 18, 'HUBLI', '1970-12-20'),
(106, 'JAYANTH', 'CSE', 'SR', 20, 'DHARVAD', '1988-11-16');

INSERT INTO FACULTY (FID, FNAME, DEPTID, ADDRESS)


VALUES
(1001, 'RAJAN', 41, 'BANGALORE'),
(1002, 'MANJU', 42, 'BELAGAVI'),
(1003, 'SUKRUTH', 43, 'CHITRADURGA'),
(1004, 'NAGARAJA', 44, 'BANGALORE'),
(1005, 'AFROZ', 41, 'BANGALORE'),
(1006, 'RAM', 42, 'BANGALORE'),
(1007, 'AHMED', 45, 'BANGALORE'),
(1008, 'SUNITHA', 46, 'BANGALORE'),
(1009, 'SRIVINAY', 42, 'HUBLI');
INSERT INTO COURSE (CNAME, MEETS_AT, ROOM, FID)
VALUES
('DBMS', '9:00', 'NG01', 1001),
('TOC', '10:00', 'KG04', 1008),
('BIGDATA', '10:00', 'KF04', 1009),
('DATA MINING', '10:00', 'KF03', 1009),
('AI', '10:00', 'NG02', 1001),
('MP', '11:15', 'NG03', 1002),
('OOPS', '12:10', 'NG04', 1002),
('COA', '01:10', 'NG05', 1003),
('SE', '01:05', 'NG06', 1004),
('OS', '02:05', 'KG01', 1005);

INSERT INTO ENROLLED (SID, CNAME)


VALUES
(101, 'DBMS'),
(105, 'TOC'),
(106, 'BIGDATA'),
(106, 'AI'),
(102, 'DATA MINING'),
(103, 'DBMS'),
(101, 'TOC'),
(104, 'TOC'),
(105, 'BIGDATA'),
(106, 'MP');

SELECT DISTINCT S.SNAME


FROM STUDENT S
JOIN ENROLLED E ON S.SID = E.SID
JOIN COURSE C ON E.CNAME = C.CNAME
JOIN FACULTY F ON C.FID = F.FID
WHERE F.FNAME = 'NARASIMHA'
AND S.LEVEL = 'JR';

SELECT C.CNAME
FROM COURSE C
WHERE C.ROOM = 'KG04' OR C.CNAME IN (
SELECT E.CNAME
FROM ENROLLED E
GROUP BY E.CNAME
HAVING COUNT(*) >= 5
);

SELECT DISTINCT S.*


FROM STUDENT S
WHERE S.SID IN (
SELECT E1.SID
FROM ENROLLED E1, ENROLLED E2, COURSE C1, COURSE C2
WHERE E1.SID = E2.SID
AND E1.CNAME <> E2.CNAME
AND E1.CNAME = C1.CNAME
AND E2.CNAME = C2.CNAME
AND C1.MEETS_AT = C2.MEETS_AT
);

SELECT DISTINCT S.sname

FROM Student S

WHERE S.sid IN (
SELECT E.sid

FROM Enrolled E

GROUP BY E.sid

HAVING COUNT(*) = (

SELECT MAX(enrollment_count)

FROM (

SELECT COUNT(*) AS enrollment_count

FROM Enrolled

GROUP BY sid

) AS max_enrollments

);

SELECT DISTINCT F.FNAME


FROM FACULTY F
WHERE F.FID IN (
SELECT C.FID
FROM COURSE C
JOIN ENROLLED E ON C.CNAME = E.CNAME
GROUP BY C.FID
HAVING COUNT(*) < 5
);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy