π§ Quiz: What is the most "Pythonic" way to create a new list containing the squares of numbers from an existing list called
A) Using a
B)
C) Using a
D)
β Correct answer:B
Explanation:This is a list comprehension. It's a concise, readable, and often faster way to create a new list from an iterable compared to a traditional loop. Option D creates a generator expression, not a list.
#Python #ProgrammingTips #PythonQuiz
βββββββββββββββ
By: @DataScienceQ β¨
nums?A) Using a
for loop and the .append() method.B)
new_list = [num**2 for num in nums]C) Using a
while loop with an index counter.D)
new_list = (num**2 for num in nums)β Correct answer:
Explanation:
for#Python #ProgrammingTips #PythonQuiz
βββββββββββββββ
By: @DataScienceQ β¨
What is the order of execution of decorators if there are several on one function?
Answer:
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
β Interview question
What is the difference between using
Answer: is a context manager that globally disables gradient calculation for all operations within its block. It's used during inference to reduce memory usage and speed up computation. is a tensor-specific method that creates a new tensor sharing the same data but detached from the current computation graph. This stops gradients from flowing back to the original graph through this tensor, effectively creating a fork.
tags: #interview #pytorch #machinelearning
β‘ @DataScienceQ
What is the difference between using
tensor.detach() and wrapping code in with torch.no_grad()?Answer:
with torch.no_grad()tensor.detach()tags: #interview #pytorch #machinelearning
β‘ @DataScienceQ
β Interview question
When saving a PyTorch model, what is the difference between saving the entire model versus saving just the model's
Answer:Saving the entire model ( ) pickles the entire Python object, including the model architecture and its parameters. Saving just the ( ) saves only a dictionary of the model's parameters (weights and biases).
The recommended approach is to save the because it is more flexible and robust. It decouples the saved weights from the specific code that defined the model, making your code easier to refactor and share without breaking the loading process.
tags: #interview #pytorch #machinelearning
β‘ @DataScienceQ
βββββββββββββββ
By: @DataScienceQ β¨
When saving a PyTorch model, what is the difference between saving the entire model versus saving just the model's
state_dict? Which approach is generally recommended and why?Answer:
torch.save(model, PATH)state_dicttorch.save(model.state_dict(), PATH)The recommended approach is to save the
state_dicttags: #interview #pytorch #machinelearning
β‘ @DataScienceQ
βββββββββββββββ
By: @DataScienceQ β¨
β Interview question
What is the purpose of a pooling layer in a Convolutional Neural Network (CNN)?
Answer:A pooling layer (like Max Pooling or Average Pooling) is used to progressively reduce the spatial size (width and height) of the feature maps. This serves two main purposes: 1) It reduces the number of parameters and computational complexity, which helps to control overfitting. 2) It introduces a degree of translation invariance, meaning the network becomes more robust to small shifts and distortions in the position of features in the input image.
tags: #interview #cnn #deeplearning
βββββββββββββββ
By: @DataScienceQ β¨
What is the purpose of a pooling layer in a Convolutional Neural Network (CNN)?
Answer:
tags: #interview #cnn #deeplearning
βββββββββββββββ
By: @DataScienceQ β¨
β Interview question
What is the difference between the
Answer: Theis for loose comparison, checking for value equality after type juggling. For example, is for strict comparison, checking for both value AND type equality, without any type conversion. So, to use to avoid unexpected bugs.
tags: #interview #php
βββββββββββββββ
By: @DataScienceQ β¨
What is the difference between the
== (loose comparison) and === (strict comparison) operators in PHP?Answer: The
== operator 1 == "1" is true. The === operator 1 === "1" is false. It's generally safer ===tags: #interview #php
βββββββββββββββ
By: @DataScienceQ β¨
β Interview question
What is the difference between
Answer:only if a variable is declared and is not . In contrast, is considered "falsy", which includes or an empty array. A key difference is that a variable like is set (so is true), but also considered empty (so is true).
tags: #interview #php
βββββββββββββββ
By: @DataScienceQ β¨
What is the difference between
isset() and empty() in PHP?Answer:
isset() returns true NULLempty() returns true if a variable NULL, false, 0, "0", an empty string "", $var = 0; isset()empty()tags: #interview #php
βββββββββββββββ
By: @DataScienceQ β¨
β€1
β Interview question
Why is it better to use
Answer: Becausehandles cross-platform compatibility automatically. Operating systems use different path separators (e.g., for Linux/macOS and for Windows). Hardcoding a separator like will break on a different OS. or depending on the system, making the code robust and portable.
tags: #interview #python #os
βββββββββββββββ
By: @DataScienceQ β¨
Why is it better to use
os.path.join() to construct paths instead of simple string concatenation?Answer: Because
os.path.join() /\'folder' + '/' + 'file' os.path.join('folder', 'file') correctly produces folder/filefolder\filetags: #interview #python #os
βββββββββββββββ
By: @DataScienceQ β¨
β€1
Clean Code Tip:
For functions with expensive, repeated computations, manual memoization (caching) adds boilerplate and clutters your logic. Use the
Example:
βββββββββββββββ
By: @DataScienceQ β¨
For functions with expensive, repeated computations, manual memoization (caching) adds boilerplate and clutters your logic. Use the
@lru_cache decorator from functools to get a powerful, ready-made cache with a single line of code. It's a pro-level move for clean, high-performance Python. πExample:
import time
from functools import lru_cache
# The verbose way with manual caching
def fibonacci_manual(n, cache={}):
if n in cache:
return cache[n]
if n < 2:
return n
# Simulate an expensive computation
time.sleep(0.5)
result = fibonacci_manual(n - 1) + fibonacci_manual(n - 2)
cache[n] = result
return result
print("--- Manual Caching Way ---")
start_time = time.time()
print(f"Result: {fibonacci_manual(10)}")
print(f"First call took: {time.time() - start_time:.2f}s")
start_time = time.time()
print(f"Result: {fibonacci_manual(10)}")
print(f"Second call (cached) took: {time.time() - start_time:.2f}s")
# The clean, Pythonic way using @lru_cache
@lru_cache(maxsize=None)
def fibonacci_lru(n):
if n < 2:
return n
# Simulate an expensive computation
time.sleep(0.5)
return fibonacci_lru(n - 1) + fibonacci_lru(n - 2)
print("\n--- Clean @lru_cache Way ---")
start_time = time.time()
print(f"Result: {fibonacci_lru(10)}")
print(f"First call took: {time.time() - start_time:.2f}s")
start_time = time.time()
print(f"Result: {fibonacci_lru(10)}")
print(f"Second call (cached) took: {time.time() - start_time:.2f}s")
βββββββββββββββ
By: @DataScienceQ β¨
β€2
How to get the current module's name?
Answer:
tags:
Please open Telegram to view this post
VIEW IN TELEGRAM
β€1
Top 50 C++ Keywords & Functions
#CPP #Basics #IO
#1.
A preprocessor directive that includes the input/output stream library.
#2.
The main function where program execution begins.
#3.
Used to output data (print to the console).
#4.
Used to get input from the user.
#5.
Tells the compiler to use the
---
#CPP #DataTypes #Variables
#6.
Declares an integer variable.
#7.
Declares a floating-point number variable (can hold decimals).
#8.
Declares a character variable.
#9.
Declares a boolean variable, which can only have the value
#10.
Declares a variable that can hold a sequence of characters. Requires
---
#CPP #Keywords #Operators
#11.
Declares a variable as a constant, meaning its value cannot be changed.
#12.
An operator that returns the size (in bytes) of a data type or variable.
#CPP #Basics #IO
#1.
#include <iostream>A preprocessor directive that includes the input/output stream library.
#include <iostream>
int main() {
std::cout << "This requires iostream!";
return 0;
}
This requires iostream!
#2.
int main()The main function where program execution begins.
#include <iostream>
int main() {
std::cout << "Program starts here.";
return 0;
}
Program starts here.
#3.
std::coutUsed to output data (print to the console).
#include <iostream>
int main() {
std::cout << "Hello, C++!";
return 0;
}
Hello, C++!
#4.
std::cinUsed to get input from the user.
#include <iostream>
#include <string>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old.";
return 0;
}
Enter your age: 25
You are 25 years old.
#5.
using namespace std;Tells the compiler to use the
std (standard) namespace. Avoids prefixing std:: to every standard function.#include <iostream>
using namespace std;
int main() {
cout << "No std:: prefix needed.";
return 0;
}
No std:: prefix needed.
---
#CPP #DataTypes #Variables
#6.
intDeclares an integer variable.
#include <iostream>
int main() {
int number = 100;
std::cout << "The number is: " << number;
return 0;
}
The number is: 100
#7.
doubleDeclares a floating-point number variable (can hold decimals).
#include <iostream>
int main() {
double price = 19.99;
std::cout << "The price is: " << price;
return 0;
}
The price is: 19.99
#8.
charDeclares a character variable.
#include <iostream>
int main() {
char grade = 'A';
std::cout << "Your grade is: " << grade;
return 0;
}
Your grade is: A
#9.
boolDeclares a boolean variable, which can only have the value
true or false.#include <iostream>
int main() {
bool isRaining = false;
std::cout << "Is it raining? " << isRaining; // Outputs 0 for false
return 0;
}
Is it raining? 0
#10.
std::stringDeclares a variable that can hold a sequence of characters. Requires
#include <string>.#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, World!";
std::cout << greeting;
return 0;
}
Hello, World!
---
#CPP #Keywords #Operators
#11.
constDeclares a variable as a constant, meaning its value cannot be changed.
#include <iostream>
int main() {
const double PI = 3.14159;
std::cout << "The value of PI is: " << PI;
// PI = 4; // This would cause a compile error
return 0;
}
The value of PI is: 3.14159
#12.
sizeof()An operator that returns the size (in bytes) of a data type or variable.
#include <iostream>
int main() {
int myInt;
std::cout << "Size of int is: " << sizeof(myInt) << " bytes.";
return 0;
}
Size of int is: 4 bytes.
#13.
A keyword that lets the compiler automatically deduce the data type of a variable at compile-time.
#14.
Returns the memory address of a variable.
#15.
Accesses the value stored at a memory address held by a pointer.
---
#CPP #ControlFlow #Conditional
#16.
Executes a block of code if a specified condition is true.
#17.
Executes a block of code if the condition in the
#18.
Specifies a new condition to test, if the first
#19.
Selects one of many code blocks to be executed.
#20.
Used to exit a
---
#CPP #Loops
#21.
Executes a block of code a specified number of times.
#22.
Loops through a block of code as long as a specified condition is true.
autoA keyword that lets the compiler automatically deduce the data type of a variable at compile-time.
#include <iostream>
int main() {
auto number = 10; // Compiler deduces int
auto pi = 3.14; // Compiler deduces double
std::cout << "Type of 'number' is deduced.";
return 0;
}
Type of 'number' is deduced.
#14.
& (Address-of Operator)Returns the memory address of a variable.
#include <iostream>
int main() {
int var = 20;
std::cout << "Memory address of var: " << &var;
return 0;
}
Memory address of var: 0x61ff08
(Note: Address will vary)
#15.
* (Dereference Operator)Accesses the value stored at a memory address held by a pointer.
#include <iostream>
int main() {
int var = 50;
int* ptr = &var; // ptr holds the address of var
std::cout << "Value at address " << ptr << " is " << *ptr;
return 0;
}
Value at address 0x61ff04 is 50
(Note: Address will vary)
---
#CPP #ControlFlow #Conditional
#16.
ifExecutes a block of code if a specified condition is true.
#include <iostream>
int main() {
int age = 18;
if (age >= 18) {
std::cout << "You are an adult.";
}
return 0;
}
You are an adult.
#17.
elseExecutes a block of code if the condition in the
if statement is false.#include <iostream>
int main() {
int age = 16;
if (age >= 18) {
std::cout << "You are an adult.";
} else {
std::cout << "You are not an adult.";
}
return 0;
}
You are not an adult.
#18.
else ifSpecifies a new condition to test, if the first
if condition is false.#include <iostream>
int main() {
int score = 85;
if (score >= 90) {
std::cout << "Grade: A";
} else if (score >= 80) {
std::cout << "Grade: B";
} else {
std::cout << "Grade: C";
}
return 0;
}
Grade: B
#19.
switch / caseSelects one of many code blocks to be executed.
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday";
break;
case 2:
std::cout << "Tuesday";
break;
case 3:
std::cout << "Wednesday";
break;
}
return 0;
}
Wednesday
#20.
breakUsed to exit a
switch statement or a loop.#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
if (i == 5) {
break; // Exit the loop when i is 5
}
std::cout << i << " ";
}
return 0;
}
0 1 2 3 4
---
#CPP #Loops
#21.
forExecutes a block of code a specified number of times.
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << i << " ";
}
return 0;
}
0 1 2 3 4
#22.
whileLoops through a block of code as long as a specified condition is true.
#include <iostream>
int main() {
int i = 0;
while (i < 5) {
std::cout << i << " ";
i++;
}
return 0;
}
0 1 2 3 4
β€1
#23.
Similar to a
#24. Range-based
Iterates over all elements in a range, such as an array or vector, without using an index.
#25.
Skips the current iteration of a loop and continues with the next iteration.
---
#CPP #Functions
#26. Function Declaration (Prototype)
Declares a function's name, return type, and parameters, allowing it to be used before it's defined.
#27.
A keyword specifying that a function does not return any value.
#28.
Terminates a function and can return a value to the caller.
#29.
Includes the C++ math library for complex mathematical operations.
#30.
A function from
---
#CPP #STL #Vector
#31.
Includes the library for
#32.
A sequence container that encapsulates dynamic size arrays.
#33.
Member function of
do-whileSimilar to a
while loop, but the code block is executed at least once before the condition is tested.#include <iostream>
int main() {
int i = 5;
do {
std::cout << "This will run once.";
i++;
} while (i < 5);
return 0;
}
This will run once.
#24. Range-based
for loopIterates over all elements in a range, such as an array or vector, without using an index.
#include <iostream>
#include <vector>
int main() {
int numbers[] = {10, 20, 30};
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
10 20 30
#25.
continueSkips the current iteration of a loop and continues with the next iteration.
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
if (i == 2) {
continue; // Skip printing 2
}
std::cout << i << " ";
}
return 0;
}
0 1 3 4
---
#CPP #Functions
#26. Function Declaration (Prototype)
Declares a function's name, return type, and parameters, allowing it to be used before it's defined.
#include <iostream>
void sayHello(); // Function declaration
int main() {
sayHello(); // Call the function
return 0;
}
void sayHello() { // Function definition
std::cout << "Hello from function!";
}
Hello from function!
#27.
voidA keyword specifying that a function does not return any value.
#include <iostream>
void printMessage(std::string message) {
std::cout << message;
}
int main() {
printMessage("This function returns nothing.");
return 0;
}
This function returns nothing.
#28.
returnTerminates a function and can return a value to the caller.
#include <iostream>
int add(int a, int b) {
return a + b; // Return the sum
}
int main() {
int result = add(5, 3);
std::cout << "Result: " << result;
return 0;
}
Result: 8
#29.
#include <cmath>Includes the C++ math library for complex mathematical operations.
#include <iostream>
#include <cmath> // Include for sqrt()
int main() {
double number = 25.0;
std::cout << "Square root is: " << sqrt(number);
return 0;
}
Square root is: 5
#30.
pow()A function from
<cmath> that returns the base raised to the power of the exponent.#include <iostream>
#include <cmath>
int main() {
double result = pow(2, 3); // 2 to the power of 3
std::cout << "2^3 is: " << result;
return 0;
}
2^3 is: 8
---
#CPP #STL #Vector
#31.
#include <vector>Includes the library for
std::vector, a dynamic array.#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
myVector.push_back(1);
std::cout << "Vector is ready.";
return 0;
}
Vector is ready.
#32.
std::vectorA sequence container that encapsulates dynamic size arrays.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {10, 20, 30};
std::cout << "First element: " << numbers[0];
return 0;
}
First element: 10
#33.
.push_back()Member function of
std::vector that adds an element to the end.β€1
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
numbers.push_back(5);
numbers.push_back(10);
std::cout << "Vector size: " << numbers.size();
return 0;
}
Vector size: 2
#34.
.size()Member function that returns the number of elements in a container like
std::vector or std::string.#include <iostream>
#include <vector>
int main() {
std::vector<std::string> fruits = {"Apple", "Banana"};
std::cout << "There are " << fruits.size() << " fruits.";
return 0;
}
There are 2 fruits.
#35.
.length()A member function of
std::string that returns its length. It's synonymous with .size().#include <iostream>
#include <string>
int main() {
std::string text = "C++";
std::cout << "The length of the string is: " << text.length();
return 0;
}
The length of the string is: 3
---
#CPP #STL #Algorithms
#36.
#include <algorithm>Includes the standard library algorithms, like sort, find, copy, etc.
#include <iostream>
#include <vector>
#include <algorithm> // Required for std::sort
int main() {
std::vector<int> nums = {3, 1, 4};
std::sort(nums.begin(), nums.end());
std::cout << "Sorting is possible with <algorithm>.";
return 0;
}
Sorting is possible with <algorithm>.
#37.
std::sort()Sorts the elements in a range (e.g., a vector).
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {50, 20, 40, 10, 30};
std::sort(nums.begin(), nums.end());
for(int n : nums) {
std::cout << n << " ";
}
return 0;
}
10 20 30 40 50
#38.
.begin()Returns an iterator pointing to the first element in a container.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {100, 200, 300};
auto it = nums.begin();
std::cout << "First element: " << *it;
return 0;
}
First element: 100
#39.
.end()Returns an iterator referring to the past-the-end element in the container.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3};
// .end() points after the last element, used as a boundary
std::cout << "Vector has elements until the end.";
return 0;
}
Vector has elements until the end.
#40.
#defineA preprocessor directive used to create macros or symbolic constants.
#include <iostream>
#define PI 3.14159
int main() {
std::cout << "The value of PI is " << PI;
return 0;
}
The value of PI is 3.14159
---
#CPP #OOP #Classes
#41.
classA keyword used to declare a class, which is a blueprint for creating objects.
#include <iostream>
class Dog {
public:
void bark() {
std::cout << "Woof!";
}
};
int main() {
Dog myDog;
myDog.bark();
return 0;
}
Woof!
#42.
structSimilar to a class, but its members are public by default.
β€1
#include <iostream>
struct Point {
int x;
int y;
};
int main() {
Point p;
p.x = 10;
p.y = 20;
std::cout << "Point: (" << p.x << ", " << p.y << ")";
return 0;
}
Point: (10, 20)
#43.
publicAn access specifier that makes class members accessible from outside the class.
#include <iostream>
class MyClass {
public: // Accessible from anywhere
int myNum = 10;
};
int main() {
MyClass obj;
std::cout << obj.myNum;
return 0;
}
10
#44.
privateAn access specifier that makes class members accessible only from within the class itself.
#include <iostream>
class MyClass {
private:
int secret = 42;
public:
void printSecret() {
std::cout << secret; // Accessible from within the class
}
};
int main() {
MyClass obj;
// std::cout << obj.secret; // This would cause a compile error
obj.printSecret();
return 0;
}
42
#45. Constructor
A special member function of a class that is executed whenever a new object of that class is created.
#include <iostream>
class Car {
public:
// Constructor
Car() {
std::cout << "Car object created.";
}
};
int main() {
Car myCar; // Constructor is called here
return 0;
}
Car object created.
---
#CPP #OOP #MemoryManagement
#46. Destructor
A special member function that is executed automatically when an object is destroyed.
#include <iostream>
class MyClass {
public:
// Destructor
~MyClass() {
std::cout << "Object destroyed.";
}
};
int main() {
MyClass obj;
// Destructor is called when main() ends
return 0;
}
Object destroyed.
#47.
thisA keyword that refers to the current instance of the class.
#include <iostream>
class Box {
private:
int length;
public:
Box(int length) {
this->length = length; // Use 'this' to distinguish member from parameter
}
void printLength() {
std::cout << "Length: " << this->length;
}
};
int main() {
Box b(10);
b.printLength();
return 0;
}
Length: 10
#48.
newAn operator that allocates memory on the heap and returns a pointer to it.
#include <iostream>
int main() {
int* ptr = new int; // Allocate an integer on the heap
*ptr = 100;
std::cout << "Value from heap: " << *ptr;
delete ptr; // Must deallocate memory
return 0;
}
Value from heap: 100
#49.
deleteAn operator that deallocates memory previously allocated with
new.#include <iostream>
int main() {
int* ptr = new int(55);
std::cout << *ptr << " allocated. ";
delete ptr; // Deallocate the memory
std::cout << "Memory freed.";
// Accessing ptr now is undefined behavior
return 0;
}
55 allocated. Memory freed.
#50.
nullptrRepresents a null pointer literal. It indicates that a pointer does not point to any valid memory location.
#include <iostream>
int main() {
int* ptr = nullptr;
if (ptr == nullptr) {
std::cout << "The pointer is null.";
}
return 0;
}
The pointer is null.
βββββββββββββββ
By: @DataScienceQ β¨
β€1
β
Python Interview Questions with Answers π§βπ»π©βπ»
1οΈβ£ Write a function to remove outliers from a list using IQR.
2οΈβ£ Convert a nested list to a flat list.
3οΈβ£ Read a CSV file and count rows with nulls.
4οΈβ£ How do you handle missing data in pandas?
β¦ Drop missing rows: df.dropna()
β¦ Fill missing values: df.fillna(value)
β¦ Check missing data: df.isnull().sum()
5οΈβ£ Explain the difference between loc[] and iloc[].
β¦ loc[]: Label-based indexing (e.g., row/column names)
Example: df.loc[0, 'Name']
β¦ iloc[]: Position-based indexing (e.g., row/column numbers)
Example: df.iloc
π¬ Tap β€οΈ for more!
1οΈβ£ Write a function to remove outliers from a list using IQR.
import numpy as np
def remove_outliers(data):
q1 = np.percentile(data, 25)
q3 = np.percentile(data, 75)
iqr = q3 - q1
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
return [x for x in data if lower <= x <= upper]
2οΈβ£ Convert a nested list to a flat list.
nested = [[1, 2], [3, 4],]
flat = [item for sublist in nested for item in sublist]
3οΈβ£ Read a CSV file and count rows with nulls.
import pandas as pd
df = pd.read_csv('data.csv')
null_rows = df.isnull().any(axis=1).sum()
print("Rows with nulls:", null_rows)
4οΈβ£ How do you handle missing data in pandas?
β¦ Drop missing rows: df.dropna()
β¦ Fill missing values: df.fillna(value)
β¦ Check missing data: df.isnull().sum()
5οΈβ£ Explain the difference between loc[] and iloc[].
β¦ loc[]: Label-based indexing (e.g., row/column names)
Example: df.loc[0, 'Name']
β¦ iloc[]: Position-based indexing (e.g., row/column numbers)
Example: df.iloc
π¬ Tap β€οΈ for more!
β€2π₯1
Top 100 SQL Interview Questions & Answers
#SQL #InterviewQuestions #DataAnalysis #Database #SQLQueries
π π π π π
#SQL #InterviewQuestions #DataAnalysis #Database #SQLQueries
Please open Telegram to view this post
VIEW IN TELEGRAM
Top 100 SQL Interview Questions & Answers
#SQL #InterviewQuestions #DataAnalysis #Database #SQLQueries
Part 1: Basic Queries & DML/DDL (Q1-20)
#1. Select all columns and rows from a table named
A: Use
#2. Select only the
A: List the desired column names.
#3. Find all products with a
A: Use the
#4. Find all products that are
A: Use
#5. Find all products that are
A: Use
#6. Select all unique
A: Use the
#7. Count the total number of products in the
A: Use the
#8. Find the average
A: Use the
#9. Find the highest and lowest
A: Use the
#10. Sort products by
A: Use
#11. Sort products by
A: Use
#12. Sort products by
A: Specify multiple columns in
#SQL #InterviewQuestions #DataAnalysis #Database #SQLQueries
Part 1: Basic Queries & DML/DDL (Q1-20)
#1. Select all columns and rows from a table named
products.A: Use
SELECT * to retrieve all columns.SELECT *
FROM products;
Output: All data from the 'products' table.
#2. Select only the
product_name and price columns from the products table.A: List the desired column names.
SELECT product_name, price
FROM products;
Output: A table with two columns: 'product_name' and 'price'.
#3. Find all products with a
price greater than 50.A: Use the
WHERE clause with a comparison operator.SELECT product_name, price
FROM products
WHERE price > 50;
Output: Products whose price is more than 50.
#4. Find all products that are
red or have a price less than 20.A: Use
WHERE with OR to combine conditions.SELECT product_name, color, price
FROM products
WHERE color = 'Red' OR price < 20;
Output: Products that are red OR cheaper than 20.
#5. Find all products that are
red AND have a price greater than 100.A: Use
WHERE with AND to combine conditions.SELECT product_name, color, price
FROM products
WHERE color = 'Red' AND price > 100;
Output: Products that are red AND more expensive than 100.
#6. Select all unique
category values from the products table.A: Use the
DISTINCT keyword.SELECT DISTINCT category
FROM products;
Output: A list of unique categories (e.g., 'Electronics', 'Books').
#7. Count the total number of products in the
products table.A: Use the
COUNT(*) aggregate function.SELECT COUNT(*) AS total_products
FROM products;
Output: A single number representing the total count.
#8. Find the average
price of all products.A: Use the
AVG() aggregate function.SELECT AVG(price) AS average_price
FROM products;
Output: A single number representing the average price.
#9. Find the highest and lowest
price among all products.A: Use the
MAX() and MIN() aggregate functions.SELECT MAX(price) AS highest_price, MIN(price) AS lowest_price
FROM products;
Output: Two numbers: the maximum and minimum price.
#10. Sort products by
price in ascending order.A: Use
ORDER BY with ASC (or omit ASC as it's the default).SELECT product_name, price
FROM products
ORDER BY price ASC;
Output: Products listed from cheapest to most expensive.
#11. Sort products by
price in descending order.A: Use
ORDER BY with DESC.SELECT product_name, price
FROM products
ORDER BY price DESC;
Output: Products listed from most expensive to cheapest.
#12. Sort products by
category (ascending), then by price (descending).A: Specify multiple columns in
ORDER BY.SELECT product_name, category, price
FROM products
ORDER BY category ASC, price DESC;
Output: Products grouped by category, then sorted by price within each category.
#13. Get the first 10 products when ordered by
A: Use
#14. Update the
A: Use the
#15. Insert a new product: ('TV', 'Electronics', 800, 'Black').
A: Use the
#16. Delete all products with a
A: Use the
#17. Delete all rows from the
A: Use
#18. Remove the entire
A: Use
#19. Add a new column
A: Use the
#20. Rename the column
A: Use
---
Part 2: Joins (Q21-40)
#21. What is the default type of
A: The default
#22. Explain
A:
product_id.A: Use
LIMIT (MySQL/PostgreSQL) or TOP (SQL Server).-- For MySQL/PostgreSQL
SELECT *
FROM products
ORDER BY product_id
LIMIT 10;
-- For SQL Server
SELECT TOP 10 *
FROM products
ORDER BY product_id;
Output: The first 10 products by their ID.
#14. Update the
price of a product named 'Laptop' to 1200.A: Use the
UPDATE statement with a WHERE clause.UPDATE products
SET price = 1200
WHERE product_name = 'Laptop';
Output: The 'Laptop' product's price is updated in the table.
#15. Insert a new product: ('TV', 'Electronics', 800, 'Black').
A: Use the
INSERT INTO statement.INSERT INTO products (product_name, category, price, color)
VALUES ('TV', 'Electronics', 800, 'Black');
Output: A new row is added to the 'products' table.
#16. Delete all products with a
category of 'Clothing'.A: Use the
DELETE FROM statement with a WHERE clause.DELETE FROM products
WHERE category = 'Clothing';
Output: All products in the 'Clothing' category are removed.
#17. Delete all rows from the
products table without logging individual row deletions.A: Use
TRUNCATE TABLE. This is a DDL command.TRUNCATE TABLE products;
Output: All rows from 'products' are removed, table structure remains.
#18. Remove the entire
products table from the database.A: Use
DROP TABLE. This is a DDL command.DROP TABLE products;
Output: The 'products' table and its data are permanently deleted.
#19. Add a new column
stock_quantity of type INT to the products table.A: Use the
ALTER TABLE statement.ALTER TABLE products
ADD COLUMN stock_quantity INT;
Output: The 'products' table now has a new 'stock_quantity' column.
#20. Rename the column
color to product_color in the products table.A: Use
ALTER TABLE with RENAME COLUMN (PostgreSQL) or CHANGE COLUMN (MySQL) or RENAME COLUMN (SQL Server).-- For PostgreSQL
ALTER TABLE products
RENAME COLUMN color TO product_color;
-- For MySQL
ALTER TABLE products
CHANGE COLUMN color product_color VARCHAR(50); -- Must specify type again
Output: The 'color' column is renamed to 'product_color'.
---
Part 2: Joins (Q21-40)
#21. What is the default type of
JOIN in SQL?A: The default
JOIN type is INNER JOIN. If you just write JOIN, it's equivalent to INNER JOIN.#22. Explain
INNER JOIN and give an example.A:
INNER JOIN returns only the rows that have matching values in both tables. Rows that do not have a match in both tables are excluded.-- Tables: employees (employee_id, name, department_id), departments (department_id, dept_name)
SELECT e.name, d.dept_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
Output: Employees matched with their respective department names.
β€1
#23. Explain
A:
#24. Explain
A:
#25. Explain
A:
#26. What is a
A: A
Use Case: Finding employees who report to the same manager.
#27. How would you find all employees who do NOT have a department assigned?
A: Use a
#28. How would you find all departments that currently have no employees?
A: Use a
#29. What is a
A: A
When used: It's rare but can be used for generating all possible combinations, such as all possible time slots for a meeting, or all product-color combinations.
LEFT JOIN (or LEFT OUTER JOIN) and give an example.A:
LEFT JOIN returns all rows from the left table, and the matching rows from the right table. If there's no match in the right table, NULL values are returned for columns from the right table.-- Show all employees, and their department if they have one
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;
Output: All employees, with NULL for 'dept_name' if no department is assigned.
#24. Explain
RIGHT JOIN (or RIGHT OUTER JOIN) and give an example.A:
RIGHT JOIN returns all rows from the right table, and the matching rows from the left table. If there's no match in the left table, NULL values are returned for columns from the left table.-- Show all departments, and any employees assigned to them
SELECT e.name, d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;
Output: All departments, with NULL for 'name' if no employee is in that department.
#25. Explain
FULL JOIN (or FULL OUTER JOIN) and give an example.A:
FULL JOIN returns all rows when there is a match in one of the tables. It effectively combines the results of LEFT JOIN and RIGHT JOIN. If a row doesn't have a match in one table, NULLs are returned for that table's columns.-- Show all employees and all departments, matching where possible
SELECT e.name, d.dept_name
FROM employees e
FULL JOIN departments d ON e.department_id = d.department_id;
Output: All employees and all departments, with NULLs where there's no match.
#26. What is a
SELF JOIN? Provide a use case.A: A
SELF JOIN is a regular join, but the table is joined with itself. It is used to combine and compare rows within the same table.Use Case: Finding employees who report to the same manager.
-- Table: employees (employee_id, name, manager_id)
SELECT e1.name AS employee_name, e2.name AS manager_name
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.employee_id;
Output: A list of employees and their respective managers.
#27. How would you find all employees who do NOT have a department assigned?
A: Use a
LEFT JOIN and filter for NULL values in the right table's key.SELECT e.name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE d.department_id IS NULL;
Output: Names of employees without an assigned department.
#28. How would you find all departments that currently have no employees?
A: Use a
RIGHT JOIN and filter for NULL values in the left table's key.SELECT d.dept_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id
WHERE e.employee_id IS NULL;
Output: Names of departments with no employees.
#29. What is a
CROSS JOIN? When is it used?A: A
CROSS JOIN produces the Cartesian product of the two tables involved. This means it returns all possible combinations of rows from both tables. If Table A has m rows and Table B has n rows, a CROSS JOIN will return m * n rows.When used: It's rare but can be used for generating all possible combinations, such as all possible time slots for a meeting, or all product-color combinations.
-- Tables: colors (color_name), sizes (size_name)
SELECT c.color_name, s.size_name
FROM colors c
CROSS JOIN sizes s;