NoVowel = []
def PushNV(N) :
for i in range(len(N)):
vowel = False
for x in N[i]:
if x in “AEIOUaeiou” :
vowel = True
break
if vowel == False: # if not vowel:
NoVowel.append(N[i])
def Pop():
while True:
if NoVowel == [] :
print(“Empty Stack”)
break
else:
n = NoVowel.pop()
print(n, end = “ ”)
All = []
for i in range(5):
n = input(“Enter a word : ”)
All.append(n)
PushNV(All)
Pop()
while True:
if NoVowel == [] :
print(“Empty Stack”)
break
else:
n = NoVowel.pop()
print(n, end = “ ”)
SQL – 20 1 X 7 MCQ, 2 x 2 Short Notes, ½ X 4 output, 1 X 4
SELECT output, 1 Degree/Cardinality
Structured Query Language
Theory:
DBMS Advantages :
Reduces Redundancy
Controls Data Inconsistency
Enforce Standard
Ensure Data Security
Enforce Data Integrity
DBMS Data Base Management System
Types of DBMS
HDBMS : Hierarchical Data Base Management System
NDBMS : Network Data Base Management System
RDBMS : Relational Data Base Management System
Terminology
Relation arrangement of data in rows and columns, Also known
as (aka) Table
Tuple Row in a relation (table)
Attribute Columns of a relation (table)
Domain Pool of values from which values for a column
(attribute) in a relation is picked.
Degree Number of Attributes (columns) in relation
Cardinality Number of Tuples (rows) in a relation
Primary Key A key attribute or combination of attributes which is
responsible for unique identification of each tuple in a
Relation
Example empno in Employee Table
AdmissionNo in student table
Candidate Key all the key attributes or combinations of attributes
for identification of tuple in relation are called
candidate keys.
Example empno, ename+deptno+hiredate,
ename+hiredate
admissionno, class+sec+rollno,
name+dob+phone
Alternate Key A key attribute that can act as primary key in the
absence of Primary Key
Example ename+deptno+hiredate
class+sec+rollno
Foreign Key a Non-Key Attribute which is primary key in some
other relation
Example deptno in Employee (deptno is Primary in
dept table)
stream in Student Table (stream is
primary key in SubjectCombination table)
In 2 Tables identify, candidate key, primary key, alternate key, foreign
key
Column having Code, Number, ID are Primary + Unique value
Foreign Key common column in two tables ( duplicate foreign key,
unique primary key)
SQL
- Structured Query Language
- Non-Procedural language used to access data in Relational
Database.
Example MySQL, Oracle, SQL Server, Ingress, Sybase
Features of MySQL
Free and Open Source Software (FLOSS)
Portable
Easy and Versatile
Secured
Examples of RDBMS
Types of SQL commands DDL, DML
- DDL Data Definition Language
o CREATE, ALTER, DROP
- DML Data Manipulation Language
o SELECT, INSERT, UPDATE, DELETE
Constraints Primary key, Unique, Not Null
Primary Key Unique Not Null
Duplicate Values Not Allowed Not Allowed Allowed
Empty Not Allowed Allowed Not Allowed
CHAR vs VARCHAR
Char Varchar
Fixed Length Character Data Varying Length Character Data
CHAR VARCHAR(n)
CHAR(n)
Where n is number of characters
N is Total number of characters in Maximum number of characters in
each data. each data ( minimum can be Zero)
“Anil ” 10 Character “Anil” 4 Character
“Amitabh ” 10 Character “Amitabh” 7 Character
Remaining places are padded with
blank space.
DISTINCT
WHERE vs HAVING
ORDER By ASC vs DESC
GROUP BY
DROP vs DELETE
IS NULL, LIKE
Aggregate Function COUNT, AVG, SUM, MIN/MAX
Syntax SELECT, UPDATE, INSERT, DELETE
CREATE TABLE, ALTER TABLE, DROP
1. To display the list of available databases
SHOW DATABASES
2. To open a Database
USE databasename
3. To display the list of tables
SHOW TABLES
4. Display the structure of the Table
DESC tablename
DESCRIBE tablename
DDL Data Definition Language
CREATE TABLE, ALTER TABLE, DROP TABLE
CREATE DATABASE, DROP DATABASE
Creating a database
CREATE DATABASE dbname
CREATE DATABASE sample
USE sample
Deleting a database
DROP DATABASE dbname
DROP DATABASE sample
Creating Table
CREATE TABLE tablename
(
column_details
)
column_details column_name datatype(size, precision) constraint
datatype
int / integer / numeric
[ int, integer, int(size), integer(size), numeric(size, 0)]
char / varchar
[ char(size) / varchar(size) ]
decimal / numeric non-dec places + . + dec places
[ numeric(size, dec) / decimal(size, dec) ]
99999.99 size = 8, precision/dec = 2
date No size
Constraints Primary Key
Unique
Not Null
DEFAULT value used when INSERT
CHECK
REFRENCES (Foreign Key Constraint)
Write SQL command to Create a table student
Column Datatype Description
Adm no 4 digit integer Primary key
Name 30 char Character Can not be empty
Fee Float with 2 dec places Default value is 1000
Date of birth date
CREATE TABLE student
(
admno INT(4) PRIMARY KEY,
name CHAR(30) NOT NULL,
fee NUMERIC(10, 2) DEFAULT 1000.00,
dateofbirth DATE
)
ALTER TABLE change the table structure
ALTER TABLE tablename
ADD / MODIFY / DROP / CHANGE
(
column_details
)
1. Adding new column
Write SQL command to add a new column Marks of decimal and
gender M or F into student table
ALTER TABLE student
ADD ( marks DECIMAL(5, 1),
gender CHAR(1) )
2. Changing Existing Column data type, size, precision, constraints
Write SQL command to change the data type of name from char to
varchar of 30 characters
ALTER TABLE student
MODIFY ( name VARCHAR(30) )
3. Deleting existing column
SQL command to delete the marks column
ALTER TABLE student
DROP marks
Deleting Table
DROP TABLE tablename
DROP TABLE student
Difference between DROP and DELETE
DROP DELETE
DDL – Data Definition Language DML – Data Manipulation
Language
Deletes the entire data along with It deletes the rows of a table, The
the table structure table structure remains intact.
Table once Dropped can’t be used Table once deleted can further be
used to add more data.
DROP can’t be rollbacked. If not committed, then delete can be
rollbacked.
DML – SELECT / INSERT / UPDATE / DELETE
SELECT to list/ to show/ to display/ to select
SELECT DISTINCT column_expression_list alias
FROM table_list
WHERE row_predicate
GROUP BY columns
HAVING aggregate_condition
ORDER BY column DESC
SELECT *
FROM empl
SELECT ename, job, sal
FROM empl
SELECT ename, sal*12
FROM empl
SELECT ename “Emp Name”, sal*12 “Annual Salary”, sal*.1 Bonus
FROM empl
SELECT job
FROM empl
SELECT DISTINCT job
FROM empl
WHERE row_predicate
1. Relational Operator
<, <=, >, >=, =, <> (!=)
WHERE deptno = 10
WHERE job = “Clerk”
WHERE hiredate >= “2010.12.31”
Date < Previous / Earlier / before
> Later / After
2. Logical operator
AND, OR, NOT
Employees who are not in deptno 20
WHERE deptno <> 20
WHERE NOT deptno = 20
Clerks of deptno 30
WHERE deptno = 30 AND job = “Clerk”
Employees who are either clerk or working in deptno 30
WHERE job = “Clerk” OR deptno = 30
3. BETWEEN … AND
WHERE sal BETWEEN 1000 AND 3000
WHERE sal >= 1000 AND sal <= 3000
List details of section A to D students
SELECT * FROM student
WHERE section BETWEEN ‘A’ AND ‘D’
SELECT * FROM student
WHERE section >= ‘A’ AND section <=’D’
WHERE section BETWEEN “A” AND “D”
WHERE section >= “A” AND section <= “D”
WHERE hiredate BETWEEN “2010.01.01” AND “2010.12.31”
WHERE hiredate >=“2010.01.01” AND hiredate <=“2010.12.31”
WGERE year(hiredate) = 2010
SELECT * from STUDENT
WHERE dateofadm>=”2005.05.01” AND
dateofadm<= “2005.05.31”
SELECT * FROM student WHERE month(dateofadm) = 5
4. IN
selection out of multiple choices
WHERE job IN (‘Clerk’, ‘Salesman’, ‘Analyst’)
Write SQL command to display details of all the clerks salesmen and
analysts
SELECT * FROM empl
WHERE job IN (‘Clerk’, ‘Salesman’, ‘Analyst’)
List of employees joined the company in 2010, 2012, 2014
SELECT * FROM empl
WHERE year(hiredate) IN (2010, 2012, 2014)
SELECT * FROM empl
WHERE job = ‘Clerk’ OR job = ‘Salesman’ OR job = ‘Analyst’
5. IS NULL / IS NOT NULL
Happening of Event IS NOT NULL
Non-Happening of event IS NULL
SELECT * FROM empl
WHERE comm IS NULL;
Employees getting commission
WHERE comm IS NOT NULL
Employees not getting commission
WHERE comm IS NULL
Student appeared in Exam
WHERE marks IS NOT NULL
Student absents in exam
WHERE dateofexam IS NULL
6. Pattern Matching LIKE / NOT LIKE
column LIKE / NOT LIKE ‘pattern’
Pattern % _ (wild card character)
Wild card characters are special symbols used in pattern for
replacement by other characters
% zero or more characters replacement
_ one and only one character replacement
pa_an pavan, palan, pawan, paran, pakan
pa%an paan, pavan, pawan, pavvan, pakakakaknmeoprhfjkfan
whose name starts with A
WHERE ename LIKE ‘A%’
Whose name ends with ‘T’
WHERE ename LIKE ‘%T’
Whose name start with A and have only 5 characters
WHERE ename LIKE ‘A_ _ _ _’
Whose name have singh singh% %singh% %singh
WHERE ename LIKE ‘%singh%’
Singh Amar Daas
Amar Dass Singh
Amar Singh Grover
List of students having gmail account
SELECT * FROM student WHERE email LIKE ‘%@gmail.%’
ORDER BY Clause
Used to arrange data in ascending or descending order of a column
ORDER BY column_name DESC
Write sql command to list employees in ascending order of their salary
SELECT * FROM empl
ORDER BY sal
In descending order of their name
SELECT * FROM empl
ORDER BY ename DESC
List all the clerks in descending order of salary
SELECT * FROM empl
WHERE job = ‘Clerk’
ORDER BY sal DESC
Product
Product_Id Product_name Price Category_ID
2 Bricks 26.70 3 Toys
4 Sofa 3200.00 1 Furniture
5 Desk 1350.00 1 Furniture
Category
Category_ID Product_Group
1 Furniture
3 Toys
SELECT Product.product_name, Category.product_group FROM
product, category where product.category_ID = category.Category_ID
Product.product_name Category.product_group
Bricks Toys
Sofa Furniture
Desk Furniture
Teacher_ID Count(*)
101 2
102 2
104 2
GROUP BY Clause
- Group By is always used with Aggregate Functions (min, max,
sum, avg, count)
- Select clause always include the column used in Group By clause
- ( if a select clause uses a column to display, then that column must
be used in Group By clause)
SELECT deptno, sum(sal) FROM empl
GROUP BY deptno
SELECT job, avg(sal) FROM empl
GROUP BY job
Write SQL command to display total salary
SELECT sum(sal) FROM empl
Write SQL command to display total salary department wise (for each
department)
SELECT deptno, sum(sal) FROM empl
GROUP BY deptno
SELECT deptno, sum(sal) FROM empl
GROUP BY deptno
Write SQL command to display total salaries of different jobs
SELECT job, sum(sal) FROM empl
GROUP BY job
Display sum of salaries of different department for male employees
SELECT deptno, sum(sal) FROm empl
WHERE gender = “M”
GROUP BY deptno
Display total salary of each department having more than 2 employees
SELECT deptno, sum(sal)
FROM empl
GROUP BY deptno
HAVING count(*) > 2
COUNT Counts not null values of a column
COUNT(*) counts the rows
COUNT(column) counts the NOT NULL columns
COUNT(DISTINCT column) ignores duplicate and nulls
SELECT count(*) FROM empl; 14
SELECT count(comm) FROM empl; 5
SUM(column) / AVG(column ) they will be used with Numeric Data
type
MIN(column) / MAX(column) used with any data type
HAVING clause
WHERE & HAVING
- Having used with Group By clause only
- Having is mostly used to compare aggregate (min, max, sum,
count, avg) values
Write SQL command to display total salary of all the clerks
SELECT sum(sal) FROM empl
WHERE job = ‘Clerk’
Write SQL command to display the total salary of each job
SELECT job, sum(sal) FROM empl
GROUP BY job
Write SQL command to display the total salary of each job for those jobs
where number of employees are more than 2
SELECT job, sum(sal) FROM empl
GROUP BY job
HAVING count(*) > 2
Write SQL command to display the total salary of each job for males only
SELECT job, sum(sal) FROM empl
WHERE gender = “M”
GROUP BY job
SELECT * FROM empl
WHERE year(hiredate) = 2010
SELECT * FROM student
WHERE day(dob) = 1
Cartesian Product / Cross Product / Cross JOIN querying multiple
tables without any common criteria
Degrees Added A (4,3)xB(10, 2)C(40,5)
Cardinality Multiplied
Join querying multiple tables with conditions
Natural Join Equi Join Inner Join Self Join
Non-Natural Join Non-Equi Join Outer Join
Column name Operator =
A B
Name deptno deptno place
X 10 10 Prayagraj
Y 30 20 Kaushambi
X 10 10 Prayagraj A.deptno = B.deptno
X 10 10 Prayagraj A.deptno(-) = B.deptno
Y 30 -- -----------
X 10 10 Prayagraj A.deptno = B.deptno (-)
-- -- 20 Kaushambi
JOIN:
1. Find common column to decide the joining criteria
2. Common column should always referred with table name or table
alias
Write SQL query to display details of employees and their departments
SELECT *
FROM empl, dept
WHERE empl.deptno = dept.deptno
SELECT *
FROM empl e, dept d
WHERE e.deptno = d.deptno
Write SQL query to display name of employee, department name and
location
SELECT ename, dname, loc
FROM empl, dept
WHERE empl.deptno = dept.deptno
Write SQL query to display name of employee, department number,
department name and location of all the clerks and salesmen
SELECT ename, empl.deptno, dname, loc
FROM empl, dept
WHERE empl.deptno = dept.deptno
AND job IN (“Clerk”, “Salesman”)
SELECT ename, job, sal, E.deptno, loc
FROM empl E, dept D
WHERE empl.deptno = dept.deptno
SELECT ename, job, sal, grade
FROM empl, salgrade
WHERE empl.sal BETWEEN salgrade.losal AND salgrade.hisal
SELECT a.ename, a.job, a.mgr, b.ename
FROM empl a, empl b
WHERE a.mgr = b.empno
UPDATE to change / modify / edit / increase / decrease / set
UPDATE tablename
SET column_name = new_value
WHERE condition
Command to increase salary by 100
UPDATE empl
SET sal = sal + 100
Command to increase salary by 100 and commission by 50
UPDATE empl
SET sal = sal + 100, comm = comm + 50
Command to increase salary by 10% for all the clerks
UPDATE empl
SET sal = sal * 1.1
WHERE job = “Clerk”
To change category from 13 to 31
UPDATE cd
SET category = 31
WHERE category = 13
sal = sal + sal * 10/100
sal = sal + sal * .1
sal = sal * 1.1
INSERT To add new Row
INSERT INTO table_name
VALUES (value_list)
Write SQL command to insert following row in empl table
1, pavan, teacher, 10, 1992-12-12, 800, NULL, 30
INSERT INTO empl
VALUES (1, “pavan”, “teacher”, 10, “1992-12-12”, 800, NULL, 30)
DELETE delete tuple / row / record
DELETE FROM table_name
WHERE condition
Delete all the records
DELETE FROM empl
Deletes only clerks
DELETE FROM empl
WHERE job = “Clerk”
Sample Question paper
Fill in the blank:
______ command is used to remove primary key from the table in SQL.
(a) update (b)remove (c) alter (d)drop
Which of the following commands will delete the table from MYSQL
database?
(a) DELETE TABLE
(b) DROP TABLE
(c) REMOVE TABLE
(d) ALTER TABLE
Fill in the blank:
_________ is a non-key attribute, whose values are derived from the
primary key of some other table.
(a) Primary Key
(b) Foreign Key
(c) Candidate Key
(d) Alternate Key
Fill in the blank:
The SELECT statement when combined with __________ clause, returns
records without repetition.
(a) DESCRIBE
(b) UNIQUE
(c) DISTINCT
(d) NULL
Which function is used to display the total number of records from table in
a database?
(a) sum(*)
(b) total(*)
(c) count(*)
(d) return(*)
Explain the use of ‘Foreign Key’ in a Relational Database Management
System. Give example to support your answer.
Differentiate between count() and count(*) functions in SQL with
appropriate example.
OR
Categorize the following commands as DDL or DML:
INSERT, UPDATE, ALTER, DROP
Consider the following tables – Bank_Account and Branch:
Table: Bank_Account
ACode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current
Table: Branch
ACode City
A01 Delhi
A02 Mumbai
A01 Nagpur
(a) What will be the output of the following statement?
SELECT * FROM Bank_Account NATURAL JOIN Branch;
SELECT * FROM Bank_account, Branch
WHERE Bank_account.A_Code = Branch.A_Code
(b) Write the output of the queries (i) to (iv) based on the table,
TECH_COURSE given below:
Table: TECH_COURSE
CID CNAME FEES STARTDATE TID
C201 Animation and VFX 12000 2022-07-02 101
C202 CADD 15000 2021-11-15 NULL
C203 DCA 10000 2020-10-01 102
C204 DDTP 9000 2021-09-15 104
C205 Mobile Application 18000 2022-11-01 101
Development
C206 Digital marketing 16000 2022-07-25 103
(i) SELECT DISTINCT TID FROM TECH_COURSE;
(ii) SELECT TID, COUNT(*), MIN(FEES) FROM TECH_COURSE
GROUP BY TID HAVING COUNT(TID)>1;
(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000
ORDER BY CNAME;
(iv) SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES
BETWEEN 15000 AND 17000;
(a) Write the outputs of the SQL queries (i) to (iv) based on the relations
Teacher and Placement given below:
Table : Teacher
T_ID Name Age Department Date_of_join Salary Gender
1 Arunan 34 Computer Sc 2019-01-10 12000 M
2 Saman 31 History 2017-03-24 20000 F
3 Randeep 32 Mathematics 2020-12-12 30000 M
4 Samira 35 History 2018-07-01 40000 F
5 Raman 42 Mathematics 2021-09-05 25000 M
6 Shyam 50 History 2019-06-27 30000 M
7 Shiv 44 Computer Sc 2019-02-25 21000 M
8 Shalakha 33 Mathematics 2018-07-31 20000 F
Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur
(i) SELECT Department, avg(salary) FROM Teacher GROUP BY
Department;
(ii) SELECT MAX(Date_of_Join), MIN(Date_of_Join) FROM Teacher;
(iii) SELECT Name, Salary, T.Department, Place FROM Teacher T,
Placement P WHERE T.Department = P.Department AND Salary>20000;
(iv) SELECT Name, Place FROM Teacher T, Placement PWHERE
Gender =’F’ AND T.Department=P.Department;
Navdeep creates a table RESULT with a set of records to maintain the
marks secured by students in Sem 1, Sem2, Sem3 and their division. After
creation of the table, he has entered data of 7 students in the table.
Table: RESULT
ROLL_NO SNAME SEM1 SEM2 SEM3 DIVISION
101 KARAN 366 410 402 I
102 NAMAN 300 350 325 I
103 ISHA 400 410 415 I
104 RENU 350 357 415 I
105 ARPIT 100 75 178 IV
106 SABINA 100 205 217 II
107 NEELAM 470 450 471 I
(b) Write the command to view all tables in a database.
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as
Primary key.
(ii) If two columns are added and 2 rows are deleted from the table result,
what will be the new degree and cardinality of the above table?
(iii) Write the statements to:
a. Insert the following record into the table
Roll No- 108, Name- Aadit, Sem1- 470, Sem2-444, Sem3-475, Div – I.
INSERT INTO result
VALUES( 108, “Aaadit”, 470, 444, 475, “I”)
b. Increase the SEM2 marks of the students by 3% whose name begins
with ‘N’.
UPDATE result
SET sem2 = sem2 * 1.03
WHERE name LIKE “N%”
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing IV division.
DELETE FROM result
WHERE div = “IV”
b. Add a column REMARKS in the table with datatype as varchar with 50
characters.
ALTER TABLE result
ADD ( remarks VARCHAR(50))