0% found this document useful (0 votes)
73 views

D XII CS Practical List 2024-25

cs practical 2024-2025
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)
73 views

D XII CS Practical List 2024-25

cs practical 2024-2025
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/ 24

Class XII (CS) New (Session 2024-25) Subject

Name with code: (083) Computer Science


Details of Practical Examination
Maximum Marks: 30

Marks
S No Unit Name (Total=30)

Lab Test:
8
1. Python program (60% logic + 20% documentation + 20% code quality)

1
2. SQL queries (4 queries based on one or two tables) 4

2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using one table / two tables.
● Minimum 4 programs based on Python - SQL connectivity
3 Project (using concepts learnt in Classes 11 and 12) 8
4 Viva voce 3
TOTAL 30 Marks

Order of the points required in practical file:


1. AIM : means the problem which you are going to solve
2. CODING : actual code in Python (Handwritten code)
3. OUTPUT : output of the program on sample data (Handwritten or screenshot)
4. VARIABLE AND FUNCTION USED : list of variables and function used in the program

VARIABLE AND FUNCTION USED


Sno Variable / Function Name Datatype Purpose
Practical Program List (Use functions in your code)
1. WAP to show functionality of a basic calculator using functions.
Suggestive answer:
# Function to add two numbers
def add(x, y):
return x + y
# Function to subtract two numbers
def subtract(x, y):
return x - y
# Function to multiply two numbers
def multiply(x, y):
return x * y
# Function to divide two numbers
def divide(x, y):
if y != 0:
return x / y
else:
return "Error: Division by zero is not allowed."
# Function to take user input and perform calculation
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(add(num1, num2)
elif choice == '2':
print(subtract(num1, num2)
elif choice == '3':
print(multiply(num1, num2))
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input")
# Run the calculator
calculator()
2. WAP to read a text file “myfile.txt” line by line and display each word separated by a #.

Suggestive answer:
# Open the file in read mode
with open("myfile.txt", "r") as file:
# Read each line from the file
for line in file:
# Split the line into words
words = line.split()
# Join the words with '#' and print them
print("#".join(words))
Explanation:

1. open("myfile.txt", "r"): Opens the file myfile.txt in read mode.


2. for line in file:: Reads the file line by line.
3. line.split(): Splits each line into words based on spaces.
4. "#".join(words): Joins the words together with # as a separator.
5. print(): Displays the result for each line.
3. WAP to read a text file “myfile.txt” and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
Suggestive answer:
def count_characters(filename):
# Vowels and consonants definition
vowels = "AEIOUaeiou"
# Initialize counters
vowel_count = 0
consonant_count = 0
uppercase_count = 0
lowercase_count = 0
try:
# Open and read the file
with open(filename, 'r') as file:
text = file.read()
# Loop through each character in the file
for char in text:
if char.isalpha(): # Check if the character is an alphabet
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
# Print the results
print("Vowels:”,vowel_count)
print("Consonants:”, consonant_count)
print("Uppercase characters:”, uppercase_count)
print("Lowercase characters:”, lowercase_count)
except FileNotFoundError:
print("Error: The file”, filename, “was not found.")

# Example usage
count_characters('myfile.txt')
Explanation:

● The program reads the content of the file myfile.txt.


● It checks each character in the text:
o If the character is a vowel or consonant (using the isalpha() function to verify if it's an
alphabet character).
o Counts vowels, consonants, uppercase, and lowercase characters separately.
● The results are printed after processing the file.

Make sure that the file myfile.txt is in the same directory as the Python script or provide the correct path.
4. Remove all the lines that contain the character `a' in a file and write it to another file.
Suggestive answer:
def remove_lines_with_a(input_file, output_file):
with open(input_file, 'r') as infile:
lines = infile.readlines()
with open(output_file, 'w') as outfile:
for line in lines:
if 'a' not in line:
outfile.write(line)
# Example usage:
input_file = 'input.txt' # Replace with your input file name
output_file = 'output.txt' # Replace with your desired output file name
remove_lines_with_a(input_file, output_file)

How it works:

1. The program opens the input file and reads all lines.
2. It then opens the output file for writing.
3. For each line in the input file, it checks if the character 'a' is not present.
4. If 'a' is not in the line, it writes that line to the output file.

Usage:
Make sure to replace input.txt and output.txt with your actual file names. You can run this script in a
Python environment where you have access to the specified files.
5. Write a program to create a text file and print the lines starting with ‘T’ or ‘P’. (Both
uppercase and lowercase).
Suggestive answer:
# Create and write to a text file
file_name = 'sample.txt'
with open(file_name, 'w') as file:
file.write("This is the first line.\n")
file.write("Another line starts with A.\n")
file.write("Perfectly positioned line.\n")
file.write("Just another line.\n")
file.write("To test the output.\n")
file.write("Possible line here.\n")
file.write("Yet another line.\n")
# Read the file and print lines that start with 'T' or 'P'
with open(file_name, 'r') as file:
for line in file:
if line.startswith(('T', 't', 'P', 'p')):
print(line.strip())

Explanation:

1. Creating the File: The program first opens a file named sample.txt in write mode and writes several
lines to it.
2. Reading the File: It then opens the same file in read mode and iterates through each line.
3. Filtering Lines: The startswith method is used to check if the line starts with 'T', 't', 'P', or 'p'.
4. Printing: If the condition is met, it prints the line without leading or trailing whitespace.
6. Read a text file to print the frequency of the word ‘He’ and ‘She’ found in the file.
Suggestive answer:
# Open the file (example.txt)
file = open('example.txt', 'r') # 'r' mode is for reading

# Read the content of the file


content = file.read()

# Close the file


file.close()

# Split the content into a list of words


words = content.split()

# Initialize counters for 'He' and 'She'


he_count = 0
she_count = 0

# Iterate over the list of words and count occurrences


for word in words:
if word == 'He':
he_count += 1
elif word == 'She':
she_count += 1

# Print the results


print("Frequency of 'He':", he_count)
print("Frequency of 'She':", she_count)

Explanation:

1. Opening the file: We use open() to open the file in read mode ('r').
2. Reading the file content: The .read() method reads the entire content of the file into a single string.
3. Closing the file: It's important to close the file after reading to free system resources.
4. Splitting the content: The split() method splits the content by whitespace, returning a list of words.
5. Counting occurrences: We loop through the list of words, and for each word, we check if it is "He" or
"She". We increment the respective counters.
6. Displaying results: The print() function is used to display the counts of "He" and "She".
7. Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
Suggestive answer:
import pickle

# Function to create a binary file with student records (name and roll number)
def create_file(file_name):
# Open the binary file in write mode
file = open(file_name, "wb")

# List of student records with name and roll number


students = [
{"roll": 1, "name": "Alice"},
{"roll": 2, "name": "Bob"},
{"roll": 3, "name": "Charlie"},
{"roll": 4, "name": "David"}
]

# Dump the students' list into the binary file


pickle.dump(students, file)

# Close the file


file.close()

# Function to search for a roll number in the binary file and display the name
def search_roll(file_name, roll_no):
# Open the binary file in read mode
file = open(file_name, "rb")

# Load the list of students from the binary file


students = pickle.load(file)

# Flag to check if the roll number is found


found = False

# Search for the roll number in the list


for student in students:
if student["roll"] == roll_no:
print("Roll Number:", roll_no)
print("Name:", student["name"])
found = True
break

# If roll number is not found, display a message


if not found:
print("Roll number not found.")

# Close the file


file.close()

# Creating the file


create_file("students.dat")

# Searching for a roll number


search_roll("students.dat", 3) # Searches for roll number 3
search_roll("students.dat", 5) # Searches for a non-existent roll number 5

Explanation:

1. Creating the Binary File:


o create_file(file_name) creates a binary file where each student record (roll number and
name) is stored as a dictionary inside a list.
o We use the pickle module to serialize the list of dictionaries and store it in the binary file.
2. Searching for a Roll Number:
o search_roll(file_name, roll_no) opens the binary file in read mode and loads the
serialized list back into memory.
o It iterates over the list of dictionaries, checks if the roll number matches the one provided, and
displays the name if found.
o If the roll number is not found, it prints "Roll number not found.".
8. Create a binary file with roll number, name and marks. Input a roll number and update
the marks.
Suggestive answer:
import pickle

# Function to create binary file and add some data


def create_binary_file():
file = open('student_data.dat', 'wb') # Open the file in binary write mode
records = [
{'roll_no': 101, 'name': 'Alice', 'marks': 85},
{'roll_no': 102, 'name': 'Bob', 'marks': 78},
{'roll_no': 103, 'name': 'Charlie', 'marks': 92},
]

# Dump the records to the file using pickle


for record in records:
pickle.dump(record, file)

file.close() # Close the file

# Function to update marks based on roll number


def update_marks(roll_no, new_marks):
file = open('student_data.dat', 'rb') # Open the file in binary read mode
temp_records = []

# Load all the records into a list and check for the roll number
try:
while True:
record = pickle.load(file)
if record['roll_no'] == roll_no:
record['marks'] = new_marks # Update marks if roll number matches
temp_records.append(record)
except EOFError:
pass # End of file reached

file.close() # Close the file after reading

# Rewrite the file with updated records


file = open('student_data.dat', 'wb') # Open the file in binary write mode
for record in temp_records:
pickle.dump(record, file)

file.close() # Close the file after writing

# Create a binary file with student records


create_binary_file()

# Update the marks for roll number 102


update_marks(102, 88)

Explanation:

1. Binary file creation:


o We first create a binary file student_data.dat and store some sample student data in the
form of dictionaries.
o We use pickle.dump() to write each dictionary into the file in binary format.
2. Update marks:
o We open the file in binary read mode ('rb') to load the records using pickle.load() and
store them in a list.
o When the roll number matches the input, we update the marks for that particular record.
o After modifying the necessary record(s), we write all the records back to the file using
pickle.dump() by opening the file in binary write mode ('wb').
9. Read a CSV file from hard disc and print all the details on the screen.
Suggestive answer:
import csv

def read_csv_file(file_path):
file = open(file_path, mode='r') # Open the file without 'with open()'
reader = csv.reader(file) # Read the file using csv.reader

details = []
for row in reader:
details.append(row) # Store rows in a list instead of printing

file.close() # Don't forget to close the file manually


return details # Return the list of CSV contents

# Call the function


file_path = 'example.csv' # Replace with the actual path to your CSV file
data = read_csv_file(file_path)

# Now, 'data' holds the content of the CSV


for line in data:
print(line) # Use print() to display the data, or you can handle it in another way

Explanation:

1. Opening the file: The open() function is used without with, which means we have to manually close
the file after reading it.
2. Reading the CSV: The csv.reader() function takes the file object and reads it row by row, converting
each row into a list of values.
3. Storing the rows: Each row is appended to the details list.
4. Returning the data: After reading all rows, the function returns the details list, which can be used
later to display or process the CSV data.
10. Read a CSV file (containing item no, name, rate, QOH) from hard disc and print all the
items whose rate is between Rs 500 and Rs 1000.
Suggestive answer:
import csv
# Open the CSV file (without using 'with open()')
file = open('items.csv', 'r')
# Initialize the CSV reader
reader = csv.reader(file)
# Skip the header (assuming the file has headers)
next(reader)
# Loop through the rows and print items with rate between 500 and 1000
for row in reader:
item_no, name, rate, QOH = row
rate = float(rate) # Convert rate from string to float
if 500 <= rate <= 1000:
print("Item No:", item_no, "Name:", name, "Rate:", rate, "QOH:", QOH)
# Close the file
file.close()

Explanation:

1. CSV Reader: Python’s built-in csv module is used to handle the reading of CSV files.
2. Opening the file:
o Instead of using with open(), we explicitly open the file using open(). This allows us to
manually manage the file closing.
o open('items.csv', 'r'): This opens the file in read mode ('r').
3. Skipping the header:
o Assuming the file has headers (like "item no, name, rate, QOH"), the next(reader) function
skips the first row (header).
4. Iterating through rows:
o We loop through the rows in the CSV file, and each row is a list of strings. We unpack this list
into individual variables: item_no, name, rate, and QOH.
o Since rate is read as a string, we convert it to a float before comparison (rate =
float(rate)).
5. Filtering by rate:
o We check if the rate is between 500 and 1000 using the condition 500 <= rate <= 1000. If
true, the details of the item are printed.
6. Closing the file:
o After reading the file, we close it using file.close() to free up resources.

CSV File Example (items.csv):


item no, name, rate, QOH
101,Pen,750,50
102,Notebook,1200,30
103,Stapler,900,10
104,Marker,400,60

Expected Output:
Item No: 101 Name: Pen Rate: 750.0 QOH: 50
Item No: 103 Name: Stapler Rate: 900.0 QOH: 10
11. Create a CSV file by entering user-id and password, read and search the password for
given userid.
Suggestive answer:
import csv

# Function to create a CSV file and add user ID and password


def create_user_csv():
filename = 'users.csv'

# Opening the file in write mode


file = open(filename, 'w', newline='')

# Creating a CSV writer object


writer = csv.writer(file)

# Get user ID and password input from the user


user_id = input("Enter User ID: ")
password = input("Enter Password: ")

# Writing the user ID and password to the CSV file


writer.writerow([user_id, password])

# Closing the file


file.close()

# Function to read the CSV file and search for the password using user ID
def search_password(user_id):
filename = 'users.csv'

# Opening the file in read mode


file = open(filename, 'r')

# Creating a CSV reader object


reader = csv.reader(file)

# Searching for the user ID


for row in reader:
if row[0] == user_id:
print("Password for User ID", user_id, "is:", row[1])
break
else:
print("User ID not found.")

# Closing the file


file.close()

# Main program
create_user_csv() # Create a new user entry
user_id_to_search = input("Enter User ID to search for the password: ")
search_password(user_id_to_search) # Search for the password
Explanation:

1. Import CSV Module: We import the csv module to handle CSV file operations.
2. Function to Create CSV File (create_user_csv):
o We open a file named users.csv in write mode ('w').
o We create a CSV writer object to write data into the file.
o We prompt the user to enter a user ID and a password.
o We use writer.writerow() to write the user ID and password as a row in the CSV file.
o Finally, we close the file to save the changes.
3. Function to Search Password (search_password):
o We open the same file in read mode ('r').
o We create a CSV reader object to read the contents of the file.
o We iterate over each row of the CSV file to check if the first element (user ID) matches the
provided user ID.
o If a match is found, we print the corresponding password. If no match is found after checking all
rows, we notify the user that the user ID was not found.
o Finally, we close the file.
4. Main Program:
o We call create_user_csv() to allow the user to enter their credentials.
o We prompt the user to enter a user ID to search for the corresponding password, calling
search_password() to perform the search.
12. Write a random number generator that generates random numbers between 1 and 6
(simulates a dice). Throw the two dices for 10 times and print their total.
Suggestive answer:
import random
# Function to simulate rolling two dice
def roll_dice():
# Generate a random number between 1 and 6 for each die
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
# Calculate the total of both dice
total = die1 + die2
return total
# Main program to roll the dice 10 times
for i in range(10):
total = roll_dice() # Call the function to roll the dice
print("Roll", i + 1, "total:", total) # Print the total for this roll
Explanation

1. Importing the Random Module:


o import random: This line imports the random module, which contains functions that allow us
to generate random numbers.
2. Defining the roll_dice Function:
o This function simulates rolling two dice.
o Inside the function:
 die1 = random.randint(1, 6): This line generates a random integer between 1 and
6, simulating the first die.
 die2 = random.randint(1, 6): This line does the same for the second die.
 total = die1 + die2: This line calculates the total value of both dice.
 return total: The function returns the calculated total.
3. Rolling the Dice 10 Times:
o for i in range(10): This loop iterates 10 times to simulate rolling the dice 10 times.
o Inside the loop:
 total = roll_dice(): Calls the roll_dice function and stores the returned total.
 print("Roll", i + 1, "total:", total): Prints the current roll number (i + 1)
and the total of the two dice.

Output

When you run this program, it will output something like this:

Roll 1 total: 7
Roll 2 total: 3
Roll 3 total: 8
Roll 4 total: 5
Roll 5 total: 10
Roll 6 total: 4
Roll 7 total: 6
Roll 8 total: 11
Roll 9 total: 9
Roll 10 total: 2

Each line shows the total of the two dice for each roll, which will vary each time you run the
program due to the randomness.
13. Write a Python program to implement a stack using a list data-structure.
Suggestive answer: #menu driven function program of stack using list
def isEmpty(stk):
if len(stk)==0:
return True
else:
return False
def Push(stk,ele):
stk.append(ele)
print("Item Pushed...")
def Pop(stk):
if isEmpty(stk):
print("Stack is empty..Underflow condition..")
else:
print("Poped item is:",stk.pop())
def Peek(stk):
if isEmpty(stk):
print("Stack is empty..Underflow condition..")
else:
print("Stack Top item is:",stk[-1])
def Display(stk):
if isEmpty(stk):
print("Stack is empty....")
else:
for i in range(len(stk)-1,-1,-1):
print(stk[i])
stack=[]
while True:
print("***Stack Operations***")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
item=int(input("Enter the item to be pushed:"))
Push(stack,item)
if ch==2:
Pop(stack)
if ch==3:
Peek(stack)
if ch==4:
Display(stack)
if ch==5:
break
14. WAP to pass an integer list as stack to a function and push only those elements in the stack
which are divisible by 7.
Suggestive answer:

def push_divisible_by_seven(input_list):

# Initialize an empty stack

stack = [ ]

# Iterate through each element in the input list

for num in input_list:

# Check if the number is divisible by 7

if num % 7 == 0:

# Push the number onto the stack

stack.append(num)

# Return the populated stack

return stack

# Example usage

integer_list = [14, 22, 35, 9, 49, 28, 50]

result_stack = push_divisible_by_seven(integer_list)

# Display the result

print("Stack elements divisible by 7:", result_stack)

Explanation

1. Function Definition:
o We define a function named push_divisible_by_seven that takes an input_list as an
argument.
2. Initialize Stack:
o We initialize an empty list called stack, which will be used to store elements that are divisible
by 7.
3. Loop Through Input List:
o We use a for loop to iterate through each element in the input_list.
4. Check for Divisibility:
o Inside the loop, we check if the current number (num) is divisible by 7 using the modulo
operator (%). If num % 7 == 0, it means num is divisible by 7.
5. Push to Stack:
o If the condition is met, we use the append() method to add the number to the stack.
6. Return Stack:
o After the loop finishes, we return the stack containing all the numbers from the input list that
are divisible by 7.
7. Example Usage:
o We create an example list of integers and call the function with this list. Finally, we print the
elements of the stack that are divisible by 7.

Output

When the above program is run with the provided example list, it will display:

Stack elements divisible by 7: [14, 35, 49, 28]

This output shows the elements that were pushed onto the stack, all of which are divisible by 7.
15. Write the definition of a user-defined function `push_even(N)` which accepts a list of integers in a
parameter `N` and pushes all those integers which are even from the list `N` into a Stack named
`EvenNumbers`.
Write function pop_even() to pop the topmost number from the stack and returns it. If the stack is
already empty, the function should display "Empty".
Write function Disp_even() to display all element of the stack without deleting them. If the stack is
empty, the function should display 'None'.
For example: If the integers input into the list `VALUES` are: [10, 5, 8, 3, 12]
Then the stack `EvenNumbers` should store: [10, 8, 12]
Suggestive answer:
# Initialize an empty list to act as a stack
EvenNumbers = [ ]

# Function to push all even numbers from a list into the EvenNumbers stack
def push_even(N):
global EvenNumbers # Using global variable for the stack
for num in N:
if num % 2 == 0: # Check if the number is even
EvenNumbers.append(num) # Push even numbers onto the stack

# Function to pop the topmost element from the EvenNumbers stack


def pop_even():
if len(EvenNumbers) > 0: # Check if stack is not empty
return EvenNumbers.pop() # Pop and return the top element
else:
print("Empty") # If stack is empty, display "Empty"
return None

# Function to display all elements of the EvenNumbers stack


def Disp_even():
if len(EvenNumbers) > 0: # Check if the stack is not empty
print(EvenNumbers) # Print the stack without removing elements
else:
print("None") # If stack is empty, display 'None'

# Example usage:
VALUES = [ ]
for i in range(5):
VALUES.append(int(input("Enter an integer: "))) # Input list of integers

push_even(VALUES) # Push even numbers into the stack


Disp_even() # Display the stack contents
print(pop_even()) # Pop the topmost element and display it
Disp_even() # Display the stack after popping

Explanation:

1. Stack Initialization:
o We use a global list named EvenNumbers to simulate the stack where the even integers are
stored.
2. Function push_even(N):
o The function push_even(N) accepts a list N of integers.
o It checks each number in N using num % 2 == 0 to determine if it is even. If it is, the number is
appended to the EvenNumbers list, which acts as the stack.
3. Function pop_even():
o The pop_even() function removes and returns the topmost element from the stack using the
pop() method.
o If the stack is empty (i.e., the length of the list is zero), it prints "Empty" and returns None.
4. Function Disp_even():
o The Disp_even() function prints the contents of the EvenNumbers stack without modifying it.
o If the stack is empty, it prints "None".

Example Walkthrough:

 Input List: VALUES = [10, 5, 8, 3, 12]


o The even numbers 10, 8, and 12 are pushed into the stack.
 After push_even(VALUES):
o Stack (EvenNumbers) becomes: [10, 8, 12].
 Display the stack:
o It prints [10, 8, 12].
 Pop the topmost element:
o The topmost element 12 is removed and returned.
 Display the stack again:
o After popping, the stack is now [10, 8].
Database Management

16. Queries using Create database, Show databases, Use, Create table, Show Tables, Describe,
Rename, Alter, Select, From, Where, Insert, Update commands.
Suggestive answer:
 Create a Database:
CREATE DATABASE kviit ;

 Show All Databases:


SHOW DATABASES ;
 Use a Database:
USE kviit;
 Create a Table:
CREATE TABLE students (
student_id INT NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
PRIMARY KEY (student_id)
);
 Show All Tables
SHOW TABLES ;

 Describe the Table Structure:


DESCRIBE students ;

 Rename a Table:
RENAME TABLE students TO school_students ;

 Alter a Table (Add a Column):


ALTER TABLE school_students ADD email VARCHAR(100) ;

 Insert Data into the Table:


INSERT INTO school_students (student_id, first_name, last_name, age, email)
VALUES (1, 'John', 'Doe', 20, '[email protected]') ;
 Select Data from the Table:
SELECT * FROM school_students ;
 Select Data with a Condition (WHERE clause):
SELECT * FROM school_students WHERE age > 18 ;
 Update Data in the Table:
UPDATE school_students
SET email = '[email protected]'
WHERE student_id = 1;
17. Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY, GROUP BY, HAVING.
Suggestive answer:
Sample Table
Let's assume we have a table employees with the following structure:
CREATE TABLE employees (
employee_id INT,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2),
hire_date DATE
);

1. Query using DISTINCT


To get a list of unique departments:
SELECT DISTINCT department
FROM employees ;

2. Query using BETWEEN


To find employees hired between 2015 and 2020:
SELECT first_name, last_name, hire_date
FROM employees
WHERE hire_date BETWEEN '2015-01-01' AND '2020-12-31' ;

3. Query using IN
To find employees working in specific departments:

SELECT first_name, last_name, department


FROM employees
WHERE department IN ('HR', 'Finance', 'IT') ;

4. Query using LIKE


To find employees whose last name starts with "S":

SELECT first_name, last_name


FROM employees
WHERE last_name LIKE 'S%' ;

5. Query using IS NULL


To find employees without a department (NULL value in the department column):

SELECT first_name, last_name


FROM employees
WHERE department IS NULL ;

6. Query using ORDER BY


To list employees ordered by their salary in descending order:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC ;

7. Query using GROUP BY


To count the number of employees in each department:

SELECT department, COUNT(*) AS employee_count


FROM employees
GROUP BY department ;

8. Query using HAVING


To find departments with more than 5 employees:

SELECT department, COUNT(*) AS employee_count


FROM employees
GROUP BY department
HAVING COUNT(*) > 5 ;

You might also like