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

Working with functions

Uploaded by

mkavipriya156
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Working with functions

Uploaded by

mkavipriya156
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Working with functions

Type C: Programming Practice/Knowledge based Questions

Q.1 Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns the
amount converted to rupees. Create the function in both void and non-void forms.

Solution

def convert_dollars_to_rupees(amount_in_dollars, conversion_rate):

amount_in_rupees = amount_in_dollars * conversion_rate

return amount_in_rupees

def convert_dollars_to_rupees_void(amount_in_dollars, conversion_rate):

amount_in_rupees = amount_in_dollars * conversion_rate

print("Amount in rupees:", amount_in_rupees)

amount = float(input("Enter amount in dollars "))conversion_rate = float(input("Enter


conversion rate "))

# Non-void function callconverted_amount = convert_dollars_to_rupees(amount,


conversion_rate)print("Converted amount (non-void function):", converted_amount)

# Void function callconvert_dollars_to_rupees_void(amount, conversion_rate)

Output

Enter amount in dollars 50

Enter conversion rate 74.5

Converted amount (non-void function): 3725.0

Amount in rupees: 3725.0

Enter amount in dollars 100

Enter conversion rate 75

Converted amount (non-void function): 7500.0

Amount in rupees: 7500.0

Q.2 Write a function to calculate volume of a box with appropriate default values for its
parameters. Your function should have the following input parameters :

(a) length of box ;


(b) width of box ;

(c) height of box.

Test it by writing complete program to invoke it.

Solution

def calculate_volume(length = 5, width = 3, height = 2):

return length * width * height

default_volume = calculate_volume()print("Volume of the box with default values:",


default_volume)

v = calculate_volume(10, 7, 15)print("Volume of the box with default values:", v)

a = calculate_volume(length = 23, height = 6)print("Volume of the box with default


values:", a)

b = calculate_volume(width = 19)print("Volume of the box with default values:", b)

Output

Volume of the box with default values: 30

Volume of the box with default values: 1050

Volume of the box with default values: 414

Volume of the box with default values: 190

Q.3 Write a program to have following functions :

(i) a function that takes a number as argument and calculates cube for it. The function does not return a
value. If there is no value passed to the function in function call, the function should calculate cube of 2.

(ii) a function that takes two char arguments and returns True if both the arguments are equal otherwise
False.

Test both these functions by giving appropriate function call statements.

Solution

# Function to calculate cube of a numberdef calculate_cube(number = 2):

cube = number ** 3

print("Cube of", number, "is", cube)

# Function to check if two characters are equaldef check_equal_chars(char1, char2):

return char1 == char2

calculate_cube(3)calculate_cube()
char1 = 'a'char2 = 'b'print("Characters are equal:", check_equal_chars(char1,
char1))print("Characters are equal:", check_equal_chars(char1, char2))

Output

Cube of 3 is 27

Cube of 2 is 8

Characters are equal: True

Characters are equal: False

Q.4 Write a function that receives two numbers and generates a random number from that range.
Using this function, the main program should be able to print three numbers randomly.

Solution

import random

def generate_random_number(num1, num2):

low = min(num1, num2)

high = max(num1, num2)

return random.randint(low, high)

num1 = int(input("Enter the first number: "))num2 = int(input("Enter the second


number: "))

for i in range(3):

random_num = generate_random_number(num1, num2)

print("Random number between", num1, "and", num2, ":", random_num)

Output

Enter the first number: 2

Enter the second number: 78

Random number between 2 and 78 : 77

Random number between 2 and 78 : 43

Random number between 2 and 78 : 52

Enter the first number: 100

Enter the second number: 599

Random number between 100 and 599 : 187


Random number between 100 and 599 : 404

Random number between 100 and 599 : 451

Q.5 Write a function that receives two string arguments and checks whether they are same-length
strings (returns True in this case otherwise False).

Solution

def same_length_strings(str1, str2):

return len(str1) == len(str2)

s1 = "hello"s2 = "world"s3 = "python"

print(same_length_strings(s1, s2)) print(same_length_strings(s1, s3))

Output

True

False

Q.6 Write a function namely nthRoot( ) that receives two parameters x and n and returns nth root
of x i.e., x^(1/n).
The default value of n is 2.

Solution

def nthRoot(x, n = 2):

return x ** (1/n)

x = int(input("Enter the value of x:"))n = int(input("Enter the value of n:"))

result = nthRoot(x, n)print("The", n, "th root of", x, "is:", result)

default_result = nthRoot(x)print("The square root of", x, "is:", default_result)

Output

Enter the value of x:36

Enter the value of n:6

The 6 th root of 36 is: 1.8171205928321397

The square root of 36 is: 6.0


Q.7 Write a function that takes a number n and then returns a randomly generated number having
exactly n digits (not starting with zero) e.g., if n is 2 then function can randomly return a number
10-99 but 07, 02 etc. are not valid two digit numbers.

Solution

import randomdef generate_number(n):

lower_bound = 10 ** (n - 1)

upper_bound = (10 ** n) - 1

return random.randint(lower_bound, upper_bound)

n = int(input("Enter the value of n:"))random_number =


generate_number(n)print("Random number:", random_number)

Output

Enter the value of n:2

Random number: 10

Enter the value of n:2

Random number: 50

Enter the value of n:3

Random number: 899

Enter the value of n:4

Random number: 1204

Q.8 Write a function that takes two numbers and returns the number that has minimum one's digit.

[For example, if numbers passed are 491 and 278, then the function will return 491 because it has got
minimum one's digit out of two given numbers (491's 1 is < 278's 8)].

Solution

def min_ones_digit(num1, num2):

ones_digit_num1 = num1 % 10

ones_digit_num2 = num2 % 10

if ones_digit_num1 < ones_digit_num2:


return num1

else:

return num2

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


number:"))result = min_ones_digit(num1, num2)print("Number with minimum one's digit:",
result)

Output

Enter first number:491

Enter second number:278

Number with minimum one's digit: 491

Enter first number:543

Enter second number:765

Number with minimum one's digit: 543

Q.9 Write a program that generates a series using a function which takes first and last values of
the series and then generates four terms that are equidistant e.g., if two numbers passed are 1
and 7 then function returns 1 3 5 7.

Solution

def generate_series(first, last):

step = (last - first) // 3

series = [first, first + step, first + 2 * step, last]

return series

first_value = int(input("Enter first value:"))last_value = int(input("Enter last


value:"))result_series = generate_series(first_value, last_value)print("Generated
Series:", result_series)

Output

Enter first value:1


Enter last value:7
Generated Series: [1, 3, 5, 7]

Enter first value:10


Enter last value:25
Generated Series: [10, 15, 20, 25]
Using Python Libraries

Type C: Programming Practice/Knowledge based Questions


Q.1 Write a Python program having following functions :

1. A function with the following signature : remove_letter(sentence, letter)


This function should take a string and a letter (as a single-character string) as arguments,
returning a copy of that string with every instance of the indicated letter removed. For
example, remove_letter("Hello there!", "e") should return the string "Hllo thr!".
Try implementing it using <str>.split() function.
2. Write a function to do the following :
Try implementing the capwords() functionality using other functions, i.e., split(), capitalize()
and join(). Compare the result with the capwords() function's result.

Solution

def remove_letter(sentence, letter):

words = sentence.split()

new_sentence = []

for word in words:

new_word = ''

for char in word:

if char.lower() != letter.lower():

new_word += char

new_sentence.append(new_word)

return ' '.join(new_sentence)

def capwords_custom(sentence):

words = sentence.split()

capitalized_words = []

for word in words:

capitalized_word = word.capitalize()

capitalized_words.append(capitalized_word)

return ' '.join(capitalized_words)

sentence = input("Enter a sentence: ")letter = input("Enter a letter:


")print("After removing letter:", remove_letter(sentence, letter))

from string import capwordssentences_input = input("Enter a sentence:


")sentences = sentences_input.split('.')
for sentence in sentences:

sentence = sentence.strip()

print("Custom capwords result:", capwords_custom(sentence))

print("Capwords result from string module:", capwords(sentence))

Output

Enter a sentence: Hello there!

Enter a letter: e

After removing letter: Hllo thr!

Enter a sentence: python is best programming language

Custom capwords result: Python Is Best Programming Language

Capwords result from string module: Python Is Best Programming Language

Q.2 Create a module lengthconversion.py that stores functions for various lengths conversion
e.g.,

1. miletokm() — to convert miles to kilometer


2. kmtomile() — to convert kilometers to miles
3. feettoinches()
4. inchestofeet()

It should also store constant values such as value of (mile in kilometers and vice versa).

[1 mile = 1.609344 kilometer ; 1 feet = 12 inches]

Help() function should display proper information.

Solution

# lengthconversion.py"""Conversion functions for various lengths"""

#ConstantsMILE_TO_KM = 1.609344KM_TO_MILE = 1 / MILE_TO_KMFEET_TO_INCHES =


12INCHES_TO_FEET = 1 / FEET_TO_INCHES

#Functionsdef miletokm(miles):

"""Returns: miles converted to kilometers"""

return miles * MILE_TO_KM

def kmtomile(kilometers):

"""Returns: kilometers converted to miles"""

return kilometers * KM_TO_MILE


def feettoinches(feet):

"""Returns: feet converted to inches"""

return feet * FEET_TO_INCHES

def inchestofeet(inches):

"""Returns: inches converted to feet"""

return inches * INCHES_TO_FEET

Output

5 miles to kilometers = 8.04672 km

5 kilometers to miles = 3.1068559611866697 miles

5 feet to inches = 60 inches

24 inches to feet = 2.0 feet

Q.3 Create a module MassConversion.py that stores function for mass conversion e.g.,
1.kgtotonne() — to convert kg to tonnes
2. tonnetokg() — to convert tonne to kg 3. kgtopound() — to convert kg to pound
4. poundtokg() — to convert pound to kg

(Also store constants 1 kg = 0.001 tonne, 1 kg = 2.20462 pound)


Help( ) function should give proper information about the module.

Solution

# MassConversion.py"""Conversion functions between different masses"""

#ConstantsKG_TO_TONNE = 0.001TONNE_TO_KG = 1 / KG_TO_TONNEKG_TO_POUND =


2.20462POUND_TO_KG = 1 / KG_TO_POUND

#Functionsdef kgtotonne(kg):

"""Returns: kilogram converted to tonnes"""

return kg * KG_TO_TONNE

def tonnetokg(tonne):

"""Returns: tonne converted to kilogram"""

return tonne * TONNE_TO_KG

def kgtopound(kg):

"""Returns: kilogram converted to pound"""

return kg * KG_TO_POUND
def poundtokg(pound):

"""Returns: pound converted to kilogram"""

return pound * POUND_TO_KG

Output

6 kilograms to tonnes = 0.006 tonnes

8 tonnes to kilograms = 8000.0 kilograms

5 kilograms to pound = 11.0231 pounds

18 pounds to kilograms = 8.164672369841515 kilograms

Question 4

Create a package from above two modules as this :

Conversion

├──Length

│ └──Lengthconversion.py

└──Mass

└──Massconversion. py

Make sure that above package meets the requirements of being a Python package. Also, you
should be able to import above package and/or its modules using import command.

Answer

1. The basic structure of above package includes packages's name i.e., Conversion and all modules
and subfolders.
2. Create the directory structure having folders with names of package and subpackages. In the
above package, we created two folders by names Length and Mass. Inside these folders, we
created Lengthconversion.py and MassConversion.py modules respectively.
3. Create __init__.py files in package and subpackage folders. We created an empty file and saved
it as "__init__.py" and then copy this empty __init__.py file to the package and subpackage
folders.
4. Associate it with python installation. Once we have our package directory ready, we can associate
it with Python by attaching it to Python's site-packages folder of current Python distribution in our
computer.
5. After copying our package folder in site-packages folder of our current Python installation, now it
has become a Python library so that now we can import its modules and use its functions.

Directory structure is as follows:

Conversion/
├── __init__.py
├── Length/
│ ├── __init__.py
│ └── Lengthconversion.py
└── Mass/
├── __init__.py
└── MassConversion.py

RELATIONAL DATABASES

Assignments

Q.1 Summarize the major differences between a relation and a traditional file.

Answer

Relation file Traditional file


Data organized in tables with rows and columns. Data stored in unstructured formats.

Supports structured querying with SQL. Lacks standardized querying abilities.

Allows for defining relationships between tables. No inherent support for relationships.

Offers flexibility in data storage and retrieval. Limited flexibility in data organisation.

Examples : MySQL, PostgreSQL Examples : Text files, CSV files, Excel spreadsheets

Q.2

(i)Define database.

Answer

A database is defined as a collection of interrelated data stored together to serve multiple


applications.

(ii)Define SQL.

Answer

The Structured Query Language (SQL) is a language that enables us to create and operate on
relational databases (RDBMS), which are sets of related information stored in tables.

(iii)Define view.

Answer

A view is a (virtual) table that does not really exist in its own right but is instead derived from one
or more underlying base tables.

Q.3 What is data redundancy ? How does it impact a database ?

Answer
Duplication of data is known as data redundancy. Data redundancy in a database leads to
wasted storage and multiple copies of the same data. When these copies do not match with one
another, it leads to data inconsistency. Additionally, data redundancy can result in performance
degradation, security risks, and increased complexity.

Q.4 What is data inconsistency ? How does it impact a database ?

Answer

Mismatched multiple copies of same data is known as data inconsistency. Data inconsistency
undermines database reliability, hindering decision-making, causing operational errors, and
increasing complexity.

Q.5

(i)Define tuple.

Answer

The rows of tables (relations) are called tuples.

(ii)Define attribute.

Answer

The columns of tables (relations) are called attributes.

(iii)Define domain.

Answer

A domain is a pool of values from which the actual values appearing in a given column are
drawn.

(iv)Define degree.

Answer

The number of attributes in a relation is called degree of a relation.

(v)Define cardinality.

Answer

The number of rows in a relation is known as cardinality of the relation.

Q.6(i)Define primary key.

Answer

A primary key is a set of one or more attributes that can uniquely identify tuples within the
relation.
(ii)Define foreign key.

Answer

A non-key attribute, whose values are derived from the primary key of some other table, is
known as foreign key in its current table.

Q.7What is MySQL ? What are its functions and features ?

Answer

MySQL is a freely available open source Relational Database Management System (RDBMS)
that uses Structured Query Language (SQL). MySQL provides us with a rich set of features that
support a secure environment for storing, maintaining and accessing data.

The functions and features of MySQL are as follows :

1. Speed — If the server hardware is optimal, MySQL runs very fast. It supports clustered
servers for demanding applications.
2. Ease of use — MySQL is a high performance, relatively simple database system. From
the beginning, MySQL has typically been configured, monitored and managed from the
command line. However, several MySQL graphical interfaces are also available.
3. Query Language Support — MySQL understands standards based SQL.
4. Portability — MySQL provides portability as it has been tested with a broad range of
different compilers and can work on many different platforms. It is fully multi-threaded
using kernel threads. It can easily use multiple CPUs if they are available.
5. Cost — MySQL is available free of cost. MySQL is a open source database.
6. Data Types — MySQL provides many data types to support different types of data. It also
supports fixed-length and variable-length records.
7. Security — MySQL offers a privilege and password system that is very flexible and
secure, and that allows host-based verification. Passwords are secure because all
password traffic is encrypted when we connect to a server.
8. Scalability and Limits — MySQL can handle large databases. Some real life MySQL
databases contain 50 million records, some have up to 60,000 tables and about
5,000,000,000 rows.
9. Connectivity — Clients can connect to MySQL Server using several protocols.
10. Localization — The server can provide error messages to clients in many languages.
11. Clients and Tools — MySQL provides several client and utility programs. These include
both command-line programs such as mysqldump and mysqladmin, and graphical
programs such as MySQL Administrator and MySQL Query Browser. MySQL Server has
built-in support for SQL statements to check, optimize and repair tables.

Q.8 What is the role of database server in database management system ? Give the key
features of MySQL.

Answer

A database server is the key to solving the problems of database management system
(information system). In general, a server must reliably manage a large amount of data in a
multi-user environment so that many users can concurrently access the same data. A database
server must also prevent unauthorized access and provide efficient solutions for failure recovery.

The key features of MySQL are as follows :


1. Speed — If the server hardware is optimal, MySQL runs very fast. It supports clustered
servers for demanding applications.
2. Ease of use — MySQL is a high performance, relatively simple database system. From
the beginning, MySQL has typically been configured, monitored and managed from the
command line. However, several MySQL graphical interfaces are also available.
3. Query Language Support — MySQL understands standards based SQL.
4. Portability — MySQL provides portability as it has been tested with a broad range of
different compilers and can work on many different platforms. It is fully multi-threaded
using kernel threads. It can easily use multiple CPUs if they are available.
5. Cost — MySQL is available free of cost. MySQL is a open source database.
6. Data Types — MySQL provides many data types to support different types of data. It also
supports fixed-length and variable-length records.
7. Security — MySQL offers a privilege and password system that is very flexible and
secure, and that allows host-based verification. Passwords are secure because all
password traffic is encrypted when we connect to a server.
8. Scalability and Limits — MySQL can handle large databases. Some real life MySQL
databases contain 50 million records, some have up to 60,000 tables and about
5,000,000,000 rows.
9. Connectivity — Clients can connect to MySQL Server using several protocols.
10. Localization — The server can provide error messages to clients in many languages.
11. Clients and Tools — MySQL provides several client and utility programs. These include
both command-line programs such as mysqldump and mysqladmin, and graphical
programs such as MySQL Administrator and MySQL Query Browser. MySQL Server has
built-in support for SQL statements to check, optimize and repair tables.

Q.9 What is the use of SQL in MySQL ?

Answer

All programs and users accessing data within the MySQL database must utilize Structured
Query Language (SQL). MySQL is compatible with standard-based SQL, enabling it to
understand and process SQL commands efficiently. Additionally, the MySQL server incorporates
built-in support for executing SQL statements, allowing users to perform tasks such as checking,
optimizing, and repairing tables.

Q.10 How are SQL commands classified ?

Answer

SQL commands can be divided into the following categories :

1. Data Definition Language (DDL) Commands


2. Data Manipulation Language (DML) Commands
3. Transaction Control Language (TCL) Commands
4. Session Control Commands
5. System Control Commands

Q.11 What functions should be performed by ideal DDL ?

Answer

An ideal DDL should perform the following functions :


1. It should identify the types of data division such as data item, segment, record and data-
base file.
2. It should give a unique name to each data-item-type, record-type, file-type, database and
other data subdivision.
3. It should specify the proper data types.
4. It should specify how the record types are related to make structures.
5. It may define the type of encoding the program uses in the data items (binary, character,
bit, string etc.). This should not be confused with the encoding employed in physical
representation.
6. It may define the length of the data items.
7. It may define the range of values that a data-item can assume.
8. It may specify means of checking for errors in the data.
9. It may specify privacy locks for preventing unauthorized reading or modification of the
data.
10. A logical data definition should not specify addressing, indexing or searching techniques
or specify the placement of data on the storage units, because these topics are in the
domain of physical, not logical, organization.

Q.12 Differentiate between DDL and DML commands.

Answer

Data Definition Language (DDL) Data Manipulation Language (DML)


DDL provides a set of definitions to specify the DML is a language that enables users to access
storage structure and access methods used by the or manipulate data as organized by the
database system. appropriate data model.

DDL commands are used to perform tasks such as


creating, altering, and dropping schema objects.
DML commands are used to retrieve, insert,
They are also used to grant and revoke privileges
delete, modify data stored in the database.
and roles, as well as for maintenance commands
related to tables.

Examples of DDL commands are CREATE, ALTER, Examples of DML commands are INSERT,
DROP, GRANT, ANALYZE etc. UPDATE, DELETE, SELECT etc.

Q.13 Name some commands used to assign/revoke privileges from database users.

Answer

Commands used to assign/revoke privileges from database users are GRANT, REVOKE.

Q.14 Name some table maintenance commands.

Answer

Table maintenance commands are ANALYZE TABLE, CHECK TABLE, REPAIR TABLE,
RESTORE TABLE.

Q.15 What is TCL part of SQL ?

Answer
TCL part of SQL includes commands for specifying the beginning and ending of transactions
along with commands to have control over transaction processing. Some examples of TCL
commands are COMMIT, ROLLBACK, SET TRANSACTION and SAVEPOINT. These
commands manage changes made by DML commands.

TABLE CREATION AND DATA MANIPULATION COMMANDS

Type A: Short Answer Questions/Conceptual Questions

Q.1 What are different divisions of SQL and commands ? Give examples of commands in each division.
Answer

SQL commands can be divided into following categories :

1. Data Definition Language (DDL) commands — CREATE, ALTER, DROP, TRUNCATE etc.
2. Data Manipulation Language (DML) commands — INSERT, UPDATE, DELETE etc.
3. Transaction Control Language (TCL) commands — COMMIT, ROLLBACK, SAVEPOINT etc.
4. Session Control Commands
5. System Control Commands

Q.2 What is foreign key ? How do you define a foreign key in your table ?

Answer

A non-key attribute, whose values are derived from the primary key of some other table, is known as
foreign key in its current table. Defining a foreign key in a table involves specifying the relationship
between the tables and setting up rules for data integrity. When two tables are related by a common
column or set of columns, the related column(s) in the parent table (or primary table) should be either
declared as a primary key or unique key. Meanwhile, the related column(s) in the child table (or related
table) should have a foreign key constraint referencing the primary or unique key in the parent table.

Q.3 How is FOREIGN KEY commands different from PRIMARY KEY command ?

Answer

The PRIMARY KEY is a set of one or more attributes that can uniquely identify tuples within the relation.
A primary key column cannot contain NULL values, and it must have unique values for each row. Only
one primary key constraint can exist per table. Conversely, the FOREIGN KEY command establishes a
relationship between two tables by linking a column or set of columns in one table to the primary key or a
unique key in another table. It enforces referential integrity, ensuring that values in the foreign key
column(s) of the referencing table match values in the referenced table's primary key or unique key
column(s). A foreign key can allow NULL values, indicating that the relationship is optional. Multiple
foreign key constraints can exist in a table, each referencing a different parent table.

Q.4 How is FOREIGN KEY commands related to the PRIMARY KEY ?

Answer

FOREIGN KEY commands establish relationships between tables by linking columns in one table to the
PRIMARY KEY or a unique key in another table. This linkage ensures referential integrity, meaning that
values in the FOREIGN KEY column(s) of the referencing table must match values in the PRIMARY KEY
or unique key column(s) of the referenced table. Therefore, FOREIGN KEY commands are directly
related to PRIMARY KEY commands as they rely on the unique identification provided by PRIMARY KEY
constraints in other tables.
Q.5 How do you enforce business rules on a database ?

Answer

Database constraints enforce business rules on a database. These include PRIMARY KEY for unique
identifiers, FOREIGN KEY for maintaining relationships between tables, UNIQUE for ensuring
uniqueness, CHECK constraint limit values that can be inserted into a column of a table, and defau lt
constraints are utilized to specify a default value for a column when no value is explicitly provided during
an insert operation.

Q.6 What are table constraints ? What are column constraints ? How are these two different ?

Answer

Table constraints are rules or conditions applied to an entire table in a database. They are defined when
creating or altering a table's schema.

Column constraints are rules or conditions applied to individual columns within a database table. They
are specified at the column level when creating or altering a table's schema.

The difference between the two is that column constraints apply only to individual columns, whereas
table constraints apply to groups of one or more columns.

Q.7 What is default value ? How do you define it ? What is the default value of column for which
no default value is define ?

Answer

A default value is a predefined value assigned to a column in a database table. It can be specified using
the DEFAULT clause when defining the table's schema. If no default value is defined for a column, and a
new row is inserted into the table without providing a value for that column, the column's default value will
be NULL, unless the column is defined with a NOT NULL constraint. In such cases, an error will occur if a
value is not provided.

Q.8(i)Differentiate between DROP TABLE, DROP DATABASE.

Answer

DROP TABLE DROP DATABASE


This command is used to delete a specific table This command is used to delete an entire database
from the database along with all its data, including all its tables, views, stored procedures,
indexes, triggers, and constraints. triggers, and other objects.

The syntax is : DROP TABLE table_name;. The syntax is : DROP DATABASE database_name;.

Question 8(ii) Differentiate between DROP TABLE, DROP clause of ALTER


TABLE.

Answer

DROP TABLE DROP clause of ALTER TABLE


This command is used to delete a specific table from This command is used to remove a specific
the database along with all its data, indexes, triggers, component of a table, such as columns,
and constraints. constraints, or indexes.
DROP TABLE DROP clause of ALTER TABLE
The syntax is : ALTER TABLE table_name
The syntax is : DROP TABLE table_name;
DROP COLUMN column_name;

Type B: Application Based Questions


Q.1 Insert all those records of table Accounts into table Pending where amt_outstanding is more than
10000.

Answer
INSERT INTO PendingSELECT * FROM AccountsWHERE amt_outstanding > 10000;

Q.2 Increase salary of employee records by 10% (table employee).

Answer

Table employee

ID First_Name Last_Name User_ID Salary

1 Dim Joseph Jdim 5000

2 Jaganath Mishra jnmishra 4000

3 Siddharth Mishra smishra 8000

4 Shankar Giri sgiri 7000

5 Gautam Buddha bgautam 2000


UPDATE employeeSET Salary = (Salary * 0.1) + Salary ;

Output

To view all the details (all columns and rows) of the "employee" table the below query is executed :

SELECT * FROM employee ;

+----+------------+-----------+----------+--------+

| ID | First_Name | Last_Name | User_ID | Salary |

+----+------------+-----------+----------+--------+

| 1 | Dim | Joseph | Jdim | 5500 |

| 2 | Jaganath | Mishra | jnmishra | 4400 |

| 3 | Siddharth | Mishra | smishra | 8800 |

| 4 | Shankar | Giri | sgiri | 7700 |

| 5 | Gautam | Buddha | bgautam | 2200 |

+----+------------+-----------+----------+--------+
Q.3 Give commission of Rs.500 to all employees who joined in year 1982 (table Empl).

Answer

Table: Empl

EMP ENAM HIREDAT DEPT


JOB MGR SAL COMM
NO E E NO

8369 SMITH CLERK 8902 1990-12-18 800 NULL 20

8499 ANYA SALESMAN 8698 1991-02-20 1600 300 30

8521 SETH SALESMAN 8698 1991-02-22 1250 500 30

MAHADE
8566 MANAGER 8839 1991-04-02 2985 NULL 20
VAN

8654 MOMIN SALESMAN 8698 1991-09-28 1250 1400 30

8698 BINA MANAGER 8839 1991-05-01 2850 NULL 30

8839 AMIR PRESIDENT NULL 1991-11-18 5000 NULL 10

KULDEE
8844 SALESMAN 8698 1991-09-08 1500 0 30
P

SHIAVN
8882 MANAGER 8839 1991-06-09 2450 NULL 10
SH

8886 ANOOP CLERK 8888 1993-01-12 1100 NULL 20

8888 SCOTT ANALYST 8566 1992-12-09 3000 NULL 20

8900 JATIN CLERK 8698 1991-12-03 950 NULL 30


EMP ENAM HIREDAT DEPT
JOB MGR SAL COMM
NO E E NO

8902 FAKIR ANALYST 8566 1991-12-03 3000 NULL 20

8934 MITA CLERK 8882 1992-01-23 1300 NULL 10

UPDATE EmplSET COMM = 500WHERE YEAR(HIREDATE) = 1982;

Explanation

Since there are no employees who joined in the year 1982 according to the data provided in the "Empl"
table, executing the given SQL query will result in no changes to the "COMM" column.

Q.4 Allocate the department situated in BOSTON to employee with employee number 7500
(tables EMPL, Dept)

Answer
UPDATE EMPLSET DEPTNO = (

SELECT DEPTNO

FROM Dept

WHERE LOC = 'BOSTON') WHERE EMPNO = 7500;

Q.5 Given the following tables :

Orders (OrdNo, Ord_date, ProdNo#, Qty)

Product (ProdNo, Descp, Price)

Payment (OrdNo, Pment)

Write a query to delete all those records from table Orders whose complete payment has been
made.

Answer
DELETE FROM Orders WHERE OrdNo IN (

SELECT Payment.OrdNo

FROM Payment

WHERE Payment.Pment = 'COMPLETE');

Q.6 Enlist the names of all tables created by you.


Answer

SHOW TABLES ;

Q.7 Write Query statements for following transaction : (Consider tables of question 12)

1. Increase price of all products by 10%.


2. List the details of all orders whose payment is pending as per increased price.
3. Decrease prices by 10% for all those products for which orders were placed 10 months before.

Answer

The following tables are considered :

Orders (OrdNo, Ord_date, ProdNo#, Qty)

Product (ProdNo, Descp, Price)

Payment (OrdNo, Pment)

1. UPDATE productSET price = (price * 0.1) + price ;

2. SELECT *FROM OrdersJOIN Payment ON Orders.OrdNo = Payment.OrdNoWHERE Payment.Pment


= 'Pending';

3. UPDATE ProductSET Price = Price - (Price * 0.1)WHERE ProdNo IN (

SELECT ProdNo#

FROM Orders

WHERE YEAR(Ord_date) = YEAR(CURDATE()) - 1

AND MONTH(Ord_date) = MONTH(CURDATE()) - 10);

Q.8 Modify table Empl, add another column called Grade of VARCHAR type, size 1 into it.

Answer

ALTER TABLE Empl

ADD (Grade VARCHAR(1)) ;

Q.9 In the added column Grade, assign grades as follows :

if sal is in range 700 — 1500, Grade is 1 ;


if sal is in range 1500 — 2200, Grade is 2 ;
if sal is in range 2200 — 3000, Grade is 3 ;
if sal is in range 3000 — Grade is 4 ;

Answer

UPDATE EmplSET Grade = '1'WHERE Sal >= 700 AND Sal <= 1500;

UPDATE EmplSET Grade = '2'WHERE Sal > 1500 AND Sal <= 2200;

UPDATE EmplSET Grade = '3'WHERE Sal > 2200 AND Sal <= 3000;
UPDATE EmplSET Grade = '4'WHERE Sal > 3000;

Q.10 Add a constraint (NN-Grade) in table Empl that declares column Grade not null.

Answer

ALTER TABLE Empl

ADD CONSTRAINT NN_Grade

(Grade NOT NULL) ;

Q.11 Insert a record of your choice in table Empl. Make sure not to enter Grade.

Answer

INSERT INTO Empl (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)VALUES (12345,
'DEEPAK', 'CLERK', 8902, '1990-12-18', 8000, 200, 10);

Q.12 Modify the definition of column Grade. Increase its size to 2.

Answer

ALTER TABLE Empl

MODIFY (Grade VARCHAR(2)) ;

Q.13 Drop the table Empl.

Answer

DROP TABLE IF EXISTS Empl;

Q.14 Create the table Department table based on the following table instance chart.

Column Name ID Name

Data Type NUMBER VARCHAR


Length 8 25
Answer

CREATE TABLE Department (

ID NUMBER(8),

Name VARCHAR(25));

Q.15 Populate the table Department with data from table dept. Including only required columns.

Answer

INSERT INTO Department (ID, Name)SELECT ID, NameFROM dept ;

Q.16 Create the table Employee based on the following table instance chart.
Column Name Data Type Length

ID NUMBER 8

First_Name VARCHAR 25

Last_Name VARCHAR 25

Dept_ID NUMBER 8
Answer

CREATE TABLE Employee (

ID NUMBER(8),

First_Name VARCHAR(25),

Last_Name VARCHAR(25),

Dept_ID NUMBER(8)

);

Q.17 Drop table Employee and Department.

Answer

DROP TABLE IF EXISTS Employee ;DROP TABLE IF EXISTS Department ;

Q.18 Create table Customer as per following Table Instance Chart.

Column Name Data Type Length

Cust_ID NUMBER 7

Cust_Name VARCHAR 30

Cust_Address1 VARCHAR 20

Cust_Address2 VARCHAR 30

Pincode NUMBER 6

Cust_Phone VARCHAR 10
Answer

CREATE TABLE Customer (

Cust_ID NUMBER(7),

Cust_Name VARCHAR(30),

Cust_Address1 VARCHAR(20),

Cust_Address2 VARCHAR(30),

Pincode NUMBER(6),

Cust_Phone VARCHAR(10)
);

Q.19 Add one column Email of data type VARCHAR and size 30 to the table Customer.

Answer

ALTER TABLE Customer

ADD (Email VARCHAR(30)) ;

Q.20 Add one more column CustomerIncomeGroup of datatype VARCHAR(10).

Answer

ALTER TABLE Customer

ADD (CustomerIncomeGroup VARCHAR(10));

Q.21 Insert few records with relevant information, in the table.

Answer

INSERT INTO Customer (Cust_ID, Cust_Name, Cust_Address1, Cust_Address2, Pincode,


Cust_Phone, Email, CustomerIncomeGroup)VALUES

(11, 'Amit', '1st Main Street', 'Mumbai', 12345, '5551234121', '[email protected]',


'High'),

(24, 'Vidya', '4th Main Street', 'Bangalore', 54321, '5234325678',


'[email protected]', 'Medium'),

(39, 'Amruta', '78th Main Street', 'Goa', 98765, '5976539012', '[email protected]',


'Low');

Q.22 Drop the column CustomerIncomeGroup from table Customer.

Answer

ALTER TABLE Customer

DROP COLUMN CustomerIncomeGroup ;

Q.23 Create table Department as per following Table Instance Chart.

Column Name DeptID DeptName

Key Type Primary


Nulls/Unique NOT NULL

Datatype NUMBER VARCHAR

Length 2 20
Answer

CREATE TABLE Department

( DeptID NUMBER(2) PRIMARY KEY,


DeptName VARCHAR(20) NOT NULL);

Q.24 Create table Employee as per following Table Instance Chart.

Column Name EmpID EmpName EmpAddress EmpPhone EmpSal DeptID

Key Type Primary Foreign


Nulls/Unique NOT NULL

Fk Table Department
Fk Column Dept_ID

Datatype NUMBER VARCHAR VARCHAR VARCHAR NUMBER VARCHAR

Length 6 20 30 10 9, 2 2
Answer

CREATE TABLE Employee

( EmpID NUMBER(6) PRIMARY KEY,

EmpName VARCHAR(20) NOT NULL,

EmpAddress VARCHAR(30),

EmpPhone VARCHAR(10),

EmpSal NUMBER(9, 2),

DeptID VARCHAR(2),

FOREIGN KEY (DeptID) REFERENCES Department (Dept_ID)

ON DELETE CASCADE ON UPDATE CASCADE);

Q.25 View structures of all tables created by you.

Answer

DESCRIBE <TABLENAME> ;

You might also like