-- create table dept(
-- deptno int primary key,
-- dname varchar(20),
-- loc varchar(20)
-- );
-- insert into dept(deptno,dname,loc) VALUES
-- (10,'accounting','new york'),
-- (20,'research','dallas'),
-- (30,'sales','chicago'),
-- (40,'operations','boston');
-- create table emp(
-- empno int primary key,
-- ename varchar(20),
-- job varchar(20),
-- hiredate date,
-- mgr int,
-- sal int,
-- comm int,
-- deptno int references dept(deptno)
-- );
-- insert into emp(empno,ename,job,hiredate,mgr,sal,comm,deptno) values
-- (7369, 'smith', 'clerk', '1980-12-17', 7902, 800, NULL, 20),
-- (7499, 'allen', 'salesman', '1981-02-20', 7698, 1600, 300, 30),
-- (7521, 'ward', 'salesman', '1981-02-22', 7698, 1250, 500, 30),
-- (7566, 'jones', 'manager', '1981-04-02', 7839, 2975, NULL, 20),
-- (7654, 'martin', 'salesman', '1981-09-28', 7698, 1250, 1400, 30),
-- (7698, 'blake', 'manager', '1981-05-01', 7839, 2850, NULL, 30),
-- (7782, 'clark', 'manager', '1981-06-09', 7839, 2450, NULL, 10),
-- (7788, 'scott', 'analyst', '1987-04-19', 7566, 3000, NULL, 20),
-- (7839, 'king', 'president', '1981-11-17', NULL, 5000, NULL, 10),
-- (7844, 'turner', 'salesman', '1981-09-08', 7698, 1500, 0, 30),
-- (7876, 'adams', 'clerk', '1987-05-23', 7788, 1100, NULL, 20),
-- (7900, 'james', 'clerk', '1981-12-03', 7698, 950, NULL, 30),
-- (7902, 'ford', 'analyst', '1981-12-03', 7566, 3000, NULL, 20),
-- (7934, 'miller', 'clerk', '1982-01-23', 7782, 1300, NULL, 10);
-- select avg(sal) from emp where job ilike 'clerk';
-- select sum(sal) from emp where job='manager'
-- select max(sal) from emp;
-- select count(*) from emp where job='clerk' and deptno=20;
-- select count(*) from emp where job='manager';
-- select ename from emp where job='clerk' order by sal asc limit 1;
-- select ename,sal from emp where job='manager'
-- order by sal desc;
-- select count(*) from emp where job='salesman' and deptno=30;
-- select deptno,ename,sum(sal) from emp where job='clerk' group by deptno,ename;
-- select deptno,max(sal) from emp group by deptno ;
-- select * from emp where job='salesman' order by sal desc limit 1;
-- select sal from emp where job='clerk' order by hiredate asc limit 1;
-- select * from emp where job='manager' and sal=(select max(sal) from emp where
job='manager') order by hiredate asc limit 1;
-- --or
-- select * from emp where job='manager' order by hiredate asc, sal desc limit 1;
-- select * from emp where job='clerk' order by hiredate desc, sal asc limit 1;
-- select * from emp order by hiredate desc limit 4;
-- select job, count(*) from emp group by job;
-- select deptno, count(*) from emp group by deptno;
-- select job,max(sal) from emp group by job;
-- select * from emp where job='clerk' and sal>800 order by sal desc;
-- select deptno, ename from (
-- select deptno, ename, hiredate, rank() over (partition by deptno order by
hiredate asc) as rnk from emp
-- ) where rnk=1;
-- select job,ename from(
-- select job,ename,hiredate, rank() over (partition by job order by hiredate
asc) as rnk
-- from emp
-- ) where rnk=1;
-- select * from emp where job='clerk' order by ename;
-- select deptno,avg(sal) from emp group by deptno;
-- select extract(year from hiredate) as year, count(*) from emp group by year
order by year desc;
-- --3
-- select * from emp where sal=(select max(sal) from emp);
-- select ename, sal from emp where job='clerk' and deptno=(select deptno from dept
where loc='dallas' );
-- select * from dept where deptno in (select distinct deptno from emp where
job='salesman');
-- select *, sal+1000 as new_sal from emp where job='clerk' and deptno=(select
deptno from dept where dname='research');
-- select ename,sal from emp where deptno=(select deptno from dept where
loc='chicago') order by hiredate asc limit 1;
-- select loc from dept where deptno=(select deptno from emp where ename='allen');
-- select dname from dept where deptno=(select deptno from emp where
ename='scott');
-- select ename from emp where deptno=(select deptno from dept where
dname='accounting');
-- select d.dname,sum(e.sal) from emp e join dept d on e.deptno=d.deptno group by
d.dname;
-- select d.loc, count(e.empno) from emp e join dept d on e.deptno=d.deptno group
by d.loc;
-- -----------
-- select d.loc, count(e.empno) from emp e join dept d on e.deptno=d.deptno group
by d.loc;
-- select d.dname, count(e.empno) from emp e join dept d on e.deptno=d.deptno group
by d.dname;
-- select d.dname, sum(sal) from emp e join dept d on e.deptno=d.deptno group by
d.dname;
-- select ename from emp where deptno=(select deptno from dept where loc='new
york') and ename like 'c%';
-- --or
-- select e.ename from emp e join dept d on e.deptno=d.deptno where d.loc='new
york' and e.ename like 'c%';
-- select e.*, d.dname, d.loc from emp e join dept d on e.deptno=d.deptno
-- where d.loc='dallas' and e.job='clerk'
-- order by e.hiredate asc limit 1;
-- select e.*, d.dname, d.loc from emp e join dept d on e.deptno=d.deptno
-- where d.loc='chicago' and job='salesman'
-- and e.sal=(select max(sal) from emp where job='salesman');
-- --or
-- select e.*, d.dname, d.loc from emp e join dept d on e.deptno=d.deptno
-- where d.loc='chicago' and job='salesman'
-- order by sal desc limit 1;
-- select d.loc, d.dname from emp e join dept d on e.deptno=d.deptno where
e.ename='scott';
-- select count(e.empno) from emp e join dept d on e.deptno=d.deptno where
d.dname='research';
-- select e.* from emp e join dept d on e.deptno=d.deptno where
d.dname='accounting' order by hiredate asc;
-- select e.ename,e.empno,d.dname,d.loc from emp e join dept d on e.deptno=d.deptno
where e.job='president';
-- select e.* from emp e join dept d on e.deptno=d.deptno where e.job='clerk' and
d.loc='dallas' order by hiredate asc limit 1;
-- select d.dname, count(e.ename) from emp e join dept d on e.deptno=d.deptno where
e.job='manager' group by d.dname;
-- select e.ename from emp e join dept d on e.deptno=d.deptno where d.loc='chicago'
order by hiredate asc limit 1;
-- select e.* from emp e join dept d on e.deptno=d.deptno where e.job='clerk' and
d.dname='research' and extract(year from hiredate)<=1981;
-- --or
-- SELECT e.*
-- FROM emp e
-- JOIN dept d ON e.deptno = d.deptno
-- WHERE e.job = 'clerk' AND d.dname = 'research' AND e.hiredate <= '1981-12-31';
-- select loc, ename from (
-- select d.loc, e.ename, e.hiredate,rank() over (partition by d.loc order by
e.hiredate asc) as rnk from emp e join dept d on e.deptno=d.deptno
-- ) where rnk=1;
-- select dname, ename from
-- (
-- select d.dname, e.ename, e.hiredate, rank() over (partition by d.dname order
by e.hiredate asc) as rnk from emp e join dept d on e.deptno=d.deptno
-- ) where rnk=1;
--
----------------------------------------------------------------------------------
-- --2nd ASSIGNMENT
-- CREATE TABLE std_reg (
-- reg VARCHAR(10) PRIMARY KEY,
-- roll VARCHAR(10),
-- coursecode VARCHAR(10)
-- );
-- CREATE TABLE course (
-- coursecode VARCHAR(10) PRIMARY KEY,
-- coursename VARCHAR(50),
-- credits INT
-- );
-- CREATE TABLE marksgrade (
-- reg VARCHAR(10),
-- minor1 NUMERIC(4,2), -- out of 10
-- midexam NUMERIC(5,2), -- out of 30
-- minor2 NUMERIC(4,2), -- out of 10
-- endexam NUMERIC(5,2), -- out of 50
-- grade VARCHAR(2),
-- FOREIGN KEY (reg) REFERENCES std_reg(reg)
-- );
-- CREATE TABLE gradespoints (
-- grade VARCHAR(2) PRIMARY KEY,
-- points INT
-- );
-- INSERT INTO gradespoints VALUES
-- ('EX', 10),
-- ('A', 9),
-- ('B', 8),
-- ('C', 7),
-- ('D', 6),
-- ('P', 5),
-- ('F', 0);
-- INSERT INTO std_reg VALUES
-- ('R001', 'ME101', 'ME201'),
-- ('R002', 'CE102', 'CE301'),
-- ('R003', 'EE103', 'EE410');
-- INSERT INTO course VALUES
-- ('ME201', 'Thermodynamics', 4),
-- ('CE301', 'Structural Analysis', 3),
-- ('EE410', 'Power Systems', 4);
-- INSERT INTO marksgrade VALUES
-- -- Passed
-- ('R001', 8.0, 20.0, 9.0, 35.0, 'A'),
-- -- Failed due to low marks
-- ('R002', 6.0, 15.0, 6.0, 10.0, 'F'),
-- -- Absent in End Exam (NULL)
-- ('R003', 9.0, 25.0, 9.5, NULL, 'F');
-- CREATE TABLE Student (
-- sid VARCHAR(10) PRIMARY KEY,
-- sname VARCHAR(50),
-- sbranch VARCHAR(20),
-- DBMS NUMERIC(4,2),
-- DAA NUMERIC(4,2),
-- COA NUMERIC(4,2),
-- TOC NUMERIC(4,2),
-- OOPS NUMERIC(4,2),
-- stotal NUMERIC(5,2),
-- scgpa NUMERIC(3,2)
-- );
-- INSERT INTO Student VALUES
-- ('S001', 'Ravi Kumar', 'ME', 45.0, 48.0, 49.0, 47.0, 46.0, 235.0, 9.2),
-- ('S002', 'Neha Singh', 'EEE', 12.0, 38.0, 20.0, 15.0, 40.0, 125.0, 6.5),
-- ('S003', 'Arjun Reddy', 'CE', NULL, 32.0, 35.0, 34.0, 36.0, 137.0, 7.1),
-- ('S004', 'Divya Patel', 'ME', 41.0, NULL, 43.0, 45.0, 44.0, 173.0, 8.3),
-- ('S005', 'Ali Shaikh', 'EEE', 14.0, 15.0, 10.0, 20.0, 42.0, 101.0, 5.0);
-- select count(*) from student;
-- select sum(dbms) from student where dbms<17.5;
-- select count(*) from student where dbms<17.5;
-- select sid,sname from student where daa=(select max(daa) from student);
-- select sid,sname,scgpa from student where oops=(select min(oops) from student);
-- select avg(dbms) from student;
-- select sid,sname,oops,daa from student where daa<17.5 and oops>=17.5;
-- select
-- min(dbms), max(dbms),
-- min(oops), max(oops),
-- min(coa), max(coa),
-- min(toc), max(toc),
-- min(daa), max(daa)
-- from student;
-- select count(*) from student where sbranch not ilike 'cse';
-- select count(*) from student where scgpa>8.0;
-- select count(*) from student where stotal>350;
-- select sum(oops) from student where scgpa<6.0;
-- select count(*) from student where toc<17.5 and coa>=17.5;
-- SELECT COUNT(*) FROM Student
-- WHERE DBMS > 17.5 AND DAA > 17.5 AND COA > 17.5 AND TOC > 17.5 AND OOPS > 17.5;
-- select
-- sum(case when dbms<17.5 then 1 else 0 end),
-- sum(case when daa<17.5 then 1 else 0 end),
-- sum(case when coa<17.5 then 1 else 0 end),
-- sum(case when toc<17.5 then 1 else 0 end),
-- sum(case when oops<17.5 then 1 else 0 end)
-- from student;
-- select max(dbms),max(daa),max(coa),max(toc),max(oops) from student;
-- select min(dbms),min(daa),min(coa),min(toc),min(oops) from student;
-- select sbranch, count(*) from student group by sbranch;
-- select
-- sum(case when dbms is null then 1 else 0 end),
-- sum(case when daa is null then 1 else 0 end),
-- sum(case when coa is null then 1 else 0 end),
-- sum(case when toc is null then 1 else 0 end),
-- sum(case when oops is null then 1 else 0 end)
-- from student;
-- select sbranch, count(*) from student where dbms>=17.5 and daa>=17.5 and
coa>=17.5 and toc>=17.5 and oops>=17.5 group by sbranch;
-- select sbranch, count(*) from student where dbms<17.5 or daa<17.5 or coa<17.5 or
toc<17.5 or oops<17.5 group by sbranch;
-- select sbranch,max(scgpa), min(scgpa) from student group by sbranch;
-- select sbranch, count(*) from student where dbms is null or daa is null or coa
is null or toc is null or oops is null group by sbranch;
-- select sbranch, count(*) from student where dbms is not null or daa is not null
or coa is not null or toc is not null or oops is not null group by sbranch;
-- select sum(dbms),sum(daa),sum(toc),sum(coa),sum(oops) from student;
-- select sbranch, sum(stotal) from student group by sbranch;
-- SELECT 'DBMS' AS subject, MAX(DBMS) AS max_marks FROM Student WHERE DBMS > 35
-- UNION
-- SELECT 'DAA', MAX(DAA) FROM Student WHERE DAA > 35
-- UNION
-- SELECT 'COA', MAX(COA) FROM Student WHERE COA > 35
-- UNION
-- SELECT 'TOC', MAX(TOC) FROM Student WHERE TOC > 35
-- UNION
-- SELECT 'OOPS', MAX(OOPS) FROM Student WHERE OOPS > 35;
-- SELECT 'DBMS' AS subject, MIN(DBMS) FROM Student WHERE DBMS > 17.5
-- UNION
-- SELECT 'DAA', MIN(DAA) FROM Student WHERE DAA > 17.5
-- UNION
-- SELECT 'COA', MIN(COA) FROM Student WHERE COA > 17.5
-- UNION
-- SELECT 'TOC', MIN(TOC) FROM Student WHERE TOC > 17.5
-- UNION
-- SELECT 'OOPS', MIN(OOPS) FROM Student WHERE OOPS > 17.5
-- ORDER BY MIN DESC;
-- select avg(dbms) from student where dbms>30
-- union
-- select avg(daa) from student where daa>30
-- order by avg asc;
-- select sbranch, max(scgpa), min(scgpa) from student where scgpa>6.0 group by
sbranch order by max desc;
-- --or
-- SELECT sbranch, MAX(scgpa), MIN(scgpa) FROM Student
-- WHERE scgpa > 6.0
-- GROUP BY sbranch
-- ORDER BY MAX(scgpa) DESC;
-- select sbranch, count(*) from student where dbms<17.5 or daa<17.5 or coa<17.5
group by sbranch having count(*)>4 order by count(*) desc;
-- select sid,sname,scgpa from student order by scgpa DESC;
-- select sid,sname,stotal,scgpa from student order by stotal desc;
-- select sbranch, sname from student where length(sname)=(select
max(length(sname)) from student) group by sbranch, sname;
-- SELECT sbranch, sid FROM Student s1
-- WHERE scgpa = (SELECT MAX(scgpa) FROM Student s2 WHERE s1.sbranch = s2.sbranch);
-- SELECT 'DBMS' AS subject, sid FROM Student WHERE DBMS = (SELECT MAX(DBMS) FROM
Student)
-- UNION
-- SELECT 'DAA', sid FROM Student WHERE DAA = (SELECT MAX(DAA) FROM Student)
-- UNION
-- SELECT 'COA', sid FROM Student WHERE COA = (SELECT MAX(COA) FROM Student)
-- UNION
-- SELECT 'TOC', sid FROM Student WHERE TOC = (SELECT MAX(TOC) FROM Student)
-- UNION
-- SELECT 'OOPS', sid FROM Student WHERE OOPS = (SELECT MAX(OOPS) FROM Student);
--
----------------------------------------------------------------------------------
-- --common table expression
-- -- with recursive <cte_name> (<parameters>) as (
-- -- base query
-- -- union all
-- -- main query
-- -- )
-- -- select ... from <cte_name>;
-- with recursive emp_hierarchy (empno,ename,mgr,level) as (
-- select empno,ename,mgr,1 as level
-- from emp
-- where mgr is null
-- union all
-- select e.empno,e.ename,e.mgr,h.level+1
-- from emp e join emp_hierarchy h
-- on e.mgr=h.empno
-- )
-- select * from emp_hierarchy
-- order by level,mgr asc nulls first ;
-- do $$
-- declare
-- rec record;
-- stack int[] := array[]::int[];
-- curr_mgr int := null;
-- begin
-- for rec in select empno from emp where mgr is null
-- loop
-- stack := array_append(stack,rec.empno);
-- end loop;
-- while array_length(stack,1)>0
-- loop
-- curr_mgr := stack[array_length(stack,1)];
-- stack := stack[1:array_length(stack,1)-1];
-- raise notice 'Manager: %', curr_mgr;
-- for rec in select empno from emp where mgr=curr_mgr
-- loop
-- raise notice ' Employee: %', rec.empno;
-- stack := array_append(stack, rec.empno);
-- end loop;
-- end loop;
-- end $$ language plpgsql;
-- INSERT INTO emp(empno, ename, job, hiredate, mgr, sal, comm, deptno) VALUES
-- (1, 'Alice', 'Manager', '2020-01-01', 3, 5000, NULL, 10),
-- (2, 'Bob', 'Clerk', '2020-02-01', 1, 3000, NULL, 10),
-- (3, 'Charlie', 'Analyst', '2020-03-01', 2, 4000, NULL, 10);
-- with recursive friend_cycle(empno,ename,mgr,path,cycle_found) as
-- (
-- select empno,ename,mgr,array[empno] as path, false as cycle_found
-- from emp
-- union all
-- select e.empno,e.ename,e.mgr,fc.path||e.empno, e.empno=any(fc.path) as
cycle_found
-- from friend_cycle fc join emp e on fc.mgr=e.empno
-- where not fc.cycle_found
-- )
-- select distinct empno,ename,mgr,path from friend_cycle
-- where cycle_found=true;
-- DROP TABLE IF EXISTS marksgrade;
-- DROP TABLE IF EXISTS reg;
-- DROP TABLE IF EXISTS course;
-- DROP TABLE IF EXISTS gradepoints;
-- DROP TABLE IF EXISTS temp_student_data;
-- -- Create the 'course' table first (no dependencies)
-- CREATE TABLE course (
-- CourseCode VARCHAR PRIMARY KEY,
-- CourseName VARCHAR,
-- Credits INT
-- );
-- -- Create students table to store unique student records
-- CREATE TABLE students (
-- RegNo VARCHAR PRIMARY KEY,
-- Dept VARCHAR
-- );
-- -- Create the 'reg' table with RegID as PRIMARY KEY and a unique constraint on
(RegNo, CourseCode)
-- CREATE TABLE reg (
-- RegID INT PRIMARY KEY,
-- RegNo VARCHAR NOT NULL,
-- RollNo VARCHAR,
-- Ayear INT,
-- Asem INT,
-- PYS VARCHAR,
-- CourseCode VARCHAR NOT NULL,
-- Dept VARCHAR,
-- FOREIGN KEY (CourseCode) REFERENCES course(CourseCode),
-- FOREIGN KEY (RegNo) REFERENCES students(RegNo),
-- CONSTRAINT unique_student_course UNIQUE (RegNo, CourseCode)
-- );
-- -- Create 'marksgrade' table related to reg
-- CREATE TABLE marksgrade (
-- RegNo VARCHAR,
-- CourseCode VARCHAR,
-- Grade VARCHAR,
-- PRIMARY KEY (RegNo, CourseCode),
-- FOREIGN KEY (RegNo, CourseCode) REFERENCES reg(RegNo, CourseCode)
-- );
-- -- Create the 'gradepoints' table for grade conversion
-- CREATE TABLE gradepoints (
-- Grade VARCHAR PRIMARY KEY,
-- Points INT CHECK (Points BETWEEN 0 AND 10)
-- );
-- -- Create a temporary table for loading data
-- CREATE TEMP TABLE temp_student_data (
-- RegID INT,
-- Ayear INT,
-- Asem INT,
-- PYS INT,
-- CourseCode VARCHAR,
-- CourseName VARCHAR,
-- Credits INT,
-- RegNo VARCHAR,
-- Grade VARCHAR,
-- Dept VARCHAR
-- );
-- -- Load the CSV data into the temporary table
-- COPY temp_student_data FROM 'C:\Users\sheik\Desktop\Student-Data-2025.csv' WITH
CSV HEADER;
-- -- Insert grade points into 'gradepoints' table
-- INSERT INTO gradepoints(Grade, Points)
-- VALUES
-- ('EX', 10),
-- ('A', 9),
-- ('B', 8),
-- ('C', 7),
-- ('D', 6),
-- ('P', 5),
-- ('F', 0);
-- -- First, insert courses
-- INSERT INTO course (CourseCode, CourseName, Credits)
-- SELECT DISTINCT CourseCode, CourseName, Credits
-- FROM temp_student_data
-- ON CONFLICT (CourseCode) DO NOTHING;
-- -- Next, extract unique students
-- INSERT INTO students (RegNo, Dept)
-- SELECT DISTINCT RegNo, Dept
-- FROM temp_student_data
-- ON CONFLICT (RegNo) DO NOTHING;
-- -- Then insert registrations
-- INSERT INTO reg (RegID, RegNo, Ayear, Asem, PYS, CourseCode, Dept)
-- SELECT RegID, RegNo, Ayear, Asem, PYS, CourseCode, Dept
-- FROM temp_student_data
-- ON CONFLICT (RegNo, CourseCode) DO NOTHING;
-- -- Finally, insert grades
-- INSERT INTO marksgrade (RegNo, CourseCode, Grade)
-- SELECT RegNo, CourseCode, Grade
-- FROM temp_student_data
-- ON CONFLICT (RegNo, CourseCode) DO NOTHING;
-- select
-- r.regno,SUM(c.credits * gp.points) / SUM(c.credits) AS cgpa
-- from
-- reg r
-- join
-- course c ON r.coursecode = c.coursecode
-- join
-- marksgrade m ON r.regno = m.regno
-- join
-- gradepoints gp ON m.grade = gp.grade
-- group by r.regno
-- order by cgpa desc;
--
----------------------------------------------------------------------------------
-- do $$
-- declare rec record;
-- cur cursor
-- for select r.regno, sum(c.credits*gp.points)/sum(c.credits) as cgpa,
sum(c.credits) as credits from reg r join course c on r.coursecode=c.coursecode
join marksgrade m on r.regno=m.regno join gradepoints gp on m.grade=gp.grade group
by r.regno having sum(c.credits*gp.points)/sum(c.credits)>=7.5 and
sum(c.credits)>=80;
-- begin
-- open cur;
-- loop
-- fetch cur into rec;
-- exit when not found;
-- raise notice 'regno: %, cgpa: %, credits: %',rec.regno,rec.cgpa,rec.credits;
-- end loop;
-- close cur;
-- end $$;
-- do $$
-- declare rec record;
-- cur cursor
-- for select r.regno, sum(c.credits) as credits from reg r join course c
on r.coursecode=c.coursecode join marksgrade m on r.regno=m.regno join gradepoints
gp on m.grade=gp.grade group by r.regno having sum(c.credits)>=190;
-- begin
-- open cur;
-- loop
-- fetch cur into rec;
-- exit when not found;
-- raise notice '% ',rec.credits;
-- end loop;
-- close cur;
-- end $$;
-- -- do $$
-- -- declare rec record;
-- -- cur cursor for
-- -- query;
-- -- begin
-- -- open cur;
-- -- loop
-- -- fetch cur into rec;
-- -- exit when not found;
-- -- raise notice
-- -- end loop;
-- -- close cur;
-- -- end $$;
-- do $$
-- declare rec record;
-- cur cursor for
-- select r.regno, sum(c.credits*gp.points)/sum(c.credits) as cgpa,
sum(c.credits) as credits from reg r join course c on r.coursecode=c.coursecode
join marksgrade m on r.regno=m.regno join gradepoints gp on m.grade=gp.grade group
by r.regno having sum(c.credits*gp.points)/sum(c.credits)>=8.0 and
sum(c.credits)>=190 and count(*) filter (where m.grade='F')>0;
-- begin
-- open cur;
-- loop
-- fetch cur into rec;
-- exit when not found;
-- raise notice 'reg: % | cgpa: % | credits: % ',rec.regno,
rec.cgpa,rec.credits;
-- end loop;
-- close cur;
-- end $$;
-- --no such students were there
--
----------------------------------------------------------------------------------
-- do $$
-- declare rec record;
-- cur cursor for
-- select * from (
-- select r.dept,
-- r.regno,
-- sum(c.credits*gp.points)/sum(c.credits) as cgpa,
-- sum(c.credits) as credits, rank() over (partition by r.dept order by
sum(c.credits*gp.points)/sum(c.credits) desc) as rnk
-- from reg r
-- join
-- course c on r.coursecode=c.coursecode
-- join
-- marksgrade m on r.regno=m.regno
-- join
-- gradepoints gp on m.grade=gp.grade
-- group by
-- r.dept,r.regno
-- having
-- count(*) filter (where m.grade='F')=0
-- ) ranked where rnk<=5;
-- begin
-- open cur;
-- loop
-- fetch cur into rec;
-- exit when not found;
-- raise notice 'dept: %, regno: %, cgpa: %
',rec.dept,rec.regno,round(rec.cgpa,2);
-- end loop;
-- close cur;
-- end $$;
--
----------------------------------------------------------------------------------
-- create table std(
-- sid int primary key,
-- name varchar(100),
-- gpa decimal(3,2),
-- role varchar(20) check (role in ('Admin','Student'))
-- );
-- insert into std(sid,name,gpa,role) values (1,'Celia',9.00,'Student'),
-- (2,'Claude',null,'Admin'),
-- (3,'Mia',9.56,'Student'),
-- (4,'Edward',8.00,'Student');
-- create or replace view adm as
-- select sid,name,
-- case when role='Admin' then gpa
-- else null
-- end as gpa
-- from std;
-- update adm
-- set name='Celia'
-- where name='Celi';
-- select * from adm;
-- grant select on adm to admin;
-- create recursive view emph(empno,ename,mgr,level) as
-- select empno,ename,mgr,1 as level
-- from emp where mgr is null
-- union all
-- select e.empno,e.ename,e.mgr,h.level+1 from emp e join emph h on
e.mgr=h.empno;
-- select * from emph;
-- create index id on std(gpa) where gpa>3.5;
-- explain analyze select * from std where gpa>3.5;
-- drop index id;
-- explain analyze select * from std where gpa>3.5;
--
----------------------------------------------------------------------------------
--insert into dept(deptno,dname,loc) values (50,'hr','california');
-- insert into dept(deptno,dname,loc) values (50,'hr','california'),
(60,'web&network','san francisco');
-- INSERT INTO emp(empno, ename, job, hiredate, mgr, sal, comm, deptno) VALUES
-- (7769, 'sam', 'clerk', '1981-05-20', 7839, 2000, 0, NULL),
-- (7469, 'ram', 'analyst', '1982-06-10', 7698, 3000, 0, NULL),
-- (7596, 'rahul', 'clerk', '1981-11-13', 7639, 2500, 200, NULL),
-- (7367, 'rajesh', 'salesman', '1982-08-11', 7769, 3200, 500, NULL),
-- (7473, 'aman', 'analyst', '1982-07-07', 7839, 2700, 300, NULL),
-- (7639, 'vishal', 'salesman', '1981-12-08', 7473, 2000, 0, NULL);
-- select e.*,d.dname,d.loc from emp e left join dept d on e.deptno=d.deptno;
-- select e.* from emp e left join dept d on e.deptno=d.deptno where d.deptno is
null;
-- select count(*) from emp where deptno is null;
-- select * from emp where job='clerk' and sal>2000 and deptno is null;
-- select * from emp where deptno is null and comm=0;
-- select * from emp where job='salesman' and deptno is null and extract(year from
hiredate)=1981;
-- select * from emp where deptno is null and extract(year from hiredate)=1981;
-- select sum(sal) from emp where deptno is null;
-- select e.*,d.dname,d.loc from emp e right outer join dept d on
e.deptno=d.deptno;
-- select d.*,e.ename from dept d left outer join emp e on d.deptno=e.deptno where
e.empno is null;
-- select e.ename, e.empno from emp e left join dept d on e.deptno=d.deptno where
d.dname is null and d.loc is null;
-- select e.*,d.* from emp e full outer join dept d on e.deptno=d.deptno where
e.deptno is null or e.empno is null;
-- select count(*) from dept d left outer join emp e on d.deptno=e.deptno where
e.empno is null;
-- select d.deptno,count(e.empno) from dept d left join emp e on d.deptno=e.deptno
group by d.deptno;
-- select e.*,d.dname,d.loc from emp e full outer join dept d on e.deptno=d.deptno
where (e.job='clerk' and e.deptno is null) or e.empno is null;
-- select e.*,d.dname,d.loc from emp e full outer join dept d on e.deptno=d.deptno
where (e.job='salesman' and e.deptno is null) or e.empno is null;
-- select * from emp where deptno is null and job='analyst' and sal<3000;
-----------------------------------------
-- DROP TRIGGER IF EXISTS upst ON emp;
-- DROP FUNCTION IF EXISTS ups();
-- create or replace function ups()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if new.sal<old.sal then
-- raise exception 'nope %',new.sal;
-- end if;
-- return new;
-- end;
-- $$;
-- create trigger upst
-- before update on emp
-- for each row
-- execute procedure ups();
-- update emp
-- set sal=20
-- where empno=7369;
-- --drop trigger if exists trigger_name on table;
-- --drop function if exist function_name();
-- alter table emp add column age int;
-- drop function if exists addage();
-- create or replace function addage()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if (new.age<21 OR new.age>32) then
-- raise exception 'You are not Eligible';
-- end if;
-- return new;
-- end;
-- $$;
-- drop trigger if exists addaget on emp;
-- create trigger addaget
-- before update on emp
-- for each row
-- execute function addage();
-- update emp
-- set age=20
-- where empno=7369;
-- drop function if exists del();
-- create or replace function del()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if old.age<>56 then
-- raise exception 'Not allowed!';
-- end if;
-- raise notice 'He is retired!';
-- return old;
-- end;
-- $$;
-- drop trigger if exists delt on emp;
-- create trigger delt
-- before delete on emp
-- for each row
-- execute function del();
-- delete from emp where age=56;
-- drop function if exists ct();
-- create or replace function ct()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if (select count(*) from emp)>15 then
-- raise exception '‘There are Enough Employees’.';
-- end if;
-- return new;
-- end;
-- $$;
-- drop trigger if exists ctt on emp;
-- create trigger ctt
-- before insert on emp
-- for each row
-- execute procedure ct();
-- insert into emp(empno) values (7878);
-- drop function if exits deldept();
-- create or replace function deldept()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- raise exception 'error';
-- return old;
-- end;
-- $$;
-- DROP TRIGGER IF EXISTS deldeptt ON dept;
-- create trigger deldeptt
-- before delete on dept
-- for each row
-- execute procedure deldept();
-- delete from dept where dname='hr';
-- drop function if exists dn();
-- create or replace function dn()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if new.dname=any(select dname from dept) then
-- raise exception 'exists';
-- end if;
-- raise notice 'created';
-- return new;
-- end;
-- $$;
-- drop trigger if exists dnt on dept;
-- create trigger dnt
-- before insert on dept
-- for each row
-- execute procedure dn();
-- insert into dept(dname) values ('accounting');
-- drop function is exists ctd();
-- create or replace function ctd()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if (select count(*) from dept)>7 then
-- raise exception 'Creating New Dept not Allowed.';
-- end if;
-- return new;
-- end;
-- $$;
-- drop trigger if exists ctdt on dept;
-- create trigger ctdt
-- before insert on dept
-- for each row
-- execute procedure ctd();
-- insert into dept(deptno) values (79);
-----------------------------------------------------------------------------------
---
-- create table Accounts(
-- AccountID serial primary key,
-- HolderName varchar(100),
-- Balance decimal(10,2) check (Balance is not null)
-- );
-- create table Transactions(
-- TransactionID serial primary key,
-- AccountID int references Accounts(AccountID),
-- Amount decimal(10,2) check (Amount is not null),
-- Type varchar(10) check (Type in ('Deposit','Withdraw')) not null
-- );
-- INSERT INTO Accounts (HolderName, Balance) VALUES
-- ('John Doe', 1000.00),
-- ('Jane Smith', 5000.50),
-- ('Alice Johnson', 1500.75),
-- ('Bob Brown', 2200.30),
-- ('Charlie Davis', 3200.90);
-- INSERT INTO Transactions (AccountID, Amount, Type) VALUES
-- (1, 500.00, 'Deposit'),
-- (2, 1000.00, 'Withdraw'),
-- (3, 200.00, 'Deposit'),
-- (4, 500.00, 'Withdraw'),
-- (5, 700.00, 'Deposit'),
-- (1, 200.00, 'Withdraw'),
-- (2, 300.00, 'Deposit'),
-- (3, 100.00, 'Withdraw');
-- drop function if exists ovd();
-- create or replace function ovd()
-- returns trigger
-- language plpgsql
-- as $$
-- begin
-- if new.Type='Withdraw' then
-- if new.Amount>(select Balance from Accounts where
new.AccountID=AccountID) then
-- raise exception 'insuff';
-- end if;
-- end if;
-- return new;
-- end;
-- $$;
-- drop trigger if exists ovdt on Transactions;
-- create trigger ovdt
-- before insert on Transactions
-- for each row
-- execute procedure ovd();
-- insert into Transactions(AccountID,Amount,Type) values (1,400000.00,'Withdraw');
-- A callable function (NOT a trigger)
-- drop function if exists pt();
-- create or replace function pt()
-- returns void
-- language plpgsql
-- as $$
-- declare
-- cur cursor for
-- select TransactionID, AccountID, Amount, Type from Transactions;
-- v_tid int;
-- v_aid int;
-- v_amt numeric;
-- v_typ varchar;
-- begin
-- open cur;
-- loop
-- fetch cur into v_tid, v_aid, v_amt, v_typ;
-- exit when not found;
-- if v_typ = 'Deposit' then
-- update Accounts
-- set Balance = Balance + v_amt
-- where AccountID = v_aid;
-- raise notice 'Deposited % to Account %', v_amt, v_aid;
-- elsif v_typ = 'Withdraw' then
-- update Accounts
-- set Balance = Balance - v_amt
-- where AccountID = v_aid;
-- raise notice 'Withdrew % from Account %', v_amt, v_aid;
-- end if;
-- end loop;
-- close cur;
-- end;
-- $$;
-- insert into Transactions(AccountID, Amount, Type)
-- values (1, 500, 'Deposit');
-- select pt();
-----------------------------------------------------------------------------------
---
create table BankAccounts(
AccountID serial primary key,
Name varchar(100) not null,
Balance decimal(10,2) check (Balance>=0) not null
);
insert into BankAccounts(Name,Balance) values ('Alex', 1000.00),
('Bob', 5000.50),
('Charlie', 1500.75),
('David', 2200.30),
('Eve', 3200.90);
begin;
savepoint sp1;
update BankAccounts
set Balance=Balance+100
where Name='Alex'
savepoint sp2;
update BankAccounts
set Balance=Balance-300
where Name='Bob';
savepoint sp3;
insert into BankAccounts(Name,Balance) values ('Frank', 2000.00);
rollback to sp2;
rollback to sp3; --error
commit;
begin;
savepoint sp4;
insert into BankAccounts(Name,Balance) values ('Grace', 2500.00);
release savepoint sp4;
rollback to sp4; --error
commit;
create table Users(
UserID serial primary key,
Name varchar(100) not null,
Role varchar(20) check (Role in ('Admin','Manager','Employee')) not null
);
insert into Users(
Name, Role) values ('Alice', 'Admin'),
('Bob', 'Manager'),
('Charlie', 'Employee'),
('David', 'Admin'),
('Eve', 'Manager');
create user yaya123 with password 'yaya';
create user sur455 with password 'sur';
create user shah111 with password 'shah';
create role Admin;
create role Manager;
create role Employee;
grant select,insert,update,delete on Users to Admin;
grant select,update on Users to Manager;
grant select on Users to Employee;
grant Admin to yaya123;
grant Manager to sur455;
grant Employee to shah111;
create or replace view mgr as select case when Role='Admin' then Name else null end
from Users;
grant select on mgr to Admin;
select * from mgr;
revoke select on Users from Employee;
grant select on Users to shah111 with grant option;