0% found this document useful (0 votes)
65 views27 pages

Computerscience Assignment

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views27 pages

Computerscience Assignment

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

VELAMMAL BODHI CAMPUS, THANJAVUR

HOLIDAY ASSIGNMENT – GRADE XII


SUBJECT – COMPUTER SCIENCE

String Functions

Q. What will be the output of the following code snippets?


1. phrase = "python programming"

print(phrase.capitalize())
2. sentence = "learn python programming"
print(sentence.title())
3. word = "UPPERCASE"
print(word.lower())
4. string = "lowercase"
print(string.upper())
5. text = "Python is powerful. Python is versatile."
print(text.count("Python"))
6. phrase = "The quick brown fox"
print(phrase.find("brown"))
7. word = "Hello, World!"
print(word.index("World"))
8. sentence = "Welcome to Python"
print(sentence.endswith("Python"))
9. string = "Python123"
print(string.startswith("Python"))
10. text = "OpenAI123"
print(text.isalnum())
11. phrase = "OpenAI"
print(phrase.isalpha())
12. word = "12345"
print(word.isdigit())
13. sentence = "pythonrocks"
print(sentence.islower())
14. string = "UPPERCASE"
print(string.isupper())
15. text = " "
print(text.isspace())
16. phrase = " Leading and Trailing Spaces "
print(phrase.lstrip())
17. word = " Spaces on the Right "
print(word.rstrip())
18. sentence = " Strip Spaces on Both Sides "
print(sentence.strip())
19. string = "Replace the old word"
print(string.replace("old", "new"))
20. text = "python"
print("#".join(text))

21. sentence = "This is a sentence"


parts = sentence.partition("is")
print(parts)
22. text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits)
23. word = "Programming is fun"
print(word.count("g", 6, 15))
24. phrase = "Python is amazing"
print(phrase.find("is", 6, 15))
25. sentence = "Python is versatile"
print(sentence.index("is", 6, 15))
26. text = "Python3"
print(text.isalnum())
27. phrase = "OpenAI"
print(phrase.isalpha())
28. word = "12345"
print(word.isdigit())
29. sentence = "pythonrocks"
print(sentence.islower())
30. string = "UPPERCASE"
print(string.isupper())
31. text = " \t "
print(text.isspace())
32. phrase = "pythonrocks"
print(phrase.lstrip("pr"))
33. word = "pythonrocks"
print(word.rstrip("s"))
34. sentence = " \t pythonrocks \t "
print(sentence.strip())
35. text = "Replace this word, not this word"
print(text.replace("word", "phrase", 1))
36. string = "openai"
print(string.swapcase())
37. text = "Python programming is fun"
print(text.startswith("Python", 2))
38. sentence = "This is Python. Python is great!"
print(sentence.endswith("is", 0, 11))
39. text = "Python is a versatile programming language."
print(text[len(text):0:-1])
Assignment 2
String Slicing

Predict the output of the following:


1. my_string = " Programming"
print(my_string[0:6])?
2. text = "Hello, World!"
print(text[:5])
3. word = "Python"
print( word[1:4])
4. phrase = "This is a test."
print(phrase[::2])
5. message = "Good morning"
print( message[::-1])
6. text = "Hello, World!"
print(text[7:])
7. text = " is fun!"
print(text[-4:])
8. greeting = "Hi there"
print(greeting[1:7:2])
9. text = " programming"
print(text[-5:-2])
10. text = "Python"
print( text[5:1:-1])
11. string = "Going Abroad"
print( string[1:5])
12. word = "Halloween"
print(word[::-1])
13. phrase = "Good morning"
print( phrase[5::-1])
14. text = " is great!"
print(text[1:9:2])
15. word = "Python"
print( word[2:-1])
16. text = "Learning Python"
print(text[:-2:-1])
17. sentence = "This is a sample sentence"
print(sentence[-11:-3])
18. word = "Python"
print( word[1:-1])
19. string = "abcdefg"
print(string[4:0:-1])
20. text = " programming"
print( text[13:9:-1])

Assignment 3
List

1. Write the most appropriate list method to perform the following tasks:
(i) To delete 4th element from the list.
(ii) To get the position of an item in the list.
(iii) To add an element in any position
(iv) To removes all elements
2. Suppose L=[“xyz”,6,9,”the”,2019,’a’,’b’,’s’,’x’]
Consider the above list and give output for the following:
(i) print(L[2:6])
(ii) print(L.index(2019))
(iii) print(len(L))
(iv) print(L.count(‘x’))
(v) print(L.pop(3))
(vi) print(L.remove(‘a’))
(vii) L.insert(2,’Sonia’)
print(L)
(viii) L.clear()
print(L)
3. Write the output:
my_list = [3, 8, 1, 6, 0, 8, 4]
my_list.sort()
print(my_list)
my_list.reverse()
print(my_list)
4. Based on the following python list, write the output of the questions:
L=[(“A”, “B”, “C”), [10,20,30], “Paramount Public School”, 11.0)
(i) print(L[0][1])
(ii) print(L[1][2])
(iii) print(L[2][4])
(iv) print(L[1])
(v) print(L[2])
(vi) pint(L[2][2:7])
5. Give the output of the following code:
a=[10,20,'abc',30,3.14,40,50]
print(a)
for i in range(0,len(a)):
print(a[i], end=' ')
print('\n')
for i in range(len(a)-1,-1,-1):
print(a[i], end=' ')
print('\n')
for i in a[::-1]:
print(i, end=' ')
print('\n')
for i in reversed(a):
print(i, end=' ')
6. What will be the output of following code?
>>>a = [[[4,5],[1,0],9],[6,7]]
>>>a[0][1][1]
7. What does each of the following expressions evaluates to ?
Suppose that L is the list
[‘These’,[‘are’,’a’,’few’,’words’],’that’,’we’,’will’,’use’]
(a) L[1][3][1:]
(b) L[2][1].upper()
8. Predict an output:
Odd=[3,4,5]
print((Odd+[12,13,14])[3])
print((Odd+[78,89,90])[4] – (Odd+[2,4,6])[4])
9. Predict an output of the following:
my_list=[‘c’,’l’,’a’,’s’,’s’,’i’,’c’]
my_list[2:3]=[]
print(my_list)
my_list[2:5]=[]
print(my_list)

Assignment 4
Tuples

Tuple Initialization:
1. Write a Python code snippet to create a tuple named months containing the names of
the months in a year.
2. Create a tuple named countries containing the names of five different countries.

Tuple Concatenation:
3. Concatenate two tuples tuple_a = (1, 2, 3) and tuple_b = (4, 5, 6) and print the result.
4. Concatenate two tuples tuple_x = (10, 20, 30) and tuple_y = (40, 50, 60) and store the
result in a new tuple.

Tuple Repetition:
5. Create a tuple named repeat_tuple that repeats the values (7, 8, 9) three times.
6. Create a tuple named repeat_tuple that repeats the values (3, 6, 9) four times.

Membership Test:
7. Check if the value 5 is present in the tuple test_tuple = (2, 4, 6, 8, 10) and print the
result.
8. Check if the value 15 is present in the tuple test_values = (10, 15, 20, 25, 30) and print
the result.

Tuple Slicing:
9. Given the tuple numbers = (1, 2, 3, 4, 5), print a new tuple containing the elements
from index 1 to 3.
10. Given the tuple letters = ('a', 'b', 'c', 'd', 'e'), print a new tuple containing elements from
index 2 to the end.
11. Given the tuple numbers = (11, 22, 34, 45, 56), print a new tuple containing elements
from index 2 to 3.

Built-in Functions and Operations


12. Calculate and print the sum of elements in the tuple values = (10, 15, 20, 25, 30).
13. Count the occurrences of the value 3 in the tuple count_tuple = (1, 3, 5, 3, 7, 3, 9).
14. Count the occurrences of the value 'apple' in the tuple fruit_tuple = ('apple', 'orange',
'apple', 'banana', 'apple').
15. Find and print the length of the tuple fruits = ("apple", "banana", "orange", "grape").
16. Find and print the length of the tuple words = ('apple', 'banana', 'cherry', 'date').
17. Create a tuple measurements = (4.5, 6.3, 2.8, 5.1). Print the sum of the elements in the
tuple.
18. Given the tuple animals = ("lion", "tiger", "elephant", "lion", "zebra"), find the count
of
occurrences of the element "lion."
Nested Tuple Operations:
19. Create a nested tuple nested = ((1, 2, 3), (4, 5, 6), (7, 8, 9)) and find the sum of the
elements in the second tuple.
20. Create a nested tuple nested_values = ((1, 2, 3), (4, 5, 6), (7, 8, 9)) and find the
product of the elements in the second tuple.
Tuple Assignment:
21. Swap the values of two variables x and y using tuple assignment without using a
temporary variable.
22. Swap the values of two variables a = 5 and b = 8 using tuple assignment without
using a temporary variable.
23. Consider the tuple coordinates = (3, 7, 9). Perform tuple unpacking and assign the
values to variables x, y, and z. Print the sum of these variables.
24. Create a nested tuple matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9)). Access the element 5 and
print it.

Tuple Indexing:
25. Find and print the third element of the tuple colors = ("red", "green", "blue",
"yellow").
26. Access the second element of the tuple marks = (85, 90, 75, 88, 92) and print its
value.
27. Consider the tuple languages = ("Python", "Java", "C++", "JavaScript"). Write a
Python code snippet to print the third element of the tuple.
28. Given the tuple grades = (85, 90, 78, 92, 88), write a Python code snippet to find the
index of the element 78.
Tuple Operations:
29. Create a tuple tuple_a = (1, 2, 3) and a tuple tuple_b = (4, 5, 6). Perform tuple
multiplication and print the result.
30. Create a tuple tuple_p = (3, 6, 9) and a tuple tuple_q = (2, 5, 8). Perform tuple
concatenation and print the result.
31. Create two tuples tuple_a = (1, 2, 3) and tuple_b = (4, 5, 6). Concatenate these tuples
and print the result.
32. Write a Python code snippet to repeat the elements of the tuple numbers = (2, 4, 6)
three times

Tuple Mean Calculation:


33. Calculate and print the mean of values in the tuple data = (12, 18, 24, 30, 36).
34. Calculate and print the mean of values in the tuple numbers = (15, 20, 25, 30, 35).
Tuple Search and Sorting
35. Given a tuple of names name_tuple = ("Alice", "Bob", "Charlie", "David"), perform a
linear search to check if "Charlie" is present and print the result.
36. Given a tuple of names name_list = ('Alice', 'Bob', 'Charlie', 'David'), perform a linear
search to check if 'Bob' is present and print the result.
37. Write a Python program to find the minimum value from the tuple numbers = (18, 12,
24, 9, 15).
38. Sort the tuple unsorted_tuple = (9, 4, 6, 1, 7, 3) in ascending order and print the result.
39. Sort the tuple unsorted_values = (50, 30, 10, 40, 20) in descending order and print the
result.
40. Given the tuple colors = ("red", "blue", "green", "red", "yellow"), count the frequency
of the element "red" and print the result.
Assignment 5
Dictionary

Dictionaries Assignment-2
1. Given below are two lists: convert them into a dictionary
keys = ['A', 'E', 'I', ‘O’, ‘U’]
values = [“Vowels”]
2. Merge following two Python dictionaries into one
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Forty': 40, 'Fifty': 50}
3. Given below is a dictionary, marks.
Marks = { 'Physics': 82, 'Math': 65, 'history': 75 ‘CS’:99 }
Find the subject with minimum and maximum marks.
4. WAP to implement library usning a dictionary. The library has the following
fields: Bookno, Author, Title, Noofcopies
The progrm should do the following:
• Add a book
• Delete a given book
• Search for the book in the library
• Give the number of copies of each book
5. Given a Python dictionary, Salesman, change Kiranpreet’s salary to 60000
Salesmant = { 'SNO1': {'name': 'Dheeraj', 'salary':65000},
'SNO2': {'name': 'Meenakshi', 'salary': 80000},
'SNO3': {'name': 'Kiranpreet', 'salary': 45000},
‘SNO4:{‘name’:’Pritika’, ‘salary’ : 67000}
}
6. WAP to merge two dictionaries classxic and classxid to form a new dictionary,
XICS. Also count the total number of students in the new class.
The fields in the dictionaries are:
Rollno, name,class, marks
7. Given a dictionary employee having fields empno and salary. Arrange the
records in ascending order of salary.

Assignment 6

Functions

Q 1. Rewrite the following code after removing error. Underline each correction done
by you.
def SI(p,t=2,r):
return (p*r*t)/100
def chksum :
x = input ( “Enter a number”)
if (x % 2 = 0) :
for i range ( 2 * x ):
print (i)
loop else:
print ( “#”)
def Tot(Number) #Method to find Total
Sum=0
for C in Range (l, Number+l):
Sum+=C
RETURN Sum
print Tot[3] #Function Calls
print Tot[6]

Q 2. Define functions. Why there is a need to use a function in a program.

Q 3. Differentiate between the following with the help of an example:


(a) Actual and Formal Parameters
(b) Local and Global Variables
(c) Positional and Default arguments

Q 4. Write the type of tokens from the following :


If roll_no Else int

Q 5. Name the Python Library modules which need to be imported to invoke the following functions:
(i) sin( ) (ii) randint ( ) (iii) uniform( ) (iv) ceil( )

Q 6. Find and write the output of the following:


a=10
def call():
global a
a=15
b=20
print(a)
call()
Q 7. How can you access a global variable inside the function, if function has a variable
with same name?

Q 8. Write the output of the following code:


(a) x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)

(b) x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
(c) def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)

Q 9. Find the output of the following:


def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)

Q 10. Find the output of the following:


def Position(C1, C2, C3):
C1[0] = C1[0] + 2
C2 = C2 + 1
C3 = "python"
P1 = [20]
P2 = 4
P3 = "school"
Position(P1, P2, P3);
print(P1, ", ", P2, ", ", P3)

Assignment -7

Files

1. Give one difference between Text file and Binary File


2. Write a Python statement to open a text file “DATA.TXT” so that new contents can be
written on it.
3. Write a Python statement to open a text file “DATA.TXT” so that new content can be
added to the end of file
4. Write a Python statement to open a text file “DATA.TXT” so that existing contents can
be read from file.
5. A file “MYDATA.TXT” is opened as
file1 = open(“MYDATA.TXT”)
Write a Python statement to close this file.
6. What is the different in file opening mode “a” and “w” ?
7. What is the significance of adding „+‟ with file opening mode, with context to „r+‟ ?
8. What is the difference between readline() and readlines() ?
9. What is the purpose of using flush() in file handling operations ?
10. What is the advantage of opening file using „with‟ keyword?
11. Considering the content stored in file “CORONA.TXT”
O Corona O Corona Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
Online padhai karona
Write the output of following statements – f = open("CORONA.TXT")
sr1 = # to read first line of file
str2 = # to read next line of file
str3 = # to read remaining lines of file
12. Considering the content stored in file “CORONA.TXT”
O Corona O Corona
Jaldi se tum Go na
Social Distancing ka palan karona
sabse 1 meter ki duri rakhona
Lockdown me ghar me ho to
Online padhai karona
Complete the missing statement using „for‟ loop to print all the lines of
file
f = open(“CORONA.TXT”)
for :
print( )
13. Considering the content stored in file “WORLDCUP.TXT”, write the
output
India won the Cricket world cup of 1983
f = open(“WORLDCUP.TXT”)
print(f.read(2))
print(f.read(2))
print(f.read(4))
14. Write a function COUNT() in Python to read contents from file
“REPEATED.TXT”, tocount and display the occurrence of the word “Catholic”
or “mother”.
For example:
If the content of the file is “Nory was a Catholic because her mother was a
Catholic , andNory‟s mother was a Catholic because her father was a
Catholic , and her father was a Catholic because his mother was a Catholic ,
or had been
The function should display:
Count of Catholic, mother is 9
15 Write a python function ATOEDISP() for each requirement in Python to
read the file“NEWS.TXT” and
(I) Display “E” in place of all the occurrence of “A” in the word COMPUTER.
(II) Display “E” in place of all the occurrence of “A”:
I SELL COMPUTARS. I HAVE A COMPUTAR. I NEED A COMPUTAR. I WANT A
COMPUTAR. I USE THAT COMPUTAR. MY COMPUTAR CRASHED.
The function should display
(I) I SELL COMPUTERS. I HAVE A COMPUTER. I NEED A COMPUTER. I
WANT ACOMPUTER. I USE THAT COMPTUER. MY COMPUTER
CRASHED.
I SELL COMPUTERS. I HEVE E COMPUTER. I NEED E COMPUTER. I WENT E
COMPUTER. I USE THET COMPTUER. MY COMPUTER CRESHED.

Assignment 8
BINARY FILE HANDLING & CSV

1. Letter is prefixed to store string in binary form


2. Write a Python statement to open a text file “DATA.TXT” in binary mode so
thatnew contents can be written on it.
3. Consider a binary file which stores Name of employee, where each
name occupies 20 bytes (length of each name) in file irrespective of
actual characters. Now you have to write code to access the first name,
5th name and last name.

f = open("Emp.txt","rb")
s= #code to get first record
print(s.decode())
# code to position at 5th
record
s = f.read(size)
print(s.decode())

# code toposition at last record


s = f.read(20)
print(s.decode())
f.close()

4. Write a function RECCOUNT() to read the content of binary file


„NAMES.DAT‟ and display number of records ( each name occupies 20
bytes in file ) in it.
For. e.g. if the content of file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK
HARI SHANKER
Function should display
Total Records are 6
5. From the given path identify the type of each:
C:\mydata\web\resources\img.jpg
..\web\data.conf
6. Consider the following Binary file „Emp.txt‟, Write a function RECSHOW() to display only those
records who are earning more than 7000

7. CSV stands for ?


8. Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200

Write Python function DISPEMP() to read the content of file emp.csv and display only those
records where salary is 4000 or above
9. Write a python function CSVCOPY() to take sourcefile, targetfile as parameter and create a
targetfile and copy the contents of sourcefile to targetfile
10. Diffrentiate between reader and writer?
11. Differntiate between Seekg and tellg
Assignment 9
RDBMS

1 Which clause is used to search for NULL values in any column?


2 RDBMS stands for:

3 Rajesh a database developer at Store India wants to search the record of those employees
whose name starts from „R‟ and they have not allotted any project, for this he has
written the following query-
Select * from Employee where Name = ‘R%’ and Project=Null;
But the query is not producing the correct output. Rewrite the query after correcting
the errors

4 Which clause is used to see the output of query in ascending or descending order?

5 What is the difference between Primary Key and Candidate Key?

6 Explain count () and count (*)?

7. Raj is a database programmer, He has to write the query from EMPLOYEE table to search for the
employee whose name begins from letter „R‟, for this he has written the query as:
SELECT * FROM EMPLOYEE WHERE NAME=‟R%‟;
But the query is not producing the correct output, help Raj and correct the query so that he gets the
desired output.

8. Raj is a database programmer, has to write the query from EMPLOYEE table to search for the
employee who are working in „Sales‟ or „IT‟ department, for this he has written the query as:
SELECT * FROM EMPLOYEE WHERE department=‟Sales‟ or „IT‟;
But the query is not producing the correct output, help Raj and correct the query so that he gets
the desired output.

9. If Table Sales contains 5 records and Raj executed the following queries; find out the output of
both the query.
(i) Select 100+200 from dual;
(ii) Select 100+200 from Sales;
10. What is the difference between Equi-Join and Natural Join?
11. What is the difference between CHAR and VARCHAR?
12. Which SQL function is used to get the average value of any column?
13. What is the Difference between ALTER Table command and UPDATE command?
14. Write MYSQL command to see the list of tables in current database
15. A table Employee contains 5 Rows and 4 Columns and another table PROJECT contains
5 Rows and 3 Columns. How many rows and columns will be there if we obtain
Cartesian product of these two tables?
16. DIFFERENCE BETWEEN
1. HAVING AND WHERE
2. % AND _
Assignment10
SQL

1. Observe the given Table TEACHER and give the output of question (i) and (ii)

TEACHER_CODE TEACHER_NAME DOJ


T001 ANAND 2001-01-30
T002 AMIT 2007-09-05
T003 ANKIT 2007-09-20
T004 BALBIR 2010-02-15
T005 JASBIR 2011-01-20
T006 KULBIR 2008-07-11

(i) SELECT TEACHER_NAME,DOJ FROM TEACHER WHERE TEACHER_NAME LIKE


„%I%‟
ii. SELECT * FROM TEACHER WHERE DOJ LIKE „%-09-%‟;

2. Suppose a table BOOK contain columns (BNO, BNAME, AUTHOR, PUBLISHER),


Raj is assigned a task to see the list of publishers, when he executed the query
as:
SELECT PUBLISHER FROM BOOK;
He noticed that the same publisher name is repeated in query output. What could be
possible solution to get publisher name uniquely? Rewrite the following query to fetch
unique publisher names from table.

3. What will be the output of the following-


a. Select Round(1449.58,-2);
b. Select Round(7.5789,3); IP ONLY
c. Select Substr(“ Hello Rahul”,3,8);
d. Select Dayofmonth(“2020-10-24”);

4. Rajesh a database developer at StoreIndia wants to search the record of those employees whose
name starts from „R‟ and they have not allotted any project, for this he has written the following
query-
Select * from Employee where Name = ‘R%’ and Project=Null;
But the query is not producing the correct output. Rewrite the query after correcting the errors
(i) To display details of all Trains which starts from New Delhi
(ii) To display PNR, PNAME, GENDER and AGE of all passengers whose AGE is below 50

(iii) To display total numbers of MALE and FEMALE passengers

(iv) To display records of all passengers travelling in trains whose TNO is 12015

(v) SELECT MAX(TRAVELDATE),MIN(TRAVELDATE) FROM PASSENGERS WHERE


GENDER=‟FEMALE‟;

(vi) SELECT END, COUNT(*) FROM TRAINS GROUP BY END HAVING COUNT(*)>1;

(vii) SELECT DISTINCT TRAVELDATE FROM PASSENGERS;

(viii) SELECT TNAME, PNAME FROM TRAINS T, PASSENGERS P WHERE T.TNO=P.TNO AND AGE
BETWEEN 50 AND 60

1. Which of the following commands will remove the entire database from
MYSQL?
(A) DELETE (B) DROP (C) REMOVE (D) ALTER
2. __________ is a non-key attribute, whose values are derived from the
primary key of some other table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
3.The SELECT statement when combined with clause, returns
records withoutrepetition.
(A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULL
4. Which of the following commands will delete the rows of table?
(a) DELETE (b) DROP (c) REMOVE (d) ALTER
5. Logical Operators used in SQL are?
(a) AND,OR,NOT (b) &&,||,! (c) $,|,! (d) None of these
6. Which of the following ignores the NULL values inSQL?
a)Count(*) b) count() c)total(*) d)None of these

7. The SQL built-in function calculates the average of values in


numeric columns.
(a) MEAN() (b)AVG() (c) AVERAGE() (d) COUNT()
8.Which of the following commands will be used to select a particulardatabase
named “Student” from MYSQL Database?
(a)SELECT Student; (b)DESCRIBE Student;(c)USE Student; (d) CONNECT
Student;
9.An attribute in a relation is a foreign key if it is the key inany
other relation.
(a) Candidate Key
(b) Foreign Key
(c) Primary Key
(d) Unique Key
10. When two conditions must both be true for the rows to be selected, the
conditions are separated by the SQL keyword
(a)ALL (b)IN (c)AND (d)OR
11. Which statement in SQL allows to change the definition of a table is
(a) Alter (b) Update. (c) Create (d) select
12. Which of the following is not part of a DDL query?
a) DROP
b) MODIFY
c) DISTINCT
d) ADD
13. Which of the following statements is True?
a) There can be only one Foreign Key in a table.
b) There can be only one Unique key is a table
c) There can be only one Primary Key in a Table
d) A table must have a Primary Key.
14. __________ Keyword is used to obtain unique values in a SELECT query
a) UNIQUE
b) DISTINCT
c) SET
d) HAVING
15. Which statement in MySql will display all the tables in a database?
a) SELECT * FROM TABLES;
b) USE TABLES;
c) DESCRIBE TABLES;
d) SHOW TABLES;
16. Which of the following is a valid sql statement?
a) ALTER TABLE student SET rollno INT(5);
b) UPDATE TABLE student MODIFY age = age + 10;
c) DROP FROM TABLE student;
d) DELETE FROM student;
17. _______command is used to ADD a column in a table in SQL.
(a) update (b)remove (c) alter (d)drop
18. Which of the following is a DML command?
(a) CREATE (b) ALTER (c) INSERT (d) DROP
18. ______is a non-key attribute, whose values are derived from the
primary key ofsome other table.
(a) Foreign Key
(b) Primary Key
(c) Candidate Key
(d) Alternate Key
19. Which SQL keyword is used to retrieve only unique values?
(a) DISTINCTIVE (b) UNIQUE (c) DISTINCT (d) DIFFEREN
2 MARKS Questions:

1. Explain the use of ‘Primary Key’ in a Relational Database Management


System. Give example to support your answer.
2. Differentiate between count(column_name) and count(*) functions in SQL
withappropriate example.
3. Categorize the following commands as DDL or DML:SELECT, UPDATE, ALTER,
DROP
4. Explain the use of ‘Foreign Key’ in a Relational Database Management System.
Give example to support your answer.

5. Differentiate between order by and group by clause in SQL with


appropriate example.

6. Differentiate between DDL and DML with one Example each.

7. Categorize the following commands as DDL or DML:


INSERT, UPDATE, ALTER, DROP
8. Mention two differences between a PRIMARY KEY and a UNIQUE KEY.
9. What is the difference between a Candidate Key and an Alternate Key

3 and 5 MARKS Questions:

1. Write the output of the queries (i) to (vi) based on the table given below

TABLE:
CHIPS
BRAND_NAME FLAVOUR PRICE QUNATIT
Y
LAYS ONION 10 5
LAYS TOMATO 20 12
UNCLE CHIPS SPICY 12 10
UNCLE CHIPS PUDINA 10 12
HALDIRAM SALTY 10 20
HALDIRAM TOMATO 25 30

(i) Select BRAND_NAME, FLAVOUR from CHIPS where PRICE <> 10;
(ii) Select * from CHIPS where FLAVOUR=”TOMATO” and PRICE > 20;
(iii) Select BRAND_NAME from CHIPS where price > 15 and QUANTITY < 15;
(iv) Select count( distinct (BRAND_NAME)) from CHIPS;
(v) Select price , price *1.5 from CHIPS where FLAVOUR = “PUDINA”;
(vi) Select distinct (BRAND_NAME) from CHIPS order by BRAND_NAME desc;
2. Consider the following tables BOOKS and ISSUED in a database named “LIBRARY”.
WriteSQL commands for the statements (i) to (iv).
Table:BOOKS

BID BNAME AUNAME PRICE TYPE QTY


COMP11 LET US C YASHWANT 350 COMPUTER 15
GEOG33 INDIA MAP RANJEET P 150 GEOGRAPHY 20
HIST66 HISTORY R BALA 210 HISTORY 25
COMP12 MY FIRST C VINOD DUA 330 COMPUTER 18
LITR88 MY DREAMS ARVIND AD 470 NOBEL 24
Table: ISSUED
BID QTY_ISSUED
HIST66 10
COMP11 5
LITR88 15

(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have been
issued.

3. Write the command to view all tables in a database.


Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation
of thetable, she has entered data of 8 items in the table.
Table : STOCK
stocki dopurchas name make Price
d e
101 2020-07- CPU ACER 12000
06
102 2020-09- CPU ACER 12750
01
103 2020-09- MONITOR ACER 7500
01
104 2016-08- PROJECTOR GLOBUS 37250
03
105 2016-05- VISUALIZER GLOBUS 17500
26
106 2020-07- WIFI RECEIVER ZEBION 450
23
107 2015-02- PRINTER LEXMARK 38000
18
108 2020-07- HEADPHONE BOAT 750
23
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 three columns are added and 5 rows are deleted from the table stock,
what will bethe new degree and cardinality of the above table?
(iii) Write the statements to:
(a) Insert the following record into the table
Stockid - 201, dateofpurchase – 18-OCT-2022, name – neckphone
Make – BoAT, price - 500
(iii) Decrease the price of stock by 5% whose were purchased in year 2020OR
Write the statements to:
(a) Delete the record of stock which were purchased before year 2015.
(b) Add a column STATUS in the table with datatype as char with 1 characters
4. Consider the following tables Emp and Dept:
Dept:
empcode ename deptid Salary
1001 TOM 10 10000
1002 BOB 11 8000
1003 SID 10 9000
1004 JAY 12 9000
1005 JIM 11 10000
deptid dname
10 Physics
What will be the output of the following
statement? 11 Chemistry
SELECT * FROM Emp NATURAL JOIN Dept WHERE
12 Biology
dname='Physics'
5. Write output of the queries (i) to (iv) based on the table Sportsclub
Table Name: Sportsclub
playerid pname sports country rating salary

10001 PELE SOCCER BRAZIL A 50000

10002 FEDERER TENNIS SWEDEN A 20000

10003 VIRAT CRICKET INDIA A 15000

10004 SANIA TENNIS INDIA B 5000

10005 NEERAJ ATHLETICS INDIA A 12000

10006 BOLT ATHLETICS JAMAICA A 8000

10007 PAUL SNOOKER USA B 10000

(i) SELECT DISTINCT sports FROM Sportsclub;


(ii) SELECT sports, MAX(salary) FROM Sportsclub GROUP BY sports
HAVING sports<>'SNOOKER';
(iii) SELECT pname, sports, salary FROM Sportsclub WHERE
country='INDIA' ORDER BY salary DESC;
(iv) SELECT SUM(salary) FROM Sportsclub WHERE rating='B';

6. Based on the given set of tables write answers to the following questions.
Table: flights
flightid model company
10 747 Boeing
12 320 Airbus
15 767 Boeing
Table: Booking
ticketno passenger source destination quantity price Flightid
10001 ARUN BAN DEL 2 7000 10
10002 ORAM BAN KOL 3 7500 12
10003 SUMITA DEL MUM 1 6000 15
10004 ALI MUM KOL 2 5600 12
10005 GAGAN MUM DEL 4 5000 10
a) Write a query to display the passenger, source, model and price for all
bookings whose destination is KOL.
b) Identify the column acting as foreign key and the table name where it
is present in the given example.

Productid pname company stock price rating

10001 Biscuit Parley 1000 15 C

10002 Toffee Parley 500 5 B

10003 Eclairs Cadbury 800 10 A

10004 Cold Drink Coca Cola 500 25 NULL

1005 Biscuit Britania 500 30 NULL

1006 Chocolate Cadbury 700 50 C


7. Based on the above table answer the following questions.

a) Identify the primary key in the table with valid justification.


b) What is the degree and cardinality of the given table.
c) Write a query to increase the stock for all products whose company is
Parley

Write a query to delete all the rows from the table which are not
having any rating.

8. Write the output of the queries (a) to (d) based on the table

(a) SELECT min(Population) FROM country;


(b) SELECT max(SurfaceArea) FROM country Where Lifeexpectancy <50;
(c) SELECT avg(LifeExpectancy) FROM country Where CName Like "%G%";
(d) SELECT Count(Distinct Continent) FROM country;
(a) Identify the candidate key(s) from the table Country.
(b) Consider the table CAPITAL given below:

Which field will be considered as the foreign key if the tablesCOUNTRY and CAPITAL are related in
a database?
9.Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and
Posting given below:
Table: Stationary
S_ID StationaryName Company Price
DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15

C_ID ConsumerName Address S_ID


1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02

1. SELECT count(DISTINCT Address) FROM Consumer;


2. SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Stationary
GROUP BY Company;
3. SELECT Consumer.ConsumerName, Stationary.StationaryName, Stationary.Price FROM
Stationary,Consumer WHERE Consumer.S_ID = Stationary.S_ID;

10. Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and
ADMIN givenbelow:
i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE
DESIGNATION = ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;

11.Write SQL commands for the following queries (i) to (v) based on the relation

Trainer and Course given below:


(i) Display the Trainer Name, City & Salary in descending order oftheir Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institutein the month of
December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE fromtables TRAINER and COURSE of
all those courses whose FEESis less than or equal to 10000.
(iv) To display number of Trainers from each city.
(iv) To display the Trainer ID and Name of the trainer who are not
belongs to ‘Mumbai’ and ‘DELHI’
12.Write the output of the queries (i) to (iv) based on the table, TABLE: EMPLOYEE
TABLE: EMPLOYEE
EMPNO NAME DATE_OF_ JOINING SALARY CITY
5001 SUMIT SINGH 2012-05-24 55000 JAIPUR
5002 ASHOK SHARMA 2015-10-25 65000 DELHI
5003 VIJAY SINGH 2009-09-09 85000 JAIPUR
5004 RAKESH VERMA 2020-12-21 60000 AGRA
5006 RAMESH KUMAR 2011-01-22 72000 DELHI

(i) SELECT AVG(SALARY) FROM EMPLOYEE WHERE CITY LIKE ‘%R’;


(ii) SELECT COUNT(*) FROM EMPLOYEE
WHERE DATE_OF_JOINING BETWEEN ‘2011-01-01’ AND ‘2020-12-21’;
(iii) SELECT DISTINCT CITY FROM EMPLOYEE WHERE SALARY >65000;
(iv) SELECT CITY, SUM(SALARY) FROM EMPLOYEE GROUP BY CITY;

13.Consider the following tables ACTIVITY and COACH.


Write SQL commands for the statements (i) to (iv) and give the The outputs for the
SQLqueries (v) to (viii) –
Table: ACTIVITY
ACode ActivityName ParticipantsNum PrizeMoney ScheduleDate
1001 Relay 100X4 16 10000 23-Jan-2004
1002 High Jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004
1005 Long Jump 12 9000 01-Jan-2004
1008 Discuss Throw 10 15000 19-Mar-2004
Table : Coach
PCode Name ACode
1 Ahmed Hussain 1001
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003
(i) To display the name of all activities with their Acodes in descending order.
(ii) To display sum of prizemoney for each of the number of participants groupings
(asshown in column ParticipantsNum 10,12,16)
(iii) To display the coach’s name and ACodes in ascending order of ACode from the
tableCOACH.
(iv) To display the content of the Activity table whose ScheduleDate is earlier
than01/01/2004 in ascending order of ParticipantsNum.
b) Write the command to view all tables in a database.

You might also like