Python&SQL 100 Interview Questions List
Python&SQL 100 Interview Questions List
Python is a high-level programming language known for its simplicity and readability. It is widely
used in data analytics because it offers powerful libraries such as NumPy, Pandas, and Matplotlib,
which help in data manipulation, analysis, and visualization. Python also supports automation and
integrates well with databases and big data tools.
List comprehension is a concise and efficient way to create lists in Python using a single line of
code. It combines a loop and optional conditions into one readable expression. It is widely used in
data analytics to transform and filter data quickly.
Example:
squares = [x**2 for x in range(5)]
12. Why is list comprehension preferred over loops?
List comprehension is preferred because it reduces the number of lines of code, improves
readability, and is generally faster than traditional loops. It is especially useful when working with
large datasets in data analytics.
A dictionary is a data structure that stores data in key-value pairs. Each key is unique and is used
to access its corresponding value. Dictionaries are useful for storing structured data such as
records.
Example:
data = {"name": "Suprika", "age": 22}
Functions are reusable blocks of code designed to perform a specific task. They help in organizing
code, improving readability, and reducing repetition. Functions are essential in data processing and
analysis.
Parameters are variables defined in a function declaration, while arguments are the actual values
passed to the function when it is called.
Default arguments are parameters that have predefined values. If no value is provided during the
function call, the default value is used.
Example:
def greet(name="Guest"):
A lambda function is an anonymous function defined using the lambda keyword. It is used for short,
simple operations and does not require a formal function definition.
Example:
add = lambda a, b: a + b
The return statement sends a value back to the function caller and is used in further processing.
The print statement only displays output on the screen and does not return any value.
Exception handling is a method used to handle runtime errors in a program. It prevents the
program from crashing and ensures smooth execution using try and except blocks.
23. What is the difference between syntax error and runtime error?
A syntax error occurs when the code violates Python rules and cannot be executed.
A runtime error occurs during execution, even if the syntax is correct.
File handling is used to read, write, and manipulate files. It is important in data analytics for
handling datasets stored in files such as text or CSV files.
A CSV file can be read using the Pandas library. It loads the data into a DataFrame for analysis.
Example:
import pandas as pd
df = pd.read_csv("[Link]")
26. What is NumPy?
NumPy (Numerical Python) is a powerful library used for numerical computations in Python. It
provides support for arrays, matrices, and mathematical functions. It is widely used in data
analytics for handling large datasets efficiently.
A NumPy array is a multi-dimensional array that stores elements of the same data type. It is faster
and more memory-efficient than Python lists.
Example:
import numpy as np
Pandas is a Python library used for data manipulation and analysis. It provides powerful data
structures like Series and DataFrame, which are essential for handling structured data.
A DataFrame is a two-dimensional, tabular data structure with rows and columns, similar to an
Excel sheet or SQL table.
Example:
import pandas as pd
Example:
[Link][0] vs [Link][0]
Example:
The groupby() function is used to group data based on a column and perform aggregation like sum,
mean, or count.
The apply() function is used to apply a custom function to rows or columns of a DataFrame.
df.sort_values(by="Age")
38. How do you find unique values in a column?
df["column_name"].unique()
Data cleaning is the process of removing errors, duplicates, and inconsistencies from data to
improve its quality.
Data preprocessing involves transforming raw data into a format suitable for analysis. It includes
cleaning, normalization, and encoding.
EDA is the process of analyzing datasets to summarize their main characteristics using statistics
and visualizations before applying models.
The describe() function provides summary statistics such as mean, median, standard deviation,
min, and max.
Example:
int("10")
None represents the absence of a value. It is commonly used to indicate missing or undefined data.
46. What is a module?
A module is a file containing Python code (functions, variables) that can be imported and reused.
import math
It is used to check whether a Python file is being run directly or imported as a module.
Python is used in real-world applications like sales analysis. For example, a company can use
Pandas to analyze customer purchase data, identify trends, and make business decisions such as
improving product sales or targeting specific customers.
return a + b
result = add(10, 5)
print("Sum:", result)
Explanation:
A function add() takes two numbers as input and returns their sum.
print("Even")
else:
print("Odd")
Explanation:
If a number is divisible by 2, it is even; otherwise, it is odd.
a, b, c = 10, 25, 15
maximum = max(a, b, c)
print("Maximum:", maximum)
Explanation:
The built-in max() function returns the largest value.
num = 5
fact = 1
fact *= i
print("Factorial:", fact)
Explanation:
Factorial is the product of all numbers from 1 to n.
text = "python"
reversed_text = text[::-1]
print("Reversed:", reversed_text)
Explanation:
Slicing [::-1] reverses the string.
text = "madam"
if text == text[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Explanation:
A palindrome reads the same forward and backward.
vowels = "aeiou"
count = 0
if char in vowels:
count += 1
Explanation:
We loop through the string and count vowels.
lst = [1, 2, 2, 3, 4, 4]
unique_list = list(set(lst))
lst = [1, 2, 3, 4, 5]
total = sum(lst)
print("Sum:", total)
Explanation:
The built-in sum() function calculates total.
print("Maximum:", max(lst))
print("Minimum:", min(lst))
Explanation:
max() and min() return highest and lowest values.
Code:
lst = [1, 2, 2, 3, 3, 3, 4]
freq = {}
if item in freq:
freq[item] += 1
else:
freq[item] = 1
print(freq)
Explanation:
This program uses a dictionary to count how many times each element appears in the list.
Code:
lst = [5, 2, 9, 1]
[Link]()
print(lst)
Explanation:
The sort() method arranges elements in ascending order. You can use reverse=True for
descending order.
Code:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print(common)
Explanation:
Sets are used to find the intersection of two lists efficiently.
Code:
list1 = [1, 2]
list2 = [3, 4]
print(merged)
Explanation:
Lists can be merged using the + operator.
Code:
values = [1, 2, 3]
print(result)
Explanation:
The zip() function pairs elements from both lists to create a dictionary.
Code:
print(sorted_data)
Explanation:
The dictionary is sorted based on values using sorted() and a lambda function.
Code:
print(max_key)
Explanation:
The max() function returns the key with the highest value.
68. Write a program to count words in a string.
Code:
words = [Link]()
count = len(words)
print(count)
Explanation:
The split() function separates words, and len() counts them.
Code:
import string
clean_text = ""
clean_text += char
print(clean_text)
Explanation:
This removes punctuation using the [Link] constant.
Code:
n = 10
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
Explanation:
Each number is the sum of the previous two numbers, starting from 0 and 1.
def calculate_sum(*args):
total = 0
total += num
return total
print(calculate_sum(1, 2, 3, 4))
Explanation:
*args allows passing multiple values. These values are stored as a tuple and summed using a loop.
def greet(name="Guest"):
print(greet())
print(greet("Suprika"))
Explanation:
If no argument is passed, the default value "Guest" is used.
def display_info(**kwargs):
display_info(name="Suprika", age=22)
Explanation:
**kwargs allows passing multiple key-value arguments as a dictionary.
my_list.append(item)
return my_list
print(add_item(1))
Correct Approach:
if my_list is None:
my_list = []
my_list.append(item)
return my_list
Explanation:
Default mutable arguments retain values across function calls, which can cause unexpected
results.
try:
print("Result:", result)
except ZeroDivisionError:
content = [Link]()
print(content)
Explanation:
The with statement ensures the file is properly closed after reading.
import pandas as pd
df = pd.read_csv("[Link]")
print(df)
Explanation:
Reads CSV data into a DataFrame for analysis.
import pandas as pd
df = pd.read_csv("[Link]")
print([Link]())
Explanation:
head() shows the first 5 rows, useful for previewing data.
import pandas as pd
df = pd.read_csv("[Link]")
print([Link])
Explanation:
Returns number of rows and columns as a tuple.
import pandas as pd
df = pd.read_csv("[Link]")
print(filtered)
Explanation:
Filters rows where Age is greater than 25.
import pandas as pd
df = [Link](data)
print([Link]())
Explanation:
The isnull() function detects missing values (NaN) and returns True where values are missing.
import pandas as pd
df = [Link](data)
df["A"].fillna(df["A"].mean(), inplace=True)
df["B"].fillna(df["B"].mean(), inplace=True)
print(df)
Explanation:
Missing values are replaced using the mean of each column, which helps maintain data
consistency.
import pandas as pd
df = [Link](data)
result = [Link]("Department")["Salary"].mean()
print(result)
Explanation:
groupby() groups data by department, and mean() calculates average salary for each group.
import pandas as pd
df = [Link](data)
df_sorted = df.sort_values(by="Age")
print(df_sorted)
Explanation:
sort_values() sorts the DataFrame based on the specified column.
df = [Link](data)
print(df)
Explanation:
The rename() function changes column names for better readability.
import pandas as pd
df = [Link](data)
df = df.drop_duplicates()
print(df)
Explanation:
drop_duplicates() removes duplicate rows from the DataFrame.
import pandas as pd
df = [Link](data)
df["A"] = df["A"].astype(int)
print([Link])
Explanation:
astype() converts the data type of a column (here from string to integer).
import pandas as pd
df = [Link](data)
print(df)
Explanation:
A new column is created by performing operations on existing columns.
import pandas as pd
df = [Link](data)
print(df["A"].unique())
Explanation:
unique() returns distinct values from a column.
import pandas as pd
print(df["Category"].value_counts())
Explanation:
value_counts() counts the frequency of each category in a column.
import numpy as np
print(arr)
import numpy as np
mean_value = [Link](arr)
print("Mean:", mean_value)
import numpy as np
print(result)
reshaped = [Link](2, 3)
print(reshaped)
import numpy as np
print("Max:", [Link](arr))
print("Min:", [Link](arr))
import numpy as np
print(random_numbers)
add = lambda a, b: a + b
print(add(3, 5))
print(flat_list)
lst = [1, 2, 3, 4, 5]
if len(lst) == len(set(lst)):
else:
print("Duplicates found")
import pandas as pd
df = pd.read_csv("[Link]")
print([Link]())
df = [Link]()
print([Link]())
filtered.to_csv("processed_data.csv", index=False)
4. What is a database?
A database is an organized collection of data that is stored electronically. It allows users to
easily access, manage, and update data. Databases are essential in applications like
banking, e-commerce, and data analytics.
Normal forms are rules used in database normalization to reduce redundancy. The main types are First
Normal Form (1NF), Second Normal Form (2NF), and Third Normal Form (3NF). Each level removes
specific types of dependency and duplication. Higher normal forms improve data consistency and integrity.
Denormalization is the process of combining tables to improve read performance. It reduces the number of
joins required in queries. Although it increases redundancy, it is useful in data warehouses and reporting
systems where fast retrieval is important.
13. What is the difference between WHERE and HAVING clause?
The WHERE clause is used to filter rows before grouping, while the HAVING clause is used to filter grouped
data after aggregation. WHERE works with individual rows, whereas HAVING works with aggregate
functions like SUM or COUNT.
CHAR is a fixed-length data type, meaning it always stores the defined number of characters. VARCHAR is
variable-length and stores only the actual data. VARCHAR is more memory-efficient and commonly used in
real-world applications.
NULL represents a missing or unknown value in a database. It is not equal to zero or an empty string. Special
conditions like IS NULL or IS NOT NULL are used to check NULL values.
The DISTINCT keyword is used to remove duplicate values from the result set. It ensures that only unique
values are returned in the output. It is commonly used in data analysis to identify unique entries.
Aggregate functions perform calculations on multiple rows and return a single result. Common functions
include COUNT(), SUM(), AVG(), MIN(), and MAX(). They are widely used in reporting and data analysis.
The GROUP BY clause is used to group rows that have the same values in specified columns. It is often used
with aggregate functions to perform calculations on grouped data, such as total sales per department.
The ORDER BY clause is used to sort the result set in ascending or descending order. By default, it sorts data
in ascending order. It helps in organizing query results for better readability.
The main types of joins are INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. Each join
type determines how data from multiple tables is combined based on matching and non-matching records.
INNER JOIN returns only the records that have matching values in both tables. If there is no match, the row
is not included in the result. It is the most commonly used join in SQL.
LEFT JOIN returns all records from the left table and the matching records from the right table. If there is no
match, NULL values are returned for columns from the right table.
RIGHT JOIN returns all records from the right table and the matching records from the left table. If there is
no match, NULL values are returned for columns from the left table.
FULL OUTER JOIN returns all records from both tables. If there is no match, NULL values are returned for
the missing side. It combines the results of both LEFT JOIN and RIGHT JOIN.
A self join is a join where a table is joined with itself. It is useful when comparing rows within the same
table, such as finding employees and their managers.
A cross join returns the Cartesian product of two tables, meaning every row from the first table is combined
with every row from the second table. It can result in a large number of rows.
A subquery is a query nested inside another SQL query. It is used to perform operations that depend on the
result of another query. Subqueries can be used in SELECT, WHERE, or FROM clauses.
A correlated subquery is a subquery that depends on the outer query for its values. It is executed once for
each row processed by the outer query. This makes it slower than normal subqueries but useful for row-wise
comparisons.
An index is a database object used to improve the speed of data retrieval operations. It works like an index in
a book, helping the database find data quickly without scanning the entire table.
Indexes are used to improve query performance and reduce the time taken to retrieve data. They are
especially useful for large tables where searching without an index would be slow.
A view is a virtual table created based on the result of a SQL query. It does not store data itself but displays
data from one or more tables. Views are used for security and simplifying complex queries.
A table physically stores data in the database, while a view is a virtual representation of data. Changes in the
base table are reflected in the view automatically.
A stored procedure is a precompiled collection of SQL statements stored in the database. It can be executed
whenever needed and helps improve performance and reusability of code.
A function is a reusable SQL block that performs a specific task and returns a value. It can be used in queries
to process and transform data.
A function must return a value and can be used inside queries, while a stored procedure may or may not
return a value and is executed independently. Functions are mainly used for calculations, whereas procedures
handle operations.
39. What is ACID property?
ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties ensure reliable
transaction processing in a database and maintain data integrity even in case of failures.
A transaction is a sequence of SQL operations executed as a single unit. It ensures that either all operations
are completed successfully or none are applied, maintaining database consistency.
COMMIT is used to permanently save all changes made during a transaction in the database. Once
committed, the changes cannot be undone.
ROLLBACK is used to undo changes made during a transaction before they are committed. It helps in
maintaining data integrity in case of errors.
The CASE statement is used to apply conditional logic in SQL queries, similar to if-else conditions in
programming. It allows you to return different values based on specific conditions.
UNION combines results from multiple queries and removes duplicate records.
UNION ALL also combines results but includes all duplicates, making it faster than UNION.
A constraint is a rule applied to a table column to ensure data accuracy and integrity. It restricts the type of
data that can be inserted into the table.
PRIMARY KEY
FOREIGN KEY
UNIQUE
NOT NULL
CHECK
DEFAULT
These constraints help maintain consistency and validity of data.
A DEFAULT constraint assigns a default value to a column when no value is provided during insertion. It
ensures that the column always has a value.
The NOT NULL constraint ensures that a column cannot have NULL (empty) values. It is used when a field
must always contain data.
Referential integrity ensures that relationships between tables remain consistent. It ensures that a foreign key
value always refers to a valid primary key in another table.
A schema is the logical structure of a database that defines how data is organized. It includes tables,
relationships, constraints, and other elements.
In a real-world scenario, SQL is used to analyze business data such as sales or customer behavior. For
example, a company can use SQL queries to find top-selling products, customer purchase trends, and
monthly revenue, helping management make data-driven decisions.
This query is used to fetch all data from a table without any filtering condition.
This query is used when only required columns need to be retrieved instead of all columns.
The DISTINCT keyword is used to remove duplicate records and return only unique values.
WHERE condition;
Aggregate functions MAX() and MIN() are used to find highest and lowest values.
FROM table_name;
SELECT AVG(column_name)
FROM table_name;
61. Write a query to use GROUP BY clause.
The GROUP BY clause is used to group rows that have the same values in specified columns. It is often used
with aggregate functions like COUNT, SUM, or AVG.
FROM employees
GROUP BY department;
The HAVING clause is used to filter grouped data after applying GROUP BY. It works with aggregate
functions.
FROM employees
GROUP BY department
This query calculates the total salary for each department using GROUP BY and SUM function.
FROM employees
GROUP BY department;
FROM employees e
ON e.dept_id = d.dept_id;
LEFT JOIN returns all records from the left table and matching records from the right table.
FROM employees e
ON e.dept_id = d.dept_id;
66. Write a query to join two tables using RIGHT JOIN.
RIGHT JOIN returns all records from the right table and matching records from the left table.
FROM employees e
ON e.dept_id = d.dept_id;
67. Write a query to join two tables using FULL OUTER JOIN.
FULL OUTER JOIN returns all records when there is a match in either left or right table.
FROM employees e
ON e.dept_id = d.dept_id;
SELECT e.*
FROM employees e
ON e.emp_id = m.emp_id;
69. Write a query to find records present in one table but not in another.
SELECT e.*
FROM employees e
ON e.emp_id = m.emp_id
SELECT name,
salary,
FROM employees;
FROM employees
Explanation:
This query first finds the highest salary using a subquery. Then it retrieves the maximum salary that is less
than the highest, which gives the second highest salary.
SELECT salary
FROM employees
Explanation:
This query sorts salaries in descending order and skips the first (n-1) records to fetch the nth highest salary.
Replace n with the desired rank.
73. Write a query to find employees with salary greater than average salary.
SELECT *
FROM employees
Explanation:
This query uses a subquery to calculate the average salary and then filters employees whose salary is greater
than the average.
CASE
ELSE 'Low'
END AS salary_category
FROM employees;
Explanation:
The CASE statement works like an if-else condition. It categorizes employees based on their salary range.
FROM employees;
Explanation:
The COALESCE function replaces NULL values with a specified value (here, 0). It ensures no missing
values during analysis.
FROM employees
GROUP BY name
Explanation:
This query groups records by name and counts occurrences. If the count is greater than 1, it means duplicates
exist.
WHERE id NOT IN (
SELECT MIN(id)
FROM employees
GROUP BY name
);
Explanation:
This query keeps only one record (minimum id) for each group and deletes the rest, effectively removing
duplicates.
salary INT
);
Explanation:
This query creates a new table named employees with columns id, name, and salary, and sets id as the
primary key.
Explanation:
This query modifies the existing table structure by adding a new column called department.
Explanation:
This query removes the specified column from the table permanently.
To rename a column, we use the ALTER TABLE statement along with RENAME COLUMN. This helps
modify the structure of an existing table without affecting the data.
The INSERT INTO statement is used to add new records into a table. You must provide values for all
required columns or specify column names.
The UPDATE statement is used to modify existing records in a table. It is usually combined with the
WHERE clause to update specific rows.
UPDATE employees
SET salary = 60000
WHERE id = 1;
The DELETE statement removes specific records from a table. It is important to use a WHERE clause to
avoid deleting all records.
WHERE id = 1;
TRUNCATE is used to remove all records from a table quickly. It is faster than DELETE and cannot be
rolled back in most cases.
A primary key is created to uniquely identify each record in a table. It ensures that no duplicate or NULL
values exist in that column.
name VARCHAR(50)
);
A foreign key is used to establish a relationship between two tables. It references the primary key of another
table.
order_id INT,
emp_id INT,
);
An index is created to improve the speed of data retrieval operations. It works like an index in a book.
A view is a virtual table created from a SELECT query. It helps simplify complex queries and improves
security.
FROM employees;
The DISTINCT keyword is used to remove duplicate values and return only unique records from a column.
FROM employees;
The BETWEEN operator is used to filter records within a specific range. It includes both the starting and
ending values.
SELECT *
FROM employees
The IN operator is used to match values against a list of multiple values. It simplifies multiple OR conditions.
SELECT *
FROM employees
The LIKE operator is used for pattern matching in text data using wildcards such as % (any number of
characters) and _ (single character).
SELECT *
FROM employees
SELECT *
FROM employees
LIMIT 5;
This query retrieves records within a specific date range using BETWEEN.
SELECT *
FROM orders
SELECT CURRENT_DATE;
FROM employees;
UNION is used to combine results of two queries and removes duplicate rows.
UNION
UNION ALL
Transactions ensure data consistency. COMMIT saves changes, while ROLLBACK undoes them.
BEGIN;
UPDATE employees
WHERE id = 1;
-- If everything is correct
COMMIT;
-- If there is an error
ROLLBACK;