You are on page 1of 16

MY SQL

SIMPLE SELECT :-
1. Select * from worker;
2. Select salary , region , grade from worker;
3. Select *, salary-2000 as salary from worker;
4. Select *, salary*12 as “annual salaries” from worker;
USING WHERE CLAUSE :-
5. Select * from worker where age < 28;
6. Select name from worker where region = ‘north’;
7. Select salary from worker where wshop=610;
USING NULL :-
8. Select * from worker where grade is null;
9. Select * from worker where grade is not null;
USING DISTINCT CLAUSE :-
10. Select distinct(name) from worker;
11. Select distinct(wshop) from worker;
USING (NOT,AND,OR) :-
12. Select * from worker where age>30 and wshop =610;
13. Select * from worker where wshop=230 and salary > 35000;
14. Select name, salary from worker where not(wshop=506);
15. Select name, salary from worker where not(region=‘west’ or
region=’centre’);
16. Select name from worker where wshop=610 or wshop=506;
17. Select * from worker where salary > 32000 and salary < 38000;
18. Select * from worker where grade > ‘A’ and grade < ‘C’;
19.Select * from worker where age> 30 and region =’west’;
USING IN :-
20. Select name from worker where wshop in(230,610);
21. Select name, salary from worker where region not in('west','centre');
USING BETWEEN :-
22. Select * from worker where salary between 32000 and 38000 ;
23. Select * from worker where age between 29 and 32 ;
USING LIKE :-
24. Select name, salary, age from worker where name like 'n%' ;
25. Select name, salary, age from worker where name like '%a' ;
26. Select name, salary, age from worker where name like '%k%' ;
27. Select * from worker where name not like '%a%';
28. Select * from worker where name like '_a%';
USING FUNCTIONS AND AGGREGATE FUNCTION :-
29.
30. Select max(salary) from worker;
31.
32. Select count(wno),sum(salary) from worker;
33. Select avg(salary),max(salary),min(salary) from worker;
34. Select max(salary)-min(salary) from worker;
USING GROUP BY AND HAVING CLAUSE :-
35.
36.
37.
38.
USING ORDER BY CLAUSE :-
39. Select * from worker order by salary;
40. Select * from worker order by name desc;
41. Select * from worker order by grade, salary desc;
USING UPDATE,DELETE,ALTER TABLE :-
42. Update worker set grade=’B’ where grade=’’;
43.
44. Delete from worker where grade=’C’ and salary < 30000;
45. Delete from worker where wshop=610 and age > 27;
46. Alter table workshop add(hiredate date);
Join of two tables
47.
48.
49.
50.
Python
Q 1. CSV= ADD()/ACCEPT() OR WON_COUNT()/SEARCH(). 5m
import csv
def accept():
f=open("result.csv",'a',newline='')
header=["st_id","st_name","game_name","result"]
std= int(input("enter student id"))
sname=input("enter student id")
game=input("enter game name")
result=input("enter result")
row=[std,sname,game,result]
csvwr=csv.writer(f)
csvwr.writerow(header)
csvwr.writerow(row)
f.close()
def won_count():
f=open("result.csv",'r')
csvrd=csv.reader(f,delimeter=',')
data=list(csv.rd)
c=0
for x in data:
if x[3]=="won":
c+=1
print(c)
f.close()
Q2. Line started with any word. 3m
def count_lines():
f=open("story.txt",'r')
w=f.readline()
c=0
for i in w:
if i[0]=='T':
c+=1
print('total line start with T',c)
f.close()
Q3. Cust_data() to ask user to enter their names and age to store data in
customer.dat file. 2m
import pickle as pk
def cust_data():
record={}
f=open("customer.dat",'bw')
while True:
record[n]=input("enter a name:")
record[a]=int(input("enter age:"))
pk.dump(record,f)
choice=input("wish to enter more record Y/N ?-")
if choice.upper()=='N':
break
print("records added to the file")
f.close()
Q4. Count() that will read the contents of text file named “report.txt” and
count the number of lines which starts with either “I” or “M”. 3m
def count():
f=open("report.txt",'r')
wr=f.readline()
c=0
for i in wr:
if i[0]=="I" or i[0]=="M":
c+=1
print("there are",c,"lines starting with 'I' or 'M'")
f.close()
Q5. Ending with any last word in line to count (txt). 2m
def count_lines():
f=open("story.txt",'r')
w=f.readline()
c=0
for i in w:
if i[-1]=='r':
c+=1
print('total lines ending with r:',c)
Q6. A binary file “student.dat” has structure
(admission_number,name,percentage) . Write a function countrec() in python
that would read contents of the file”student.dat” and display the details of
those students whose percentage is above 75.also display number of
students scoring above 75%.4m
import pickle as pk
def countrec():
f=open("student.dat",'rb')
n=0
try:
while True:
rec=pk.load(f)
if rec[2]>75:
print(rec[0],rec[1],rec[2],sep="\t")
n+=1
except:
f.close()
return n
Q7. Count ending with words.(txt). 2m
def displaywords():
f=open("story.txt",'r')
t=f.read()
w=t.split()
c=0
for i in w:
if i[-1]==’n’:
c+=1
print(c)
f.close()
Q8) What is the difference between switch and router?
ANS. Switch Router
1 it works on the same network type It works on network of a different type.
2 They are found in the same LAN They connect LANs and there can be
where there is a single path from multiple paths from source to destination
source to destination
Q9) What is the difference between a Hub and Switch?
ANS Hub Switch
1 It broadcast signals to all the devices it sends signals to only selected devices
connected instead of sending to all
2 It is not an intelligent device it is an intelligent device.
3 Hub is simply old type of device and switch is very sophisticated device and
is not generally used. widely used.

Q10. Word with ing in text file. 3m


def count_ing():
f=open("quotes.txt",'r')
w=f.read()
t=w.split()
for i in t:
if 'ing' in i:
print(i)
f.close()
Q11. 3 words length. 3m
def three_char_words():
f=open("data.txt",'r')
txt=f.read()
w=txt.split()
for i in w:
if len(i)== 3:
print (i)
f.close()
Q12. Replace vowels. 3m
def replace_vowel(st):
str=''
for i in st:
if i in 'aeiouAEIOU':
str+='*'
else:
str+=i
st=str
return st
st='message your token number'
replace_vowel(st)
Q13. Count lines started with W or w and H or h. 3m
def countlines():
f=open("textfile.txt",'r')
wr=f.readlines()
c=0
n=0
for i in wr:
if 'Ww' in i[0]:
c+=1
elif 'Hh' in i[0]:
n+=1
print("W or w:",c,"H or h",n)
f.close()
countlines()
Q14. Write a method in python to read lines from a text file INDIA.TXT to find
and display the occurrence of word “india”. 3m
def display():
c=0
f=open ("india.txt",'r')
for l in f:
w=l.split()
for k in w:
if k=="india":
c+=1
print(c)
f.close()
Q15. Word greater than 3. 2m
def displaywords():
f=open("story.txt",'r')
t=f.read()
w=t.split()
for i in w:
if len(i)>3:
print(i)
f.close()
Q16. Odd and even in list.2m
def odev_list():
m=[]
for i in l:
if i %2:
m+=['odd']
else:
m+=['even']
print (m)
l=[3,4,2,6,5]
odev_list()
Q17. Word greater than 5 words. 2m
def count_len(places):
for i in places:
if len(i)>5:
print(i)
Q18. Read lines one by one.2m
def read_text():
f=open("data.txt",'r')
fw=f.readlines()
for i in fw:
print(i)
f.close()
or
def read_text():
f=open("data.txt",'r')
try:
while true:
l=f.readline()
print(l)
except EOF error:
print("file complete")
f.close()
Q19.Define Degree and Cardinality.
Ans. DEGREE OF A RELATION – The total number of Attributes in a relation is
known as the Degree of the Relation.
CARDINALITY OF A RELATION – The total number of Tuples / Records in a relation
(excluding the Top Row, which contains the Attribute Headers) is known as the
Cardinality of the Relation.
Q20. Capturedata(), that reads contents from the file Movie.DAT and copies
the records with banner as “YashRaj” to the file named Yashrajfilms.DAT. the
function should return the total number of records copied to the file
Yashrajfilms.DAT. 3m
import pickle
def capturedata():
f=open("movie.dat",'br')
f1=open("yashraj.dat",'bw')
data=pickle.load(f)
c=0
for i in data:
if k[1]=="yashraj":
c+=1
pickle.dump(k,f1)
return c
f.close()
f1.close()
capturedata()
Q21. Find Type(mtype),that accepts mtype as parameter and displays all the
records from the binary file CINEMA.DAT,that have the value of Movie Type
as mtype.
import pickle as pk
def findtype(mtype):
record={}
f=open("cinema.dat","bw")
while True:
record['Mn']=int(input("enter movie number::"))
record['nm']=input("enter movie name::")
record['mT']=input("enter movie type::")
pk.dump(record,f)
choice=input("wish to enter more records Y/N ?-")
if choice.upper()=='N':
break
print("records added to the file")
f.close()
Q22. Palindrome.3m
def STR_PALIN(str):
y= str.lower()
if y==y[::-1]:
print ('the given string',str,'is a palindrome')
else:
print('the given string',str,'is not palindrome')
str='naman'
STR_PALIN(str)
Q23.push_in(l),where l is a list of number . from this list, push all numbers
which are multiple of 3 into a stack which is implemented by using another
list. Or Push(kitem),where kitem is a dictionary containing the details of
kitchen items-{item:price}.
y=[]
def push_in(l):
for i in l:
if i%3==0:
y.append(i)
return y
or
y=[]
def push(kitem):
s,c=0,0
for k in kitem:
if kitem[k] < 100:
y.append(k)
s=s+kitem[k]
c+=1
print("the average price of items:",sum(c))
y=[]
def pop():
while y!=[]:
print(y.pop())
else:
print('the stack is empty')
Q24. PUSH(): to push a node into the stack. Pop():to remove a node from
the sack.
d=[]
def push():
pnr=int(input('enter the pass of principle to put n succes:'))
pname=input('enter name of passenger:')
p=[pnr,pname]
d.append(p)
def pop():
if d==[]:
print("the stack is empty,no passenger to pop:")
else:
print("the passanger:",d.pop())
Q25. Write a function in Python PUSH(Arr), where Arr is a list of numbers.
From this list push all numbers divisible by 5 into a stack implemented by
using a list. Display the stack if it has at least one element, otherwise display
appropriate error message.
s=[25,40,27,34 ]
def PUSH(Arr,value):
for x in range(0,len(Arr)):
if(Arr[x]%5--0):
s.append(Arr[x])
if(len(s)==0):
print("Empty stack")
else:
print(s)
Q26.Differentiate between Primary Key and Foreign Key.
Ans. An Attribute or a set of Attributes, which uniquely identifies each tuple in
the Relation is known as Primary Key whereas an Attribute or a Set of
Attributes in one relation which refer to the Primary Key of any other Relation
is known as the Foreign Key of the Relation. They are used to establish
relationships between Tables. There can only be 1 Primary Key however, there
can be multiple Foreign Keys from multiple Tables.
Q27. Write a function in Python POP(Arr), where Arr is a stack implemented
by a list of numbers. The function returns the value deleted from the stack.
st=[2,3,6,8,10]
def popStack(st):
if(len(st)==0):
print('Underflow')
else:
L=len(st)
val=st[L-1]
print(val)
st.pop(L-1)
popStack(st)
Q28. Write functions in python for Push(List) and for PopS(List) for
performing Push and Pop operations with a stack of list containing integers.
List=[1,2,3]
def PushS(List):
N=int(input('Enter Integer'))
List.append(N)
def PopS(List):
if (List==[]):
print('UnderFlow!!')
else:
print('Deleted Value: ',List.pop())
PushS(List)
print(List)
PopS(List)

Q29. Differentiate Pickling and unpickling process.


Ans. Pickiling, is the process of converting the structure (Python object like List,
Dictionary etc.) to a byte stream before writing to the file.
Unpickling refers to the conversion of byte stream to the original structure (Python
objects ).

Q30. Differentiate write() and writelines()


Ans. Write – it takes a string as an argument and writes it to the text file.
Writelines() - This method is used to write multiple strings to a file. We need to
pass an iterable object like lists, tuple, etc. containing strings to the writelines()
method.
Q31. Julie has created a dictionary containing names and marks as key value
pairs of 6students. Write a program, with separate user defined functions to
perform the following operations: -
• Push the keys (name of the student) of the dictionary into a stack, where
the corresponding value (marks) is greater than 75.
• Pop and display the content of the stack.
For example
If the sample content of the dictionary is as follows: R={“OM”:76, “JAI”:45,
“BOB”:89, “ALI”:65, “ANU”:90, “TOM”:82}
The output from the program should be: TOM ANU BOB OM
R={'OM':76, 'JAI':45, 'BOB':89, 'ALI':65, 'ANU':90, 'TOM':82}
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop( )
else:
print('Underflow')
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST,k)
while True:
if ST!=[ ]:
print (POP(ST), end=' ')
else:
break

Q32. Differentiate read() and readlines().


Ans. Read() – it reads the whole content of the file character by character,if no
argument is provided. If argument is provided it reads that many bytes.
Readlines()- Reads all lines and returns them in the form of a List. Every element
of the list is theline of the file.

Q33. Differentiate Seek() and Tell () methods.


Ans. The seek() function is used to set the position of the file cursor,whereas
the tell() function returns the position where the cursor is set to begin
reading.
Q34. Alarm has a list containing 10 integers. You need to help him create a
program with separate user defined functions to perform the following
operations based on this list.
• Traverse the content of the list and push the even numbers into a stack.
• Pop and display the content of the stack.
For Example
If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be: 38 22 98 56 34 12
N=[12,13,34,56,21,79,98,22,35,38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop( )
else:
print('Underflow')
ST=[ ]
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST), end=" ")
else:
break

Q35. Differentiate Text Files and Binary Files.


Ans. Text files are structured as a sequence of lines, where each line includes a
sequence of characters (i.e. stored based on ASCII value). It can be edited in any
text editor program.
Eg.Notepad
A binary file is a file stored in binary format (i.e. combination of one’s and zero's).
Binary filesntypically contain bytes that are intended to be interpreted as
something other than text characters. Binary filesare a computer-readable form
of storing data.
Q36. A list, NList contains following record as list elements:
[City, Country, distance from Delhi] Each of these records are nested together
to form a nested list. Write the following user defined functions in Python to
perform the specified operations on the stack named travel.
• Push_element(NList): It takes the nested list as an argument and pushes a
list object containing name of the city and country, which are not in India and
distance is less than 3500 km from Delhi.
• Pop_element(): It pops the objects from the stack and displays them. Also,
the function should display “Stack Empty” when there are no elements in the
stack.
travel=[]
def Push_element(NList):
for L in NList:
if(L[1] != 'India' and L[2]<3500):
travel.append([L[0],L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print('Stack Empty')
Q37 Difference between Primary key and unique key ?
Parameters PRIMARY KEY UNIQUE KEY
Basic Used to serve as a unique Uniquely determines a
identifier for each row in a row that isn’t the primary
table. key.
NULL value Cannot accept NULL values. Can accept NULL values.
acceptance
Number of keys that Only one primary key
can be defined in the More than one unique key
table

Uses The primary Key is used The Unique Key is used for
for indicating the rows preventing duplicate
uniquely. entries
Q38. What is Difference between DDL and DML?
Ans . The difference between DDL and DML:
DDL DML
It stands for Data Definition Language. It stands for Data Manipulation
Language.
It is used to create database schema It is used to add, retrieve or update
and can be used to define some the data.
constraints as well.
It basically defines the column It add or updates the row of the
(Attributes) of the table. table. These rows are called tuple.
Basic command present in DDL are BASIC command present in DML
CREATE, DROP, RENAME, ALTER etc. are UPDATE, INSERT, MERGE etc.
DDL is used to define the structure of a DML is used to manipulate the data
database. within the
database.

DDL is used to create and modify DML is used to perform operations


database objects like tables, indexes, on the data within those database
views, and constraints. objects.

Q39 Difference between Primary key and unique key?


The following table highlights all the important differences between primary
key and foreign key -
Key Primary Key Foreign Key
Basic It is used to uniquely identify It is used to maintain relationship
data in the table. between tables.
Null It can't be NULL. It can accept the NULL values.
Duplicate Two or more rows can't have It can carry duplicate value for a
same primary key. foreign key attribute.
Tables Primary key constraint can be It can't be defined on temporary
defined on temporary table. table

You might also like