0% found this document useful (0 votes)
6 views40 pages

CS Practical File

The document is a practical file for Computer Science submitted by Kavya Sahai for the session 2025-26. It includes various programming exercises and their explanations, covering topics like even/odd checks, prime numbers, Fibonacci series, and dictionary operations. Each program is accompanied by code, output, and a brief explanation of its functionality.

Uploaded by

kaavje.sah
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)
6 views40 pages

CS Practical File

The document is a practical file for Computer Science submitted by Kavya Sahai for the session 2025-26. It includes various programming exercises and their explanations, covering topics like even/odd checks, prime numbers, Fibonacci series, and dictionary operations. Each program is accompanied by code, output, and a brief explanation of its functionality.

Uploaded by

kaavje.sah
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

RALLI INTERNATIONAL SCHOOL

COMPUTER SCIENCE PRACTICAL FILE


Session 2025-26

Name: Kavya Sahai


Class: XII A1
Submitted to: Bhawna Mahajan Ma’am
CERTIFICATE
This is to certify that Computer Science
practical file has been submitted by the
candidate Kavya Sahai of XII A1 to teacher
in charge Mrs. Bhawna Mahajan of CBSE
Board Examination for the session 2025-26.
It is further certified that this project is the
individual work of the candidate.

__________________ _____________________ ____________________


Teacher’s Signature Principal’s Signature Examiner’s Signature
INDEX
Write a program to input a number and check whether the number is even or odd. ....... 5
Write a program to input the value of a and b and check if a is greater than b. If a is
greater than b then print a²; otherwise print b². ........................................................... 6
Write a program to input three numbers and find the greatest among the three. ............ 7
Write a program to input a number and check whether the number is positive, negative
or neutral................................................................................................................. 8
Write a program to input a number and print its reverse. (Using while loop) .................. 9
Write a program to input a number and check whether the number is prime or not.
(Using while loop) .................................................................................................. 10
Write a program to print the Fibonacci series to n terms. (Using for loop).................... 11
Write a program to print the factors of a number entered by the user. (Using for loop) .. 12
Write a program to input a list and shift even elements of the list to the right and odd
elements to the left. ............................................................................................... 13
Write a program to input a list and remove duplicate elements from the list. .............. 14
Write a program to input a string and display the longest word in the given string ........ 15
Write a program to input a string and check whether it is a palindrome or not. ............ 16
Write a program to read a sentence and then create a dictionary that contains the
frequency of letters and digits in the sentence. Ignore other symbols if any................. 17
Write a program to input your friend’s names and their phone numbers and store them
in a dictionary. Perform various operations (Display, Add, Delete, Modify, Search, Sort).
............................................................................................................................. 18
Write a function that takes two numbers and returns the number that has the minimum
one’s digit. ............................................................................................................. 20
Write a program that generates a series using a function which takes the first and last
values and generates four terms that are equidistant. ............................................... 21
Write a method in Python to read lines from a text file, [Link], to find and display the
occurrence of the word “India”. ............................................................................... 24
CSV File "[Link]". (i) createfile() to input data. (ii) CountRec(Author) to count books by
specific author. ...................................................................................................... 27
WAP to read following details of sports performance (Sport, competitions, prize won) of
your school & store into binary file [Link]. Show records of those sports whose
prize-won is more than 10. ...................................................................................... 29
A binary file [Link] (a pickle file) stores the records of structure as [rollno, Name,
marks].(i) Write a user-defined function Create() to input data for a student record and
add to pickle file. (ii) Write a function Display() in python which prints the records having
marks more than 81. If no matching record is found it displays "No record found". ...... 31
Consider the tables CABHUB and CUSTOMER. Write SQL commands for the following
statements. ........................................................................................................... 33
Consider the table STORE. Write SQL commands for the following statements .......... 35
Consider the table DRESS. Write SQL commands for the following statements. ......... 37
Consider the tables CONSIGNOR and CONSIGNEE. Write SQL commands. .............. 39
Q1: Write a program to input a number and check whether the number is even or odd.

Code:

num = int(input("Enter a number: "))

if num % 2 == 0:

print(f"{num} is an Even number.")

else:

print(f"{num} is an Odd number.")

Output:

Enter a number: 7

7 is an Odd number.

Explanation:

The program takes an integer input. It uses the modulo operator (%) to find the
remainder when divided by 2. If the remainder is 0, the number is even; otherwise, it is
odd.
Q2: Write a program to input the value of a and b and check if a is greater than b. If a is greater
than b then print a²; otherwise print b².

Code:

a = int(input("Enter value for a: "))

b = int(input("Enter value for b: "))

if a > b:

result = a ** 2

print(f"a is greater. The square of a is: {result}")

else:

result = b ** 2

print(f"b is greater or equal. The square of b is: {result}")

Output:

Enter value for a: 5

Enter value for b: 8

b is greater or equal. The square of b


is: 64

Explanation:

The program compares two numbers. If a is strictly larger, it calculates the square
of a (using ** 2); otherwise, it calculates the square of b.
Q3: Write a program to input three numbers and find the greatest among the three.

Code:

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

num3 = int(input("Enter third number: "))

if num1 >= num2 and num1 >= num3:

greatest = num1

elif num2 >= num1 and num2 >= num3:

greatest = num2

else:

greatest = num3

print(f"The greatest number is: {greatest}")

Output:

Enter first number: 10

Enter second number: 45

Enter third number: 32

The greatest number is: 45

Explanation:

This program uses logical and operators to compare one number against the other
two simultaneously to determine which is the largest.
Q4: Write a program to input a number and check whether the number is positive, negative or
neutral

Code:

num = int(input("Enter a number: "))

if num > 0:

print("The number is Positive.")

elif num < 0:

print("The number is Negative.")

else:

print("The number is Neutral (Zero).")

Output:

Enter a number: -5

The number is Negative.

Explanation:

An if-elif-else ladder is used. Numbers greater than 0 are positive, numbers less than 0
are negative, and if neither condition is met, the number is 0 (neutral).
Q5: Write a program to input a number and print its reverse. (Using while loop)

Code:

num = int(input("Enter a number: "))

temp = num

reverse_num = 0

while temp > 0:

digit = temp % 10

reverse_num = (reverse_num * 10) + digit

temp = temp // 10

print(f"Original: {num}")

print(f"Reverse: {reverse_num}")

Output:

Enter a number: 1234

Original: 1234

Reverse: 4321

Explanation:

We use a while loop to extract the last digit of the number using modulo (% 10), add it to
the reversed variable, and then remove the last digit from the original number using
floor division (// 10).
Q6: Write a program to input a number and check whether the number is prime or not. (Using
while loop)

Code:

num = int(input("Enter a number: "))

count = 0

i=1

while i <= num:

if num % i == 0:

count += 1

i += 1

if count == 2:

print(f"{num} is a Prime number.")

else:

print(f"{num} is Not a Prime number.")

Output:

Enter a number: 13

13 is a Prime number.

Explanation:

A prime number has exactly two factors: 1 and itself. The loop counts how many
numbers divide the input exactly. If the total count of factors is 2, it is prime.
Q7: Write a program to print the Fibonacci series to n terms. (Using for loop)

Code:

n = int(input("How many terms? "))

a, b = 0, 1

print("Fibonacci Series:", end=" ")

if n >= 1:

print(a, end=" ")

if n >= 2:

print(b, end=" ")

for i in range(2, n):

next_term = a + b

print(next_term, end=" ")

a=b

b = next_term

Output:

How many terms? 7

Fibonacci Series: 0 1 1 2 3 5 8

Explanation:

The Fibonacci sequence starts with 0 and 1. Every subsequent number is the sum of the
previous two. The loop calculates the sum, prints it, and updates the variables for the
next iteration.
Q8: Write a program to print the factors of a number entered by the user. (Using for loop)

Code:

num = int(input("Enter a number: "))

print(f"Factors of {num} are:")

for i in range(1, num + 1):

if num % i == 0:

print(i, end=" ")

Output:

Enter a number: 12

Factors of 12 are:

1 2 3 4 6 12

Explanation:

The loop runs from 1 up to the number itself. If the number is divisible by the loop
counter i (remainder is 0), then i is a factor and is printed.
Q9: Write a program to input a list and shift even elements of the list to the right and odd
elements to the left.

Code:

input_string = input("Enter numbers separated by space: ")

num_list = [int(x) for x in input_string.split()]

odds = []

evens = []

for num in num_list:

if num % 2 == 0:

[Link](num)

else:

[Link](num)

new_list = odds + evens

print("Arranged List:", new_list)

Output:

Enter numbers separated by


space: 10 3 5 8 2 7

Explanation:

The program iterates through the list and separates numbers into two new lists: one for
odds and one for evens. Finally, it concatenates the odds list before the evens list to
achieve the "odd-left, even-right" arrangement.
Q10: Write a program to input a list and remove duplicate elements from the list.

Code:

input_string = input("Enter numbers separated by space: ")

original_list = [int(x) for x in input_string.split()]

unique_list = []

for item in original_list:

if item not in unique_list:

unique_list.append(item)

print("Original List:", original_list)

print("List without duplicates:", unique_list)

Output:

Enter numbers separated by space: 1 2 2 3 4 4 5

Original List: [1, 2, 2, 3, 4, 4, 5]

List without duplicates: [1, 2, 3, 4, 5]

Explanation:

We create an empty list called unique_list. We loop through the original inputs and only
append an item to the new list if it does not already exist there. This preserves the
original order while removing duplicates.
Q11: Write a program to input a string and display the longest word in the given string.

Code:

text = input("Enter a sentence: ")

words = [Link]()

longest = ""

for word in words:

if len(word) > len(longest):

longest = word

print(f"The longest word is: {longest}")

Explanation:
The split() method breaks the sentence into a list of words. The loop iterates through
every word, comparing its length to the currently stored longest word.

Output:

Enter a sentence: Programming in Python is fun

The longest word is: Programming


Q12: Write a program to input a string and check whether it is a palindrome or not.

text = input("Enter a string: ")

clean_text = [Link]()

if clean_text == clean_text[::-1]:

print("It is a Palindrome.")

else:

print("It is NOT a Palindrome.")

Explanation:
A palindrome reads the same forwards and backwards. We use string slicing [::-1] to
reverse the string and compare it with the original.

Output:

Enter a string: Madam

It is a Palindrome.
Q13: Write a program to read a sentence and then create a dictionary that contains the
frequency of letters and digits in the sentence. Ignore other symbols if any.

sentence = input("Enter a sentence: ")

freq_dict = {}

for char in sentence:

if [Link]():

if char in freq_dict:

freq_dict[char] += 1

else:

freq_dict[char] = 1

print("Frequency Dictionary:", freq_dict)

Explanation:
The isalnum() method ensures we only count letters and numbers, ignoring spaces and
punctuation. We use a dictionary to store the character as the Key and its count as the
Value.

Output:

Enter a sentence: Class 12 CS!!

Frequency Dictionary: {'C': 2, 'l': 1, 'a': 1, 's': 3, '1': 1, '2': 1}


Q14: Write a program to input your friend’s names and their phone numbers and store them in
a dictionary. Perform various operations (Display, Add, Delete, Modify, Search, Sort).

Code:

friends = {"Amit": "9876543210", "Rahul": "1122334455"}

# (a) Display all

print("(a) All Friends:", friends)

# (b) Add new

name = input("Enter new name to add: ")

phone = input("Enter phone number: ")

friends[name] = phone

print("(b) After Adding:", friends)

# (c) Delete a friend

del_name = input("Enter name to delete: ")

if del_name in friends:

del friends[del_name]

print("(c) After Deleting:", friends)

# (d) Modify number

mod_name = input("Enter name to modify: ")

if mod_name in friends:

new_phone = input("Enter new phone number: ")

friends[mod_name] = new_phone

print("(d) After Modification:", friends)


# (e) Check presence

check_name = input("Enter name to search: ")

if check_name in friends:

print(f"(e) {check_name} is present.")

else:

print(f"(e) {check_name} is NOT present.")

# (f) Sort by name

sorted_friends = dict(sorted([Link]()))

print("(f) Sorted Dictionary:", sorted_friends)

Explanation:
This script sequentially performs dictionary operations: Adding (dict[key]=val), Deleting
(del), Checking existence (if key in dict), and Sorting (sorted([Link]())).

Output:

(a) All Friends: {'Amit': '9876543210', 'Rahul': '1122334455'}

Enter new name to add: Suman

Enter phone number: 5555555555

(b) After Adding: {'Amit': '9876543210', 'Rahul': '1122334455', 'Suman':


'5555555555'}
Q15: Write a function that takes two numbers and returns the number that has the minimum
one’s digit.
Code:

def check_min_digit(n1, n2):

digit1 = n1 % 10

digit2 = n2 % 10

if digit1 < digit2:

return n1

else:

return n2

val1 = 491

val2 = 278

result = check_min_digit(val1, val2)

print(f"Between {val1} and {val2}, the result is: {result}")

Explanation:
The function uses the modulo operator % 10 to isolate the last digit of both numbers. It
compares these digits and returns the full original number corresponding to the smaller
digit.

Output:

Between 491 and 278, the result is: 491


Q16: Write a program that generates a series using a function which takes the first and last
values and generates four terms that are equidistant.
Code:

def generate_series(start, end):

# We need 4 terms. There are 3 intervals between 4 terms.

# Step size = (Last - First) / 3

step = (end - start) // 3

term1 = start

term2 = start + step

term3 = start + (step * 2)

term4 = end # or start + (step * 3)

return term1, term2, term3, term4

s, e = 1, 7

series = generate_series(s, e)

print(f"Series between {s} and {e}: {series}")

Explanation:
To find equidistant points (Arithmetic Progression), we calculate the "common
di erence" (step). For 4 terms, the range is divided into 3 parts.

Output:

Series between 1 and 7: (1, 3, 5, 7)

Q17: Write a function ETCount() in Python, which should read each character of a
text file “[Link]” and then count and display the count of occurrences of the
alphabets E and T individually.
Code:

with open("[Link]", "w") as f:

[Link]("The Elephant eats Tea leaves.")

def ETCount():

count_e = 0

count_t = 0

with open("[Link]", "r") as f:

content = [Link]()

for char in content:

if [Link]() == 'e':

count_e += 1

elif [Link]() == 't':

count_t += 1

print(f"Count of E/e: {count_e}")

print(f"Count of T/t: {count_t}")

ETCount()

Explanation:

The function opens the file in read mode. It iterates through every character. The
.lower() function is used to ensure both uppercase (E, T) and lowercase (e, t) are
counted.
Output:

Count of E/e: 6

Count of T/t: 3
Q18: Write a method in Python to read lines from a text file, [Link], to find and display the
occurrence of the word “India”.
Code:

with open("[Link]", "w") as f:

[Link]("India is my country.\nI love India.\nCulture of India is unique.")

def count_india():

count = 0

with open("[Link]", "r") as f:

lines = [Link]()

for line in lines:

words = [Link]()

for word in words:

# Removing punctuation for accurate matching

if [Link](".,!").lower() == "india":

count += 1

print(f"Occurrences of 'India': {count}")

count_india()

Explanation:
The code reads the file line by line. Each line is split into words. We strip
punctuation and check if the word (case-insensitive) matches "india".

Output:

Occurrences of 'India': 3

Q19: Write a program in Python to define and call: (a) add() to accept employee data
to '[Link]'. (b) search() to display records with price > 10000.
Code:

import csv

def add():

with open('[Link]', 'a', newline='') as f:

writer = [Link](f)

fid = input("Enter Furniture ID: ")

fname = input("Enter Furniture Name: ")

fprice = int(input("Enter Price: "))

[Link]([fid, fname, fprice])

print("Record added.")

def search():

print("Searching for items > 10000:")

try:

with open('[Link]', 'r') as f:

reader = [Link](f)

for row in reader:

if int(row[2]) > 10000:

print(row)

except FileNotFoundError:

print("File not found. Add data first.")


print("1. Add Data")

print("2. Search Data")

choice = int(input("Enter choice: "))

if choice == 1:

add()

elif choice == 2:

search()

Explanation:
The csv module is used. add() opens the file in append mode ('a') and writes a list of
inputs. search() reads rows and checks if the value in the 3rd column (index 2) is greater
than 10000.

Output:

1. Add Data

2. Search Data

Enter choice: 1

Enter Furniture ID: 101

Enter Furniture Name: Sofa

Enter Price: 15000

Record added.
Q20: CSV File "[Link]". (i) createfile() to input data. (ii) CountRec(Author) to count books by
specific author.
Code:

import csv

def createfile():

with open('[Link]', 'a', newline='') as f:

writer = [Link](f)

bno = input("Enter Book No: ")

bname = input("Enter Book Name: ")

auth = input("Enter Author: ")

price = input("Enter Price: ")

[Link]([bno, bname, auth, price])

print("Book saved.")

def CountRec(author_name):

count = 0

try:

with open('[Link]', 'r') as f:

reader = [Link](f)

for row in reader:

# Author is at index 2

if row[2].lower() == author_name.lower():

count += 1

return count

except FileNotFoundError:

return 0
createfile()

auth_search = input("Enter Author to count: ")

c = CountRec(auth_search)

print(f"Books by {auth_search}: {c}")

Explanation:
createfile appends a new book record to the CSV. CountRec opens the file in read
mode, iterates through rows, and compares the Author column (index 2) with the
passed parameter.

Output:

Enter Author to count: Rowling

Books by Rowling: 2
Q21: WAP to read following details of sports performance (Sport, competitions, prize won) of
your school & store into binary file [Link]. Show records of those sports whose prize-won
is more than 10.
Code:

import pickle

def create_sports_file():

with open("[Link]", "wb") as f:

while True:

sport = input("Enter Sport Name: ")

competitions = int(input("Enter number of Competitions: "))

prizes = int(input("Enter Prizes Won: "))

record = [sport, competitions, prizes]

[Link](record, f)

more = input("Add another record? (y/n): ")

if [Link]() == 'n':

break

def read_high_achievers():

print("\n--- Sports with more than 10 Prizes ---")

try:

with open("[Link]", "rb") as f:

while True:

record = [Link](f)

if record[2] > 10:

print(record)

except EOFError:

pass

create_sports_file()

read_high_achievers()
Explanation:

1. Writing: The program opens [Link] in wb (write binary) mode. It takes inputs
from the user, creates a list [Sport, Competitions, Prizes], and uses
[Link]() to serialize (save) the object to the file.

2. Reading: It opens the file in rb (read binary) mode. It uses an infinite while loop to
load records using [Link]().

3. Condition: Inside the loop, it checks if the 3rd element (index 2, which is prizes)
is greater than 10. If so, it prints the record.

4. Error Handling: The try-except EOFError block is standard for reading binary files
to stop the loop when the file ends without crashing.

Output:

Enter Sport Name: Cricket

Enter number of Competitions: 15

Enter Prizes Won: 12

Add another record? (y/n): y

Enter Sport Name: Football

Enter number of Competitions: 10

Enter Prizes Won: 5

Add another record? (y/n): n

--- Sports with more than 10 Prizes ---

['Cricket', 15, 12]


Q22: A binary file [Link] (a pickle file) stores the records of structure as [rollno, Name,
marks].(i) Write a user-defined function Create() to input data for a student record and add to
pickle file.
(ii) Write a function Display() in python which prints the records having marks more than 81. If
no matching record is found it displays "No record found".
Code:

import pickle

def Create():

with open("[Link]", "ab") as f:

print("Enter Student Details:")

rno = int(input("Roll No: "))

name = input("Name: ")

marks = float(input("Marks: "))

record = [rno, name, marks]

[Link](record, f)

print("Record added successfully.")

def Display():

found = False

print("\n--- Students with marks > 81 ---")

try:

with open("[Link]", "rb") as f:

while True:

record = [Link](f)

if record[2] > 81:

print(record)

found = True

return
if found == False:

print("No record found")

Create()

Display()

Explanation:

1. Create(): This function opens [Link] in ab (append binary) mode. This


ensures that every time we run the function, new students are added to the end
of the file rather than erasing the old ones. It takes input, forms a list, and dumps
it.

2. Display():

o It sets a boolean flag found = False.

o It iterates through the file reading records.

o If record[2] (marks) is greater than 81, it prints the record and sets found =
True.

o After the loop finishes (indicated by EOFError), it checks the found flag. If
it is still False, it prints the specific message "No record found" as
requested.

Output:

--- Students with marks > 81 ---

[2, 'Sumit', 90.0]

[3, 'Rina', 85.0]


Q23: Consider the tables CABHUB and CUSTOMER. Write SQL commands for the following
statements.
Table Structure:

 CABHUB (Vcode, VehicleName, Make, Color, Capacity, Charges)

 CUSTOMER (CCode, CName, Vcode)

(i) To display the names of all the white colored vehicles.

Code:

SELECT VehicleName

FROM CABHUB

WHERE Color = 'WHITE';

Explanation:
The WHERE clause filters the records to only include those where the 'Color' column
matches the string "WHITE".

(ii) To display name of vehicle, make and capacity of vehicles in ascending order of
their seating capacity.

Code:

SELECT VehicleName, Make, Capacity

FROM CABHUB

ORDER BY Capacity ASC;

Explanation:
The ORDER BY clause sorts the result set. ASC specifies ascending order (smallest to
largest).

(iii) To display the highest charges at which a vehicle can be hired from CABHUB.

Code:
SELECT MAX(Charges)

FROM CABHUB;

Explanation:
The aggregate function MAX() is used to find the largest numerical value in the 'Charges'
column.

(iv) To display the customer name and the corresponding name of the vehicle hired
by them.

Code:

SELECT CName, VehicleName

FROM CUSTOMER, CABHUB

WHERE [Link] = [Link];

Explanation:
This is a Join query. We select data from both tables and link them using the common
column Vcode in the WHERE clause.
Q24: Consider the table STORE. Write SQL commands for the following statements.

Table Structure:

 STORE (ItemNo, Item, Scode, Qty, Rate, LastBuy)

(i) To display details of all the items in the Store table in ascending order of LastBuy.

Code:

SELECT *

FROM STORE

ORDER BY LastBuy;

Explanation:
SELECT * retrieves all columns. ORDER BY LastBuy sorts the dates from oldest to
newest.

(ii) To display ItemNo and Item name of those items from Store table whose Rate is
more than 15 Rupees.

Code:

SELECT ItemNo, Item

FROM STORE

WHERE Rate > 15;

Explanation:
We specify the columns to view (ItemNo, Item) and filter rows where the Rate is strictly
greater than 15.

(iii) To display the details of those items whose Suppliers code (Scode) is 22 or
Quantity in Store (Qty) is more than 110.

Code:

SELECT *

FROM STORE

WHERE Scode = 22 OR Qty > 110;


Explanation:
The OR operator is used in the condition, meaning the row will be shown
if either condition (Scode is 22 or Qty > 110) is true.

(iv) To display Minimum Rate of items for each Supplier individually as per Scode.

Code:

SELECT Scode, MIN(Rate)

FROM STORE

GROUP BY Scode;

Explanation:
GROUP BY Scode arranges the data into groups based on the supplier. MIN(Rate) finds
the lowest rate within each of those specific groups.
Q27: Consider the table DRESS. Write SQL commands for the following statements.
Table Structure:

 DRESS (DCODE, DESCRIPTION, PRICE, MCODE, LAUNCHDATE)

(i) To display DCODE and DESCRIPTION of each dress in ascending order of DCODE.

Code:

SELECT DCODE, DESCRIPTION

FROM DRESS

ORDER BY DCODE ASC;

Explanation:
Selects the specific columns and sorts them numerically by the dress code.

(ii) To display the details of all the dresses which have LAUNCHDATE in between 05-
DEC-07 and 20-JUN-08 (inclusive of both dates).

Code:

SELECT *

FROM DRESS

WHERE LAUNCHDATE BETWEEN '05-DEC-07' AND '20-JUN-08';

Explanation:
The BETWEEN operator selects values within a given range. It includes the start and end
values.

(iii) To display the average PRICE of all the dresses which are made up of material
with MCODE as M003.

Code:

SELECT AVG(PRICE)

FROM DRESS

WHERE MCODE = 'M003';


Explanation:
First, WHERE filters for M003 items. Then, AVG(PRICE) calculates the mathematical
average of the prices for those filtered items.

(iv) To display materialwise (MCODE) highest and lowest price of dresses.

Code:

SELECT MCODE, MAX(PRICE), MIN(PRICE)

FROM DRESS

GROUP BY MCODE;

Explanation:
GROUP BY MCODE buckets the dresses by material. MAX and MIN find the most and
least expensive dress for each material type.
Q28: Consider the tables CONSIGNOR and CONSIGNEE. Write SQL commands.
Table Structure:

 CONSIGNOR (CnorID, CnorName, CnorAddress, City)

 CONSIGNEE (CneeID, CnorID, CneeName, CneeAddress, CneeCity)

(i) To display the names of all Consignors from Mumbai.

Code:

SELECT CnorName

FROM CONSIGNOR

WHERE City = 'Mumbai';

Explanation:
Filters the CONSIGNOR table to only show names where the City column is "Mumbai".

(ii) To display the CneeID, CnorName, CnorAddress, CneeName, CneeAddress for


every Consignee.

Code:

SELECT CneeID, CnorName, CnorAddress, CneeName, CneeAddress

FROM CONSIGNOR, CONSIGNEE

WHERE [Link] = [Link];

Explanation:
This joins the two tables. It matches the CnorID (Consignor ID) present in both tables to
display the sender's details alongside the receiver's details.

(iii) To display consignee details in ascending order of CneeName.

Code:

SELECT *

FROM CONSIGNEE

ORDER BY CneeName ASC;


Explanation:
Sorts the entire CONSIGNEE table alphabetically by the name of the consignee.

(iv) To display number of consignors from each city.

Code:

SELECT City, COUNT(*)

FROM CONSIGNOR

GROUP BY City;

Explanation:
Groups the consignors by their city and COUNT(*) returns the total number of people in
each city group.

You might also like