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

SQL Notes

This document discusses SQL and database concepts. It covers: 1. SQL commands for defining and managing databases including DDL commands like CREATE, ALTER, and DROP for creating, modifying and deleting tables along with examples. 2. Data types in SQL for different kinds of data like numeric, character, date/time etc. 3. DDL (Data Definition Language) including using CREATE TABLE to define table structure, adding constraints like PRIMARY KEY, UNIQUE, NOT NULL, and examples of creating tables. 4. ALTER TABLE to modify existing tables by adding/dropping columns and constraints.

Uploaded by

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

SQL Notes

This document discusses SQL and database concepts. It covers: 1. SQL commands for defining and managing databases including DDL commands like CREATE, ALTER, and DROP for creating, modifying and deleting tables along with examples. 2. Data types in SQL for different kinds of data like numeric, character, date/time etc. 3. DDL (Data Definition Language) including using CREATE TABLE to define table structure, adding constraints like PRIMARY KEY, UNIQUE, NOT NULL, and examples of creating tables. 4. ALTER TABLE to modify existing tables by adding/dropping columns and constraints.

Uploaded by

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

Chapter 5

SQL
5.1. Introduction to query languages
5.2. DDL commands (create, drop, alter) with examples
5.3. Basic structure of SQL query
5.4. Set operations
5.5. Aggregate Operators and functions
5.6. Null values
5.7. Nested Sub queries
5.8 Modifications to Database (insert, delete, update)
5.9 SQL mechanisms for joining relations (inner joins, outer joins and their types)
5.10. Examples on SQL (case studies)

Data types in SQL


Data type specifies what kind you want to store in table field. When we create table, we specify
each attribute as column of table. For each column we use data type.
1. Numeric data types:
a) smallint – 2 bytes – small range integer
b) integer, int – 4 bytes – integer data
c) bigint – large range 8 bytes, stores whole numbers
d) real – 4 byte, floating point numbers
e) double – 8 bytes, floating point numbers
a. float(n) - floating point numbers with precision n.
b. numeric(p,d) – A fixed point number with user specified precision, where p
means total number of digits and d means digits after decimal point
3. Character data types:
a. character(n), char(n) – Fixed n length character string
b. e.g char(10) – for 10 characters memory is allocated.
c. If “ICICI” value is stored then memory for rest 5 characters will be wasted.
d. varchar(n) – A variable length character string with n limit.
Eg. varchar(10) – If value is “ICICI” then memory for storing value is allocated. It will
be allocated dynamically after storing the value. So there is no wastage of memory.
c) text – A variable length character string of unlimited length
2. Monetary data type:
a) money – 8 bytes currency amount
b) Boolean data type:
3. boolean – 1 byte It specifies the state of true or false
4. Date/Time data type:
date: 4 bytes to store date yyyy/mm/dd
time: 8 bytes to store time hh:mm:sec

3.3 DDL (Data Definition Language)

DDL – DDL commands are used to design database.


Following are the types of DDL Commands:
1. Create table – It is use to create new table in database.
2. Alter table – It is used to modify existing table from database.
3. Drop table – It is used to delete table completely from database.

1. Create table – This command is used to create table in database.


Syntax:
CREATE TABLE <TABLE_NAME>
(
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
………
);
Eg. Emp(eid, ename)
Create table Emp (eid int, ename varchar(50));
Commands for executing in PostgreSQL –
1. \d - To See list of tables created under current user.
2. \d tablename – To see details particular table as attribute or column names and its
datatypes.
e.g \d emp
Different ways of creating table:
1. Create table emp(eno int, ename varchar(50));
2. Creating table with primary key.
Create table emp1(eno int primary key, ename varchar(50));
\d emp1 – Details of emp table
Table "public.emp1"
Column | Type | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
eno | integer | | not null |
ename | character varying(50) | | |
Indexes:
"emp1_pkey" PRIMARY KEY, btree (eno)
Above table is created with Primary key constraint where eno is PK and constraint name for
PK is emp1_pkey
• Creating table with primary key in another way.
create table emp2(eno int, ename varchar(50), constraint pk_emp primary key(eno));

\d emp2
Table "public.emp2"
Column | Type | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
eno | integer | | not null |
ename | character varying(50) | | |
Indexes:
"pk_emp" PRIMARY KEY, btree (eno)
pk_emp – We have specified the constraint name

OR
create table emp2(eno int, ename varchar(50), primary key(eno));
• Examples from Assignment 5
• Create table emp (eno integer primary key, ename varchar(50) , salary float);
• Create table books( id integer UNIQUE, title text NOT NULL, author_id
integer,sub_id integer);
• Create table books1( id integer, title text NOT NULL, author_id integer,sub_id
integer,CONSTRAINT books_id_pkey PRIMARY KEY(id));
• Create table sales_order(order_no char(10) PRIMARY KEY, order_date date,
salesman_no integer);
• Create table client_master (client_no integer CONSTRAINT p_client PRIMARY
KEY, name varchar(50), addr text, bal_due integer);
• Create table inventory(inv_no integer PRIMARY KEY, in_stock Boolean);
Primary Key Unique NOT NULL
Duplicate Not allowed Not Allowed Allowed
Value
NULL value Not allowed Allowed Not allowed

Assignment 5 SET A
 create table player(player_id int primary key,name varchar(50), birth_date date, birth_place
varchar(100));
To check table details
\d player
Constraints types:
1. Column level constraint: If the constraint is specified only for particular column and if it
written just after columnname and datatype then it is called as column level constraint.
e.g: Create table emp1(eno int primary key, ename varchar(50));
2. Table level constraint: If constraints is specified at the end of table ie after writing all
columns with data types then it is called as table level constraints.
e.g. create table emp2(eno int, ename varchar(50), constraint pk_emp primary key(eno));
 create table student(roll_no int, class varchar(20), weight numeric(6,2), height numeric(6,2),
primary key(roll_no, class));
postgres=# \d student
Table "public.student"
Column | Type | Collation | Nullable | Default
---------+-----------------------+-----------+----------+---------
roll_no | integer | | not null |
class | character varying(20) | | not null |
weight | numeric(6,2) | | |
height | numeric(6,2) | | |
Indexes:
"student_pkey" PRIMARY KEY, btree (roll_no, class)

 Check constraint –
1. Create table as student with no, name, age. Apply constraint for age column as age should
be between 18 to 40.
 Create table student(sno int, name varchar(30), age int, check (age between 18 and 40));
In above query table level constraint is applied.
postgres=# \d student1
Table "public.student1"
Column | Type | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
sno | integer | | |
name | character varying(30) | | |
age | integer | | |
Check constraints:
"student1_age_check" CHECK (age >= 18 AND age <= 40)
OR
Create table student(sno int, name varchar(30), age int check (age between 18 and 40));
In above query column level constraint is applied.
2. Create table for item with (itemno(PK), itemname, qty, price). Add constraint for qty as
Quantity should be greater than 5.
 create table item(itemno int primary key, itemname varchar(50), qty int, price float, check
(qty > 5));
OR
 create table item1(itemno int primary key, itemname varchar(50), qty int check (qty > 5),
price float);
3. Create table as Emp with (eno, ename). Apply constraint for ename as ename should starts
with R.
 create table emp1(eno int, ename varchar(30), check (ename like ‘R%’));
OR
 create table emp2(eno int, ename varchar(30) check (ename like 'R%'));
4. Create table as Customer(cno, cname, mobno). Apply constraint for cname as customer
name should be in upper case.
 create table customer(cno int, cname varchar(30), mobno int, check
(cname=upper(cname)));
OR
 create table customer1(cno int, cname varchar(30) check (cname=upper(cname)), mobno
int);
5. Create table supplier as(sno(pk), sname, age, mobno). Apply following constraints:
1. sname should starts with P
2. age should not be null and it should be greater than 25
3. mobno should be unique.
 create table supplier(sno int primary key, sname varchar(30) check (sname like 'P%'), age
int not null check(age>25), mobno int unique);
6. Create table staff(id(pk), name, position, age). Apply constraint for position as position
value should be either – Asst Prof, Asso Prof, Prof
 create table staff(id int primary key, name varchar(30), position varchar(15), age int,
check(position in('Ass Prof', 'Asso Prof', 'Prof')));

Assignment 6 Set A 1
 postgres=# create table machine(machine_id int primary key, machine_name varchar(50)
not null check(machine_name=upper(machine_name)), machine_type varchar(10)
check(machine_type in('drilling', 'milling', 'lathe', 'turing', 'grinding')), machine_price
float check(machine_price > 0), machine_cost float, check
(machine_cost<machine_price));
Assignment 6 Set A 2
7. create table employee(employee_id int primary key, employee_name varchar(50) NOT
NULL check(employee_name=upper(employee_name)), employee_desg varchar(10)
check(employee_desg in('Manager', 'Staff', 'Worker')), employee_sal float
check(employee_sal>0), employee_uid int, check (employee_id<>employee_uid));
2. Alter table – It is used to modify existing table. We can add new column, drop column,
rename column, add constraints like, NOT NULL, Check, Primary key or can drop
constraint in existing table.
 To add new column to existing table.
Syntax:
Alter table tablename add column new_columname datatype;
e.g Add mobno column in emp table
alter table emp add column mobileno int;
alter table emp add column salary numeric(8,2);
 To delete column from existing table
Syntax:
Alter table tablename drop column columnname;
-> Alter table emp drop column salary;
 Rename existing column name
Syntax:
Alter table tablename rename column existing_columnname to new_columnname;
e.g.
Alter table emp rename column addr to address;
 Add or remove NOT NULL constraint
Syntax:
Alter table tablename alter column columnname set NOT NULL | DROP NOT NULL;
e.g.
alter table emp alter column mobileno set NOT NULL;
 Add check constraint
Syntax:
Alter table tablename add check expression;
alter table emp add check (ename like 'R%'); //ename starting with R
alter table emp add check (address in('Pune', 'Mumbai', 'Nasik'));
 Drop or delete constraint
Syntax:
Alter table tablename drop constraint constraintname;
Before dropping constraint:
postgres=# \d emp
Table "public.emp"
Column | Type | Collation | Nullable | Default
----------+-----------------------+-----------+----------+---------
eno | integer | | not null |
ename | character varying(30) | | |
address | text | | |
dno | integer | | |
mobileno | integer | | not null |
Indexes:
"emp_pkey" PRIMARY KEY, btree (eno)
Check constraints:
"emp_address_check" CHECK (address = ANY (ARRAY['Pune'::text, 'Mumbai'::text,
'Nasik'::text]))
"emp_ename_check" CHECK (ename::text ~~ 'R%'::text)
Foreign-key constraints:
"emp_dno_fkey" FOREIGN KEY (dno) REFERENCES dept(dno) ON UPDATE
CASCADE ON DELETE CASCADE
Lets remove constraint for ename
alter table emp drop constraint emp_ename_check;
Where emp_ename_check is name of constraint. We can check name of constraint using \d
tablename
After dropping constraint:
postgres=# \d emp
Table "public.emp"
Column | Type | Collation | Nullable | Default
----------+-----------------------+-----------+----------+---------
eno | integer | | not null |
ename | character varying(30) | | |
address | text | | |
dno | integer | | |
mobileno | integer | | not null |
Indexes:
"emp_pkey" PRIMARY KEY, btree (eno)
Check constraints:
"emp_address_check" CHECK (address = ANY (ARRAY['Pune'::text, 'Mumbai'::text,
'Nasik'::text]))
Foreign-key constraints:
"emp_dno_fkey" FOREIGN KEY (dno) REFERENCES dept(dno) ON UPDATE
CASCADE ON DELETE CASCADE
 Add primary key constraint
Syntax:
Alter table tablename add primary key(columnname);
e.g.
alter table cust add primary key(cno);
3. To delete or remove table
Systax:
Drop table tablename;
Eg.
Drop table cust;

 Assignment 7
 SET B
 Alter table employee add column desg varchar(20) check (desg in(‘Manager’, ‘Ass.
Manager’, ‘Software engineer’));
 a) Alter table student add column address text NOT NULL;
 b) Alter table student add column phone integer;

Create table for relationship


 One to many or Many to One
Dept -> Emp Emp ->Dept
1–M M-1
Dept(dno, dname)
Emp(eno, ename, addr, dno(FK))
create table Dept(dno int primary key, dname varchar(20));
create table emp(eno int primary key, ename varchar(30), addr text, dno int references
Dept(dno) on delete cascade on update cascade);
OR

create table emp(eno int primary key, ename varchar(30), addr text, dno int, foreign key(dno)
references Dept(dno) on delete cascade on update cascade);

postgres=# \d dept
Table "public.dept"
Column | Type | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
dno | integer | | not null |
dname | character varying(20) | | |
Indexes:
"dept_pkey" PRIMARY KEY, btree (dno)
Referenced by:
TABLE "emp" CONSTRAINT "emp_dno_fkey" FOREIGN KEY (dno) REFERENCES
dept(dno) ON UPDATE CASCADE ON DELETE CASCADE

postgres=# \d emp
Table "public.emp"
Column | Type | Collation | Nullable | Default
--------+-----------------------+-----------+----------+---------
eno | integer | | not null |
ename | character varying(30) | | |
addr | text | | |
dno | integer | | |
Indexes:
"emp_pkey" PRIMARY KEY, btree (eno)
Foreign-key constraints:
"emp_dno_fkey" FOREIGN KEY (dno) REFERENCES dept(dno) ON UPDATE
CASCADE ON DELETE CASCADE

 Many to Many relationship


Student - > Subject
M -> M
Student (sno, sname)
Subject (subno, subname)
create table Stud(sno int primary key, sname varchar(30));
create table Sub(subno int primary key, subname varchar(40));
create table Stud_Sub(sno int references Stud(sno) on delete cascade on update cascade,
subno int references Sub(subno) on delete cascade on update cascade, primary key(sno,
subno));

 One to one
Room(rno, rtype)
Person(pid, pname, rno(FK)
create table Room(rno int primary key, rtype varchar(20));
create table Person(pid int primary key, pname varchar(30), rno int references Room(rno) on
delete cascade on update cascade);
 Create table for descriptive attribute
Supplier (sno, sname)
Part (pno, pname)
Sup_Part (sno, pno, quantity)
create table supp(sno int primary key, sname varchar(30));
create table part(pno int primary key, pname varchar(30));
create table sup_part(sno int references supp(sno) on delete cascade on update cascade, pno
int references part(pno) on delete cascade on update cascade, quantity int, primary key(sno,
pno));
3.4 DML Commands:

 We can manage data by inserting, deleting or updating.


 DML commands are – insert, select, update, delete

1. Insert command: This command is to add new values in table.


Syntax:
insert into tablename [(columnname1, columnname2,……, columnname n)]
values (columnname1, columnname2,……, columnname n);
Char = 1byte = 8bits 28 = 256/2 = 128 = (-127 to 0 and 1 to 128)
Smallint = 2byte = 16 bits 216 = 65535 = -32767 to 0 and 1 to 32768

e.g:
insert into dept values(10, 'Accounts');
insert into dept values(20, 'Sales');
insert into dept values(30, 'Purchase');

e.g:
insert into emp values(101, 'Amit', 'Pune', 10, 9850304043);
postgres=# insert into emp values(101, 'Raj', 'Mumbai', 10, 9850349043);
ERROR: duplicate key value violates unique constraint "emp_pkey"
DETAIL: Key (eno)=(101) already exists.
postgres=# insert into emp values(102, 'Ajit', 'Nagpur', 10, 9850349043);
ERROR: new row for relation "emp" violates check constraint "emp_address_check"
DETAIL: Failing row contains (102, Ajit, Nagpur, 10, 9850349043).
postgres=# insert into emp values(102, 'Ajit', 'Pune', 60, 9850349043);
ERROR: insert or update on table "emp" violates foreign key constraint
"emp_dno_fkey"
DETAIL: Key (dno)=(60) is not present in table "dept".

• Insert two more employee details:


postgres=# insert into emp values(102, 'Ajit', 'Pune', 10, 9860235412);
INSERT 0 1
postgres=# insert into emp values(103, 'Riya', 'Mumbai', 20, 9890287625);
INSERT 0 1
postgres=# select * from emp;
eno | ename | address | dno | mobileno
-----+-------+---------+-----+------------
101 | Amit | Pune | 10 | 9850304043
102 | Ajit | Pune | 10 | 9860235412
103 | Riya | Mumbai | 20 | 9890287625
(3 rows)
• Insert employee details without mobileno
postgres=# insert into emp values(104, 'Arpita', 'Nasik', 30);
INSERT 0 1
• Insert employee details without address
postgres=# insert into emp(eno, ename, dno, mobileno) values(105, 'Kiran', 20,
8661244103);
INSERT 0 1
• Insert employee details without address, mobileno
postgres=# insert into emp(eno, ename, dno) values(106, 'Neha', 30);
INSERT 0 1

3 ways for inserting value in table:


Emp(eno, ename, address, dno, mobileno, salary, birthdate)
1. If all values are known.
insert into emp values(110,'Kavya','Pune', 20, 7888790560, 60000, '1988-02-13');
2. If address and mobileno not known.
insert into emp values(111,'Suresh',NULL, 10, NULL, 650000, '1989-02-18');
3. insert into emp(eno,ename,dno,salary,birthdate) values(112,'Ajay',30, 60000, '1986-02-
13');
• Insert values in Machine table
postgres=# \d machine
Table "public.machine"
Column | Type | Collation | Nullable | Default
---------------+-----------------------+-----------+----------+---------
machine_id | integer | | not null |
machine_name | character varying(50) | | not null |
machine_type | character varying(10) | | |
machine_price | double precision | | |
machine_cost | double precision | | |
Indexes:
"machine_pkey" PRIMARY KEY, btree (machine_id)
Check constraints:
"machine_check" CHECK (machine_cost < machine_price)
"machine_machine_name_check" CHECK (machine_name::text =
upper(machine_name::text))
"machine_machine_price_check" CHECK (machine_price > 0::double precision)
"machine_machine_type_check" CHECK (machine_type::text = ANY
(ARRAY['drilling'::character varying, 'milling'::character varying, 'lathe'::character varying,
'turing'::character varying, 'grinding'::character varying]::text[]))

• Insert values in Machine table


postgres=# insert into machine values(1012,'DRILL','drilling',1000,90);
INSERT 0 1
• Insert values in Machine table without machine_type, machine_price
postgres=# insert into machine(machine_id, machine_name, machine_cost)
values(1013,'MIXER',2000);
INSERT 0 1
postgres=# select * from machine;
machine_id | machine_name | machine_type | machine_price | machine_cost
------------+--------------+--------------+---------------+--------------
1012 | DRILL | drilling | 1000 | 90
1013 | MIXER | | | 2000
(2 rows)

• Update command – It allows to update a value in a row or set of rows of tables.


Syntax:
update tablename
set columnname = expression [, columname = expression, ….]
[where condition];
e.g.
1. Update the address of Arpita to ‘Mumbai’
postgres=# update emp set address='Mumbai' where eno=104;
UPDATE 1
This means one row is updated
2. Update the dno, mobileno of Riya to 10 and 7785523147 respectively.
postgres=# update emp set dno=10, mobileno=7785523147 where eno=103;
UPDATE 1
• Update address of all employees as ‘Pune’
postgres=# update emp set address='Pune';
UPDATE 6
This will all 6 rows with address as ‘Pune’
• Update dno of all employees as 10 or Move all employees into dno 30.
postgres=# update emp set dno=30;
UPDATE 6
• Transfer the employees of department no 20 to ‘Nasik’.
Update emp set address=‘Nasik’ where dno=20;

• Delete command: This command is used to delete a row/s or record/s from the table.
Syntax:
delete from tablename
[where condition];
• Delete employee 104
postgres=# delete from emp where eno=104;
DELETE 1
postgres=# select * from emp;
eno | ename | address | dno | mobileno
-----+-------+---------+-----+------------
101 | Amit | Pune | 30 | 9850304043
102 | Ajit | Pune | 30 | 9860235412
103 | Riya | Pune | 30 | 7785523147
105 | Kiran | Mumbai | 30 | 8661244103
106 | Neha | Mumbai | 30 |
(5 rows)
• Delete employee staying in ‘Mumbai’
postgres=# delete from emp where address='Mumbai';
DELETE 2
• Delete all employee from table
postgres=# delete from emp;
DELETE 3
• Select command:
This command is used to display data from database as per user requirement.
Syntax:
select columnname 1, columnname 2,………, columnname n
from tablename1, tablename2, ………, tablename n
[where condition]
[order by columnname 1, columnname 2,………, columnname n]
[group by columname]
[having condiotion];
Examples:
Consider Emp table as Emp(eno(PK), ename, address, dno, mobilno, salary, birthdate)
1. Display details of all departments.
-> select * from dept;
2. Display details of employees.
->select * from emp;
3. Display only information of eno and ename.
->select eno,ename from emp;
4. Display only information of ename with mobileno.
->select ename, mobileno from emp;
5. Display dno with ename.
->select dno, ename from emp;
6. Display information of employees from dept 10.
->select * from emp where dno=10;
7. Display ename and mobileno from department no 10.
->select ename, mobileno from emp where dno=10;
8. Display information of employees having address as ‘Pune’.
->select * from emp where address='Pune';
9. Display employee ename with dno having address as ‘Pune’.
->select ename, dno from emp where address='Pune';
10. Display list of addresses from emp table.
->select address from emp;
11. Display list of addresses without repetition from emp table.
->select distinct address from emp;
Logical operators and comparison operators in SQL:
and , or, not logical operators can be used in SQL Query.
<,<=,>,>=,=,!= comparison operators can be used in SQL Query.
1. Display list of employees either from Pune or Mumbai.
->select * from emp where address='Pune' or address='Mumbai';
2. Display list of employees whose salary >40000.
->select * from emp where salary>40000;
3. Display list of employees from Pune whose salary >40000.
->select * from emp where address='Pune' and salary>40000;
4. Display list of employees either from Pune or whose salary >40000.
->select * from emp where address='Pune' or salary>40000;
5. Display names of employees from dno 20 whose salary <40000.
-> select ename from emp where dno=20 and salary<40000;
6. Display eno, ename of employees whose salary is less than or equal to 40000.
->select eno,ename from emp where salary<=40000;
7. Display eno, ename of employees whose salary is 40000.
->select eno,ename from emp where salary=40000;
8. Display eno, ename of employees whose salary is not 40000.
-> select eno,ename from emp where salary!=40000;
9. Display list of employee whose salary is between 30000 and 60000.
-> select * from emp where salary>30000 and salary<60000;
Assignment no 8:
SET B
1.
Property(pno ,description,area)
Owner(oname, address,phone)
An owner can have one or more properties, but a property belongs to exactly one owner. Create
the relations accordingly, so that the relationship is handled properly and the relations are in
normalized form (3NF).

Property - Owner OR Owner - Property


M–1 1- M
->Since there is one to many relationship between Owner to Property. So take primary key of
one ie Owner in many many ie Property.
create table owner(oname varchar(30) primary key, address text, phone bigint);
create table property(pno int primary key, description text, area varchar(50), oname varchar(30)
references owner(oname) on delete cascade on update cascade);
insert into owner values('Mr. Nene', 'Pune', 8879012376);
insert into owner values('Mr. Joshi', 'Pune', 9739012276);
insert into owner values('Mr. Kale', 'Mumbai', 9890162276);
insert into property values(1001, '2BHK', 'Pune', 'Mr. Nene');
insert into property values(1002, '3BHK', 'Mumbai', 'Mr. Nene');
insert into property values(1003, '2BHK', 'Mumbai', 'Mr. Joshi');
insert into property values(1004, '2BHK', 'Pune', 'Mr. Joshi');
insert into property values(1005, '1000sq.ft', 'Pune', 'Mr. Joshi');
insert into property values(1006, '3000sq.ft', 'Satara', 'Mr. Kale');
insert into property values(1007, '3BHK', 'Satara', 'Mr. Kale');
Update owner set phone=9890278008 where oname='Mr. Nene';
delete from property where area='Pune' and oname='Mr. Joshi';

Set B 2:
3. increase salary of “managers” by 15%;
-> Update emp Set sal=sal+(sal*0.15) where designation=‘Manager’;
4. delete all employees of deparment 30;
-> delete from emp where dno=30;
5. delete all employees who are working as a “clerk”
->delete from emp where designation=‘Clerk’;
6. change location of department 20 to ‘KOLKATA’.
->update dept set dloc=‘KOLKATA’ where dno=20;
Set B3:
Client -> Sales_Order
1->M
Note: Take client_no as varchar(10)
3. change order date of client_no ’C004’ to 12/4/08
->update sales_order set s_order_date=‘2008-04-12’ where client_no=‘C004’;
4. delete all sale records having order date before 10th feb. 08
Delete from sales_order where s_order_date<‘2008-02-10’;
5. delete the record of client “joshi”
->delete from client where name=‘joshi’;
String operation:
The most commonly used string operation on string is pattern matching. For this like operator is
used.
% and _ characters are used to match characters of column using like operator.
% is used for zero or more than one character matching.
_ is used to match exactly one character.
1. Display the list of employees whose name starts with ‘A’;
->select * from emp where ename like 'A%' ;
2. Display the list of employees whose name starts with ‘A’ or ‘a’;
->select * from emp where ename like 'A%' or ename like 'a%';
3. Display the list of employees whose name ends with ‘A’ or ‘a’;
->select * from emp where ename like '%A' or ename like '%a';
4. Display the list of employees containing ‘t’ in their name.
-> select * from emp where ename like '%T%' or ename like '%t%';
5. Display the list of employees whose name contains ‘m’ as a second character.
->select * from emp where ename like '_m%';
6. Display name, deptno whose name is of 4 characters.
->select ename,dno from emp where ename like '____'; (4 underscore characters)
7. Display name, deptno whose name contains ‘I’ or ‘i’ as a second last character.
->select ename,dno from emp where ename like '%i_' or ename like '%I_';
order by clause/command:
select columnname 1, columnname 2,………, columnname n
from tablename1, tablename2, ………, tablename n
[where condition]
[order by columnname {asc/desc}];
Order by is used to display data in sorted manner either in ascending or descending manner. By
default data is displayed in ascending order.
1. Display list of employees sorted by names.
->select * from emp order by ename;
OR
select * from emp order by ename asc;
2. Display list of employees sorted on salary column in descending order.
OR Display list of employees from highest to lowest salary.
-> select * from emp order by salary desc;
3. Display list of employees from highest to lowest salary department wise.
-> select * from emp order by dno, salary desc; (2 level sorting)
4. Display list of employees from lowest to highest address wise.
-> select * from emp order by address,salary;
5. Display list of employees from Pune with salary from highest to lowest.
-> select * from emp where address='Pune' order by salary desc;
6. Display name, address of employees with address in ascending order.
-> select ename,address from emp order by address;
7. Display name, dno of employees from dno=10 with name in descending order.
-> select ename,dno from emp where dno=10 order by ename desc;

Aggregate functions:
There are 5 aggregate functions is SQL.
1. sum
2. avg
3. min
4. max
5. count
1. Display sum of salary of all employees.
-> select sum(salary) from emp;
2. Display average of salaries of all employees.
-> select avg(salary) from emp;
3. Display salary which is maximum.
-> select max(salary) from emp;
4. Display salary which is minimum.
-> select min(salary) from emp;
5. Display total number of employees.
-> select count(eno) from emp;
Group by clause:-
select columnname 1, columnname 2,………, columnname n
from tablename1, tablename2, ………, tablename n
[where condition]
[order by columnname {asc/desc}];
[group by columname];
For aggregate functions group by clause is used to group the data.
NOTE: Whenever aggregate function is used with any other column then use group by clause
with that other column.
1. Display department-wise number of employees.
OR Display number of employees in each department.
-> select dno,count(eno) from emp group by dno;
2. Display department-wise sum of salaries. OR Display total salary for each department.
-> select dno, sum(salary) from emp group by dno;
3. Display department-wise max salary. OR Display max salary for each department.
-> select dno, max(salary) from emp group by dno;
4. Display department-wise min salary. OR Display min salary for each department.
-> select dno, min(salary) from emp group by dno;
5. Display department-wise average salary. OR Display average salary for each department.
-> select dno, avg(salary) from emp group by dno;
6. Display sum of salary for dno=20;
-> select sum(salary) from emp where dno=20;
7. Display dno and sum of salary for dno=20;
-> select dno,sum(salary) from emp where dno=20 group by dno;
Assignment 9:
SET A
1. Select * from emp;
-> Displays all columns from emp table.
2. Select empno, name from emp;
-> Displays empno and name from emp table;
3. Select distinct deptno from emp;
-> Displays deptno without repetition.
4. . Select * from emp where deptno = 10;
-> Displays records of employees from dept no = 10.
5. Select * from emp where address = ‘Pune’ and sal> 30000 ;
-> Displays records of employees from Pune and salary > 30000.
6. Select * from emp where address = ‘Pune’ and salary between 55000 and 65000;
-> Displays list of employees from Pune with salary range is from 55000 to 65000.
7. Select * from emp where name like ‘___%’; (3 underscrore)
-> Displays records of employees whose name contains atleast 3 chatacters.
8. Select * from emp where name like ‘%mi%’;
-> Displays records of employees having mi anywhere in their name.
9. Select * from emp where salary is null;
-> Displays the list of employees having no salary.
10. Select * from emp order by eno;
-> Display records of employees with eno in ascending order.
11. Select * from emp order by deptno,eno desc; (2 Level sorting)
-> Display records of employees with deptno in ascending order and eno in descending order.
12. Select deptno as department, sum(salary) as total from emp group by deptno order by deptno;
-> It will display department-wise sum of salary of employees where deptno will be displayed in
ascending order.
NOTE: In above query ‘as’ keyword is used to give new heading to the column. Here instead of
deptno, it will display department as heading.
13. Select deptno as department , count(eno) as total_emp from emp group by deptno having
count(eno ) >3 order by deptno;
-> Displays department-wise count of employees, if count of employees in department is > 3.
Also it displays records in order of dno.
14. select avg(salary) from emp;
-> Displays avg salary of all employees.
15. select max(salary),deptno from emp group by deptno having max(sal) > 20000;
-> Displays department-wise maximum salary, if maximum salary > 20000.
16. select deptno, min(salary) from emp group by deptno;
-> It will display department-wise minimum of salary of employees.
SET B
Person (pnumber, pname, birthdate, income, aname(FK))
Area (aname,area_type)
Area -> Person
1 -> M
-> Create Area table and then create person table. Add constraint for area_type as ‘Urban’ or
‘Rural’
Insert 3 areas and 10 person information
1. List the names of all people living in ‘Pune’ area.
-> select pname from person where aname=‘Pune’;
2. List details of all people whose names start with the alphabet ‘R’ & contains maximum 4
alphabets in it.
-> select * from person where pname like ‘R___’; (3 underscore)
3. List the names of all people whose birthday falls in the month of ‘February’.
-> select pname from person where extract(month from birthdate)=02;
4. Give the count of people who are born on ‘1995-05-25’.
-> select count(pnumber) from person where birthdate=‘1995-05-25’;
5. Give the count of people whose income is below < 30000.
-> select count(pnumber) from person where income < 30000;
6. List names of all people whose income is between 20000 and 40000;
-> select pname from person where income between 20000 and 40000;
7. List the names of people with average income.
->
8. List the sum of incomes of people living in ‘Mumbai’.
-> select sum(income) from person where aname=‘Mumbai’;
9.
10. Give the count of people in each area.
-> select aname, count(pnumber) from person group by aname;
11. List the details of people living in ‘Satara’ and having income greater than 40000.
-> select * from person where aname=‘Satara’ and income > 40000;
12. List the details of people, sorted by person number.
-> select * from person order by pnumber.
13. List the details of people, sorted by area, person name
-> select * from person order by aname, pname; (2 level sorting)
14. List the minimum income of people.
-> select min(income) from person;
15. Transfer all people living in ‘pune’ to ‘mumbai’.
-> update area set aname=‘mumbai’ where aname=‘pune’;
Having clause:
Syntax:
Select columnname1, columnname2,…., columnname n
from tablename1, tablename2,….., tablenamen
[where condition]
[order by columnname1, columnname2,…., columnname n]
[group by columname]
[having condition];
It there is a condition on groups rather than tuples(rows) then having clause is used. This
condition does not apply to single tuple, it applies to each group constructed by group by clause.
1. Display department-wise number of employees if count of employees greater than 3.
-> select dno, count(eno) from emp group by dno having count(eno)>3;
2. Display department-wise minimum salary if minimum salary in < 25000;
-> select dno, min(salary) from emp group by dno having min(salary) < 25000;
3. List department-wise total salary if total salary of department greater than or equal to 80000.
-> select dno, sum(salary) from emp group by dno having sum(salary)>80000;

Checking for NULL and not NULL values.


1. Display information of employees where mobile no is not specified.
-> select * from emp where mobileno is null;
2. Display information of employees where mobile no is specified.
-> select * from emp where mobileno is not null;

Set Operations: In SQL set operation works on two tables.


There following set operations:
1. Union: It returns all rows of first table and all rows of second table eliminating duplicate
values.
2. Union all: It returns all rows of first table and all rows of second table without eliminating
duplicate values.
3. Intersect: It returns common values from both the table eliminating duplicate values.
4. Intersect all: It returns common values from both the table without eliminating duplicate
values.
5. except: It returns values from first table which are not in 2nd table eliminating duplicate values.
6. except all: It returns values from first table which are not in 2nd table without eliminating
duplicate values.

Assignment 10:
create table department(dno int primary key, dname varchar(20));
create table nonteaching(empno int primary key, name varchar(20), address varchar(20), salary
int, dno int references department(dno) on delete cascade on update cascade);
create table teaching(empno int primary key, name varchar(20), address varchar(20), salary int,
dno int references department(dno) on delete cascade on update cascade);
insert into department values(10, 'Physics');
insert into department values(20, 'Maths');
insert into department values(30, 'Computer');
insert into nonteaching values(111, 'Mr. Patil', 'Pune', 18000,10);
insert into nonteaching values(112, 'Mr. Kale', 'Pune', 22000,10);
insert into nonteaching values(113, 'Mr. Pawar', 'Mumbai', 20000,20);
insert into nonteaching values(114, 'Mrs. Nene', 'Nasik', 25000,30);
insert into nonteaching values(115, 'Mr. Patil', 'Nagpur', 30000,20);
insert into teaching values(1001, 'Mr. Nene', 'Nagpur', 50000,10);
insert into teaching values(1002, 'Mr. Patil', 'Pune', 65000,10);
insert into teaching values(1003, 'Mrs. Joshi', 'Mumbai', 60000,30);
insert into teaching values(1004, 'Mr. Shah', 'Nagpur', 70000,30);
insert into teaching values(1005, 'Mr. Khan', 'Pune', 70000,20);
insert into teaching values(1006, 'Mr. Shah', 'Pune', 68000,20);
Queries:
1. select name from nonteaching union select name from teaching;
2. select name from nonteaching union all select name from teaching;
3. select name from nonteaching intersect select name from teaching;
4. select name from nonteaching intersect all select name from teaching;
5. select name from teaching except select name from nonteaching;
//this is values from teaching which are not present in nonteaching
6. select name from nonteaching except select name from teaching;
//this is values from nonteaching which are not present in teaching
Assignment 10: SET B
emp(empid(PK) ,emp_name, address, bdate)
Investor( inv_name, inv_no(PK), inv_date, inv_amt, empid(FK))
emp->investor
1–M
NOTE: For column emp-name and inv-name keep some names common in both columns.
Emp(1, ‘Ajay’, ‘Pune’, ‘1990-03-21’)
Emp(2, ‘Sheetal’, ‘Pune’, ‘1992-07-28’)
Emp(3, ‘Nita’, ‘Pune’, ‘1990-06-25’)
Investor(‘Ajay’, ‘1001’ , ‘2020-12-20’, 10000, 1);
Investor(‘Ajay’, ‘1002’ , ‘2021-01-01’, 20000);
Investor(‘Sheetal’, ‘1003’ , ‘2020-12-20’, 25000, 2);
Investor(‘Amit’, ‘1003’ , ‘2020-11-25’, 30000);
Queries:
1. List the distinct names of customers who are either employees, or investors or both.
-> select emp_name from emp union select inv_name from investor;
Assignment 10: SET B
2. List the names of customers who are either employees , or investors or both.
-> select emp_name from emp union all select inv_name from investor;
3. List the names of employees who are also investors.
-> select emp_name from emp intersect select inv_name from investor;
4. List the names of employees who are not investors.
-> select emp_name from emp except select inv_name from investor;
Nested Sub Queries:
Consider emp and dept table.
Dept(dno(PK), dname)
Emp (eno(PK), ename, address, mobileno, salary, dno(FK))
Dept->Emp 1->M
1. List the details of employees from dept no =10;
-> select * from emp where dno = 10;
2. List the details of employees from ‘Accounts’ department;
-> select * from emp where dno=(select dno from dept where dname='Accounts');
select * from emp where dno -> This is outer query.
select dno from dept where dname='Accounts‘ -> This is inner query or subquery Where output
of inner query is provided to outer query.
OR Using join querys
select ename, salary, emp.dno from emp,dept where emp.dno=dept.dno and dname='Accounts';

3. Display count of employees from ‘Purchase’ department.


-> select count(eno) from emp where dno=(select dno from dept where dname=‘Purchase’);
4. Update salaries of employees from department ‘Sales’ by 10%.
-> update emp set salary = salary + (salary*0.10) where dno=(select dno from dept where dname
= ‘Sales’);
5. Display names of employees from department ‘Sales’ whose salary is > 50000;
-> select ename from emp where salary > 50000 and dno=(select dno from dept where dname =
‘Sales’);
6. Display name of employee having maximum salary of all.
-> select ename from emp where salary=(select max(salary) from emp);
7. Display name of employee having maximum salary from department ‘Accounts’.
-> select ename from emp where salary=(select max(salary) from emp where dno=(select dno
from dept where dname='Accounts'));
Join: A SQL join statement is used to combine data from two or more tables based on common
fields. There are types of join as,
1. Inner join
2. Left Outer join
3. Right Outer join
4. Full Outer join
5. Self join
Lets create table.
Student(RollNo, Name)
Create table student(rollno int primary key, name varchar(30));
Course(cid, cname)
Create table course(cid in primary key, cname varchar(30));
Student->Course M-M
course_student(Cid, RollNo)
create table course_student(cid int references course(cid) on delete no action on update no action
, rollno int references student(rollno) on delete no action on update no action, primary key(cid,
rollno));
postgres=# select * from student;
rollno | name
--------+--------
1 | Harsh
2 | Deep
3 | Rohit
4 | Meenal
5 | Niraj
6 | Rahul
7 | Sita
8 | Gita
postgres=# select * from course_student;
cid | rollno
-----+--------
111 | 1
112 | 2
112 | 3
113 | 4
111 | 5
114 | 9
115 | 10
114 | 11
115 | 1
1. Inner join: It returns records that have matching values from both tables.

It returns records that have matching values from both tables.


select student.rollno, cid, name from student
inner join course_student
on student.rollno=course_student.rollno;
rollno | cid | name
--------+-----+--------
1 | 111 | Harsh
2 | 112 | Deep
3 | 112 | Rohit
4 | 113 | Meenal
5 | 111 | Niraj
1 | 115 | Harsh
Above inner join works on rollno that is matching column in both the tables. It returns
records of those student who are present in student table and opted any course.
2. Left Outer join: It returns all the rows of the table on left side of the join and matching
rows of the table on right side of join. The rows for which there is no matching row on
right side the result set contains NULL.

select student.rollno, name, cid from student


left join course_student
on student.rollno=course_student.rollno;
rollno | name | cid
--------+--------+-----
1 | Harsh | 111
2 | Deep | 112
3 | Rohit | 112
4 | Meenal | 113
5 | Niraj | 111
1 | Harsh | 115
8 | Gita |
6 | Rahul |
7 | Sita |
It returns all students rollno, name from student table who have opted and not opted for any
course. If student has opted for any course then it displays course otherwise it displays
NULL.
3. Right Outer join: It returns all the rows of the table on right side of the join and
matching rows of the table on left side of join. The rows for which there is no matching
row on left side the result set contains NULL.

select student.rollno, name, cid from student


right join course_student
on student.rollno=course_student.rollno;

rollno | name | cid


--------+--------+-----
1 | Harsh | 111
2 | Deep | 112
3 | Rohit | 112
4 | Meenal | 113
5 | Niraj | 111
| | 114
| | 115
| | 114
1 | Harsh | 115
It returns all rows from course. Students who have opted course and present in student
table as well as student who had opted course but are not present now in student table.
4. Full Outer join: It creates the result by combining result of both left join and right join.
The result set contains all rows from both tables. The rows for which there is no matching
will contains NULL.
select student.rollno, name, cid from student
full join course_student
on student.rollno=course_student.rollno;
rollno | name | cid
--------+--------+-----
1 | Harsh | 111
2 | Deep | 112
3 | Rohit | 112
4 | Meenal | 113
5 | Niraj | 111
| | 114
| | 115
| | 114
1 | Harsh | 115
8 | Gita |
6 | Rahul |
7 | Sita |

It returns all rows from course and Students. If there is no matching for any records it
returns NULL.
5. Self join: The table which joins with itself.
Display employees names with same addresses.
select A.ename as Emp1, B.ename as Emp2,A.address from emp A, emp B Where
A.eno<>B.eno and A.address=B.address order by A.address;
emp1 | emp2 | address
--------+--------+---------
Amit | Neha | Mumbai
Amit | Riya | Mumbai
Neha | Amit | Mumbai
Neha | Riya | Mumbai
Riya | Amit | Mumbai
Riya | Neha | Mumbai
Kiran | Arpita | Nasik
Arpita | Kiran | Nasik
AJIT | Amit | Pune
AJIT | anay | Pune
Amit | AJIT | Pune
Amit | anay | Pune
anay | AJIT | Pune
anay | Amit | Pune
Assignment 12: SET A
PROJECT (PNO INTEGER, P_NAME CHAR(30), PTYPE CHAR(20),DURATION
INTEGER)
EMPLOYEE(ENO INTEGER, E_NAME CHAR (20), QUALIFICATION CHAR (15),
JOINDATE DATE)
Project - > Employee M->M with descriptive attributes as start_date (date),
no_of_hours_worked (integer).
create table project (pno int primary key, pname varchar(30), ptype char(20), duration int);
create table employee(eno int primary key, ename char(20), qualification char(15), joindate
date);
create table emp_proj(eno int references employee(eno) on delete cascade on update cascade ,
pno int references project(pno) on delete cascade on update cascade, start_date date, hrs_worked
int, primary key(eno,pno));
insert into employee values (2000, 'Atul', 'MSc CS', '2018-02-01');
insert into employee values (2001, 'Akash', 'MSc CA', '2020-05-15');
insert into employee values (2002, 'Swati', 'BTech', '2012-11-10');
insert into project values(1000,'Home Automation', 'System', 2);
insert into project values(1001,'AI in Mall', 'Robotics', 4);
insert into project values(1002,'e-waste management', ‘Green Computing', 5);
insert into project values(1003,'Find Map', 'SEO', 3);
insert into emp_proj values(2000, 1001, '2019-01-20', 30);
insert into emp_proj values(2000, 1002, '2019-05-22', 50);
insert into emp_proj values(2001, 1002, '2020-06-10', 70);
insert into emp_proj values(2001, 1000, '2020-08-10', 20);
insert into emp_proj values(2002, 1001, '2015-03-12', 100);
insert into emp_proj values(2002, 1002, '2017-09-14', 50);
insert into emp_proj values(2002, 1003, '2014-07-02', 200);
1. Find the names of the employees starting with ’A’.
-> select ename from employee where ename like ‘A%’;
2. Find the details of employees working on the project “System”.
-> select * from employee where eno in(select eno from emp_proj where pno=(select pno from
project where ptype='System'));
Note: - In above query ‘in’ is used because inner query is returning more than one row. In
nested subquery output of inner query is provided as a input to outer query.
select pno from project where ptype='System‘; o/p = 1000;
select eno from emp_proj where pno=1000; o/p = 2000,2001 (Returing more than one row)
select * from employee where eno = 2000 and eno=2001; ->Atul, akash
3. Find the employee numbers of the employees, who do not work on project “Robotics”.
-> select eno,ename from employee where eno <some(select eno from emp_proj where pno not
in(select pno from project where ptype='Robotics'));
select count(eno) from employee where eno <some(select eno from emp_proj where pno not
in(select pno from project where ptype='Robotics'));

4. Get employee number of the employee, who works on at least one project that employee
number ‘2000’ works on.
->
5. List the names of the first three employees in alphabetical order.
-> select ename from employee order by ename limit 3;
6. Find the names of the employees whose project duration is more than three years.
-> select ename from employee where eno in(select eno from emp_proj where pno in(select pno
from project where duration>3));
SET B:
BRANCH (bid integer, brname char (30), brcity char (10))
CUSTOMER (cno integer, cname char (20), caddr char (35), city (20))
LOAN_APPLICATION (lno integer, lamtrequired money, lamtapproved money, l_date date)
The relationship is as follows:
BRANCH, CUSTOMER, LOAN_APPLICATION are related with ternary relationship.
TERNARY (bid integer, cno integer, lno integer).
-> create table branch(bid integer primary key, brname char(30), brcity char(10));
create table customer(cno integer primary key, cname char(20), caddr char(35), city(20))
create table(lno integer primary key, lamtrequired money, lamtapproved money, l_date date)
create table ternary(bid integer references BRANCH(bid) on delete cascade on update cascade,
cno integer references CUSTOMER(cno) on delete cascade on update cascade, lno integer
references LOAN_APPLICATION(lno) on delete cascade on update cascade, primary key(bid,
cno, lno));
Insert values in branch table:
e.g.
insert into BRANCH values(1,'Kothrud','Pune');
Insert values in customer table:
e.g.
insert into CUSTOMER values(101,'Prakash','Karvenagar','Pune');
Insert values in LOAN_APPLICATION table:
e.g.
insert into LOAN_APPLICATION values(11,'10000','9000',‘2020-02-10');
insert into LOAN_APPLICATION values(12,‘40000',‘35000',‘2020-05-15');
Insert values in TERNARY table:
insert into TERNARY values(1, 101, 11);
insert into TERNARY values(2, 101, 12);
Queries:
1. Find the names of the customers for the “Aundh” branch.
-> select cname from CUSTOMER where cno in(select cno from TERNARY where bid = (select
bid from BRANCH where brname=‘Aundh’));
OR (Using join)
-> select cname from CUSTOMER, TERNARY, BRANCH where CUSTOMER.cno=
TERNARY.cno and TERNARY.bid=BRANCH.bid and brname=‘Aundh’;
NOTE: If we want columns values only from one table then we can write nested sub query. But
If we want display columns values from different tables then write query using join.
Queries:
2. List the names of the customers who have received loan less than their requirement.
-> select cname from CUSTOMER where cno in(select cno from TERNARY where lno in(select
lno from LOAN_APPLICATION where lamtapproved < lamtrequired));
OR (Using join):
Select cname from CUSTOMER, LOAN_APPLICATION, TERNARY where
CUSTOMER.cno= TERNARY.cno and TERNARY.lno=LOAN_APPLICATION.lno and
lamtapproved < lamtrequired;
3. Find the maximum loan amount approved.
-> select max(lamtapproved) from LOAN_APPLICATION;
4. Find out the total loan amount sanctioned by “Deccan” branch.
-> select sum(lamtapproved) from LOAN_APPLICATION where lno in(select lno from
TERNARY where bid=(select bid from BRANCH where brname=‘Deccan’));
OR
Select sum(lamtapproved) from LOAN_APPLICATION, TERNARY, BRANCH where
LOAN_APPLICATION.lno= TERNARY.lno and TERNARY.bid= BRANCH.bid and
brname=‘Deccan’;
5. Count the number of loan applications received by “M.G.ROAD” branch.
-> select count(lno) from LOAN_APPLICATION where lno in(select lno from
TERNARY where bid=(select bid from BRANCH where brname=‘M.G.Road’));
OR
Select count(lno) from LOAN_APPLICATION, TERNARY, BRANCH where
LOAN_APPLICATION.lno= TERNARY.lno and TERNARY.bid= BRANCH.bid and
brname=‘M.G.Road’;
6. List the names of the customer along with the branch names who have applied for loan in the
month of September.
-> select cname, brname from CUSTOMER, BRANCH, TERNARY, LOAN_APPLICATION
where CUSTOMER.cno = TERNARY.cno and TERNARY.bid = BRANCH.bid and
LOAN_APPLICATION.lno = TERNARY.lno and extract (month from l_date)=09;

You might also like