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

RONAK

Uploaded by

vsenterprise2917
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 views30 pages

RONAK

Uploaded by

vsenterprise2917
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/ 30

SY BCA Div:-D DBHUP-journal.

2481376

Create the following tables and enter at least 10 records with appropriate
constraints:

1. Employees (employee_id, first name, last_name, age, email, phone number, hire date, job id,
salary, commission pct, manager id, department id)
2. Departments ( Department_Id, Department_ Name, Manager Id, Location Id)

3. Locations ( location id, street address, postal_code city, state_province, country id)

4. Countries (country id, country name, region id)

A) Write a query to display the names (first name, last name) using alias name "First
Name", "Last Name")

B) Write a query to select first 10 records from a table.


C) Write a query to display the last names of employees whose names have exactly 6
characters

D) Write a query to get the department ID and the total salary payable in each
department.

E) Write a query to find the names (first name, last name) of the employees who have
a manager who works for a department based in the United States.
F) Write a query to find the names (first name, last name), the salary of the employees
who can more than the average salary and who works in any of the IT departments
G) Write a query to find the employee id, name (last name) along with their manager
id, manager name (last name).

H) Write a query to display the job title and average salary of employees.

I) Write a query to find the addresses (location id, street address, city, state province,
country name) of all the departments

Table -1

CREATE TABLE Employe (

employee_id INTEGER PRIMARY KEY,

first_name TEXT,

last_name TEXT,

age INTEGER,

email TEXT,

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

phone_number TEXT,

hire_date TEXT,

job_id TEXT,

salary REAL,

commission_pct REAL,
manager_id INTEGER,

department_id INTEGER );

Table -2

CREATE TABLE Departments (


department_id INTEGER PRIMARY KEY,

department_name TEXT,

manager_id INTEGER,

location_id INTEGER);

Table -3

CREATE TABLE IF NOT EXISTS Locations (


location_id INTEGER PRIMARY KEY,

street_address TEXT,
postal_code TEXT,

city TEXT,

state_province TEXT,
country_id TEXT);

Table -4

CREATE TABLE IF NOT EXISTS Countries (

country_id TEXT PRIMARY KEY,

country_name TEXT,
region_id INTEGER);

Table Insert-1

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

Table Insert-2

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

Table Insert-3

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

Table Insert-4

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

Quries:-
A) Write a query to display the names (first name, last name) using alias name "First Name",
"Last Name")

B) Write a query to select first 10 records from a table.

C) Write a query to display the last names of employees whose names have exactly 6 characters

D) Write a query to get the department ID and the total salary payable in each de np ta. r tme

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

E) Write a query to find the names (first name, last name) of the employees who have a manager who
works for a department based in the United States

F) Write a query to find the names (first name, last name), the salary of the employees who can more
than the average salary and who works in any of the IT departments.

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

G) Write a query to find the employee id, name (last name) along with their manager id,
manager name (last name).

H) Write a query to display the job title and average salary of employees.

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRATICLE-2

Write a command to dump entire database with proper file name and tables
structure into a file named as your rollno.

SOLUTION:

PRAGMA foreign_keys=OFF;

BEGIN TRANSACTION;

CREATE TABLE stud

stud_id primary key,

stud_name varchar2(30),

stud_salary integer

);

INSERT INTO stud VALUES(1,'jinu',50000);

INSERT INTO stud VALUES(2,'jinesh',40000);

INSERT INTO stud VALUES(3,'jignesh',30000);

INSERT INTO stud VALUES(4,'mukesh',20000);

CREATE TABLE emp

emp_id integer primary key,

emp_name text not null,

phone text default 'unknown'

);

INSERT INTO emp VALUES(1,'jinu','12');

INSERT INTO emp VALUES(2,'vishal','13');

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

INSERT INTO emp VALUES(101,'jinu','1223445674');

INSERT INTO emp VALUES(102,'jinesh','7654564357');

INSERT INTO emp VALUES(103,'hamil','6543326784');

INSERT INTO emp VALUES(104,'Ritik','8765456435');

CREATE TABLE man

id integer primary key,

name text not null,

phone text default 'unknown'

);

INSERT INTO man VALUES(101,'jinu','unknown');

INSERT INTO man VALUES(102,'jinesh','unknown');

INSERT INTO man VALUES(103,'jignesh','4535467865');

INSERT INTO man VALUES(104,'parth','4565432189');

INSERT INTO man VALUES(105,'sidarth','4589765432');

CREATE TABLE dept(

dept_id integer primary key,

dept_name varchar2(35),

dept_salary numeric

);

INSERT INTO dept VALUES(101,'jinu',10000);

INSERT INTO dept VALUES(102,'manish',20000);

INSERT INTO dept VALUES(103,'harhs',30000);

INSERT INTO dept VALUES(104,'chintu',40000);

INSERT INTO dept VALUES(105,'sidarth',50000);

INSERT INTO dept VALUES(106,'kamal',60000);

INSERT INTO dept VALUES(107,'hamil',70000);

10

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

CREATE TABLE emp2

d_no integer primary key,

d_name varchar2(30));

INSERT INTO emp2 VALUES(101,'jinu');

INSERT INTO emp2 VALUES(102,'aftab');

INSERT INTO emp2 VALUES(103,'harry');

INSERT INTO emp2 VALUES(104,'harsh');

INSERT INTO emp2 VALUES(105,'rakesh');

INSERT INTO emp2 VALUES(106,'jignesh');

INSERT INTO emp2 VALUES(107,'jayesh');

INSERT INTO emp2 VALUES(108,'sidarth');

CREATE TABLE emp3

eno number primary key,

ename varchar2(35),

d_no integer references emp3(d_no),

salary number);

INSERT INTO emp3 VALUES(101,'jinu',2,10000);

INSERT INTO emp3 VALUES(102,'aftab',3,20000);

INSERT INTO emp3 VALUES(103,'raj',4,30000);

INSERT INTO emp3 VALUES(104,'kamal',5,40000);

INSERT INTO emp3 VALUES(105,'sidarth',6,50000);

INSERT INTO emp3 VALUES(106,'brijesh',7,60000);

INSERT INTO emp3 VALUES(107,'manat',8,70000);

CREATE TABLE stud3 (

studentid integer primary key,

11

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

name varchar(20) not null,

age integer,

mark real);

INSERT INTO stud3 VALUES(1,'jinu',20,80.0);

CREATE TABLE stud4 (

studentid integer primary key,

name varchar(20) not null,

age integer,

mark real);

INSERT INTO stud4 VALUES(1,'jinu',20,80.0);

INSERT INTO stud4 VALUES(2,'vishal',19,89.0);

CREATE TABLE employees (

employee_id integer primary key,

first_name text(30),

last_name text(30),

age integer,

email varchar(30),

phone_number integer,

hire_date DATE,

job_id text(30),

salary REAL,

commission_pct REAL,

manager_id integer,

location text(30));

CREATE TABLE Employee (

emp_id INTEGER PRIMARY KEY,

first_name TEXT,

12

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

last_name TEXT,

name TEXT,

age INTEGER,

email TEXT,

phone_number TEXT,

hire_date DATE,

job_id INTEGER,

salary REAL,

commission_pct REAL,

manager_id INTEGER,

department_id INTEGER,

location TEXT

);

CREATE TABLE Employe (

employee_id integer primary key,

first_name text(30),

last_name text(30),

age integer,

email text(40),

phone_number integer,

hire_date DATE,

job_id integer,

salary REAL,

commision_act real,

manager_id integer,

department_id integer);

INSERT INTO Employe VALUES(1,'jinu','jain',19,'[email protected]',1472583690,'2023-


01-15',101,75000.0,0.05000000000000000277,1001,1);

13

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

INSERT INTO Employe


VALUES(2,'vishal','karena',20,'[email protected]',1472583609,'2023-02-
14',102,70000.0,0.05999999999999999778,1002,2);

INSERT INTO Employe


VALUES(3,'m ilin','karena',21,'mi [email protected]',1472583609,'2023 -01-
16',103,60000.0,0.04000000000000000083,1003,3);

INSERT INTO Employe


VALUES(4,'manish','sharma',18,'[email protected]',1472583309,'2023-05-
15',104,65000.0,0.05000000000000000277,1004,4);

INSERT INTO Employe VALUES(5,'priya','jain',21,'[email protected]',1472583312,'2023-


05-17',105,50000.0,0.05999999999999999778,1005,5);

INSERT INTO Employe


VALUES(6,'sidarth','jain',18,'[email protected]',1472583345,'2023-05-
20',106,55000.0,0.07000000000000000667,1006,6);

INSERT INTO Employe VALUES(7,'vansh','jain',20,'[email protected]',1472585645,'2023-


07-20',107,45000.0,0.05999999999999999778,1007,7);

INSERT INTO Employe


VALUES(8,'kanishka','jain',20,'[email protected]',1472587845,'2024-07-
20',108,40000.0,0.08000000000000000166,1008,8);

INSERT INTO Employe VALUES(9,'harsh','jain',20,'[email protected]',1472587870,'2024-


09-20',109,30000.0,0.08999999999999999667,1009,9);

INSERT INTO Employe VALUES(10,'ritu','jain',19,'[email protected]',1472587670,'2024-12-


20',110,35000.0,0.1000000000000000055,1000,10);

CREATE TABLE department (

department_id integer primary key,

departmen_name text(30),

manager_id integer,

location_id integer);

INSERT INTO department VALUES(1,'jinesh',1001,101);

INSERT INTO department VALUES(2,'aftab',1002,102);

INSERT INTO department VALUES(3,'milin',1003,103);

INSERT INTO department VALUES(4,'vishal',1004,104);

INSERT INTO department VALUES(5,'kalpesh',1005,105);

INSERT INTO department VALUES(6,'nishay',1006,106);

INSERT INTO department VALUES(7,'rakesh',1007,107);

14

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

INSERT INTO department VALUES(8,'neel',1008,108);

INSERT INTO department VALUES(9,'harry',1009,109);

INSERT INTO department VALUES(10,'pandey',1010,110);

CREATE TABLE countries (

country_id integer,

country_name text(40),

region_id integer);

INSERT INTO countries VALUES(1,'russia',1001);

INSERT INTO countries VALUES(2,'youkrian',1002);

INSERT INTO countries VALUES(3,'newyourk',1003);

INSERT INTO countries VALUES(4,'singapur',1004);

INSERT INTO countries VALUES(5,'malishya',1005);

INSERT INTO countries VALUES(6,'antartica',1006);

INSERT INTO countries VALUES(7,'atlantic',1007);

INSERT INTO countries VALUES(8,'bharat',1008);

INSERT INTO countries VALUES(9,'nodia',1009);

INSERT INTO countries VALUES(10,'norway',1010);

CREATE TABLE locations (

location_id integer primary key,

street_address text(40),

postal_code integer,

city text(40),

state_province text(40),

country_id integer);

INSERT INTO locations VALUES(1,'123 main st',12345,'new yourk','ny',1);

INSERT INTO locations VALUES(2,'456 main st',12354,'maliysha','my',2);

INSERT INTO locations VALUES(3,'456 pine st',13254,'chichog','dy',3);

15

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

INSERT INTO locations VALUES(4,'356 nine st',33254,'diono','sy',4);

INSERT INTO locations VALUES(5,'777 maple st',33252,'liono','py',5);

INSERT INTO locations VALUES(6,'787 malio st',33275,'malio','cy',6);

INSERT INTO locations VALUES(7,'687 chandi st',33252,'chadigard','dy',7);

INSERT INTO locations VALUES(8,'567 gard st',33254,'blondigard','dy',8);

INSERT INTO locations VALUES(9,'897 tone st',33123,'washing ton','wd',9);

INSERT INTO locations VALUES(10,'999 noway st',0,'norway','ny',10);

CREATE TABLE emp1 (

studentid integer primary key,

name varchar(20) not null,

age integer,

mark real);

INSERT INTO emp1 VALUES(1,'jinu',20,80.0);

INSERT INTO emp1 VALUES(2,'vishal',19,89.0);

CREATE TABLE emp6 (

id integer primary key,

name text(30) not null,

age integer);

COMMIT;

16

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-3

Write a trigger called AGECHECK on table EMPLOYE that don’t allow the
insertion or update or any record that has an age less than 18.

SOLLUTION:

17

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-4

Write a python to find mean, median and mode from set of number in a list.

SOLUTTION:

import statistics

def calculate_statistics(numbers):

if not numbers:

raise ValueError("The list of numbers is empty"

mean = statistics.mean(numbers)

median = statistics.median(numbers)

mode = statistics.mode(numbers)

return mean, median, mode

def main():

numbers = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9]

try:

mean, median, mode = calculate_statistics(numbers)

print(f"Mean: {mean}")

print(f"Median: {median}")

print(f"Mode: {mode}")

except ValueError as e:

print(e)

if name == " main ":

main() OUTPUT:-

18

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-5

Write a python to retrieve all rows from Employe table and display the column values
in tabular format.
SOLUTION:

import sqlite3
import pandas as
pd def fetch_and_display_employees(db_file):

try:

conn = sqlite3.connect(db_file)
cursor = conn.cursor()

cursor.execute("SELECT * FROM employees")


rows = cursor.fetchall()

column_names = [description[0] for description in cursor.description]


df = pd.DataFrame(rows, columns=column_names)

print(df)
except sqlite3.Error as err:

print(f"Error: {err}")

finally:

if conn:

conn.close()

db_file = "C:/sqlite/jinu.db"

fetch_and_display_employees(db_file)

19

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

OUTPUT:

20

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-6

Write a python program to read CSV file and upload data into table.

SOLUTION:

import sqlite3
import csv
# Function to create a database connection and table
def create_table(database_path):
connection = sqlite3.connect(database_path)
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees2 ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER,
department TEXT ) ''')
# This command creates the table if it does not exist

connection.commit()
connection.close()

# Function to read CSV file and insert data into the table

def insert_data_from_csv(database_path, csv_file):

connection = sqlite3.connect(database_path)

cursor = connection.cursor()
with open(csv_file, 'r') as file:

reader = csv.DictReader(file) for row in reader:

cursor.execute

(''' INSERT INTO employees2 (id, name, age, department) VALUES (

:id, :name, :age, :department) ''', row)


# This command inserts each row from the CSV file into the table

connection.commit()
connection.close()

# Main execution if name == " main ":

database_path = r'C:\sqlite\vishal.db'

# Database path csv_file_path = r'C:\sqlite\employees.csv'

21

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

# CSV file path

create_table(database_path)

# Create the table if it doesn't exist insert_data_from_csv(database_path, csv_file_path)

# Insert data from CSV connection = sqlite3.connect(database_path)

cursor = connection.cursor()
cursor.execute('SELECT * FROM employees2')

rows = cursor.fetchall()
for row in rows: print(row) #
Print each row to verify insertion connection.close()

22

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-7

Write a python to retrieve all rows from Employe table and dump into
‘employee_details.csv’ CSV file.
SOLUTION:

import sqlite3
import csv
def export_to_csv(db_path, table_name, csv_file_path):

"""Exports data from a SQLite table to a CSV file.

Args:

db_path: The path to the SQLite database file.

table_name: The name of the table to export.


csv_file_path: The path to the output CSV file.

"""

try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()

cursor.execute(f"SELECT * FROM {table_name}")


rows = cursor.fetchall()

# Get column names column_names = [description[0] for description in cursor.description]


with open(csv_file_path, 'w', newline='') as csvfile:

writer = csv.writer(csvfile) writer.writerow(column_names)


# Write the column names as the first row writer.writerows(rows)

# Write the rows except sqlite3.Error as e: print(f"Error: {e}") finally:


if conn: conn.close()
database_path = 'C:\\sqlite\\jinu.db'
table_name = 'employees'

csv_file_path = 'C:\\sqlite\\employee_details.csv'
export_to_csv(database_path, table_name, csv_file_path)

23

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

24

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-8

Write a program to implement DML operation using sqlite3.

SOLUTION:

INSERT-

UPDATE-

25

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

DELETE-

PRACTILE-9
Get total salary from employe table and show line plot with following style properites
Genertated line plot must include following style properties:-
• Line style dotted and line-color should be red
• Show legend at lower right location
• X label name = salary
• Y label name = employe name
• Add a circle marker
• Line marker color as read
• Line wdth should be 3.

SOLUTION:

import sqlite3

import matplotlib.pyplot as plt

conn = sqlite3.connect('C:\\sqlite\\jinu.db')

cursor = conn.cursor()
cursor.execute("SELECT first_name, salary FROM employees")
data = cursor.fetchall()

conn.close()

# Prepare data for plotting names = [row[0] for row in data] salaries = [row[1] for row in data]
# Create the plot plt.plot(salaries, names, linestyle=':', color='red',
marker='o',markerfacecolor='red', linewidth=3)
# Add labels and legend

26

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

plt.xlabel('Salary')

plt.ylabel('Employee Name')

plt.legend(['Total Salary'], loc='lower right')

# Show the plot

plt.show()

OUTPUT:

27

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

PRACTILE-10

Use employe_details.csv file and read salary and commission_pct data and show it
using the bar chart should display the number of units for each employe. Add a
separate bar each first name in the same chart.

SOLUTION:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('C:\\sqlite\\employee_details.csv')
df.rename(columns={'commissic': 'commission_pct'}, inplace=True)
# Prepare data for plotting
employees = df['first_name']
salaries = df['salary']

commissions = df['commission_pct']
# Set the positions and width for the bars
x = np.arange(len(employees)) # the label locations

width = 0.35 # the width of the bars

# Create the bar chart fig, ax1 = plt.subplots()


# Plot salaries on the primary y-axis
bars1 = ax1.bar(x - width/2, salaries, width, label='Salary', color='blue')
ax1.set_xlabel('Employee') ax1.set_ylabel('Salary', color='blue')

ax1.tick_params(axis='y', labelcolor='blue')
ax2 = ax1.twinx()

bars2 = ax2.bar(x + width/2, commissions, width, label='Commission %', color='orange')


ax2.set_ylabel('Commission %', color='orange')
ax2.tick_params(axis='y', labelcolor='orange') ax2.set_ylim(0, 100)
# Set the limit for commission percentage to 100% fig.suptitle('Salaries and Commission
Percentages \nby Employees')

28

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

ax1.set_xticks(x)

ax1.set_xticklabels(employees)
ax1.set_xticklabels(employees, fontsize=8)
fig.legend(loc='upper right', bbox_to_anchor=(1,1))
plt.xticks(rotation=45)

plt.show()

OUTPUT:-

29

KANKADIYA RONAK
SY BCA Div:-D DBHUP-journal. 2481376

30

KANKADIYA RONAK

You might also like