SQL Questions and Answers : PART 1
✅ SQL Date & Time Functions ✅
✅ SQL Date & Time Functions ✅
1. Why Date Functions Matter?
Almost every real-world database contains dates 👇
- ✔️ Orders
- ✔️ Employee joining dates
- ✔️ Transactions
- ✔️ Login activity
SQL date functions help analyze time-based data 💯
⚡ 2. Common Date Functions
Function : Purpose
NOW() : Current date & time
CURDATE() : Current date
CURTIME() : Current time
YEAR() : Extract year
MONTH() : Extract month
DAY() : Extract day
DATEDIFF() : Difference between dates
DATE_FORMAT() : Format dates
🔥 3. NOW(), CURDATE(), CURTIME()
SELECT NOW();
Output : ✔️ Current date + time
SELECT CURDATE();
Output : ✔️ Current date only
SELECT CURTIME();
Output : ✔️ Current time only
🔥 4. YEAR(), MONTH(), DAY()
SELECT YEAR(joining_date) FROM employees;
SELECT MONTH(joining_date) FROM employees;
SELECT DAY(joining_date) FROM employees;
🔥 5. DATEDIFF()
👉 Find difference between dates
SELECT DATEDIFF('2026-06-10', '2026-06-01');
✔️ Result → 9 days
🔥 6. DATE_FORMAT()
👉 Format dates professionally
SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');
✔️ Example Output → 06-06-2026
🎯 7. Real Example
👉 Employees joined in 2025
SELECT * FROM employees WHERE YEAR(joining_date) = 2025;
🎯 8. Practice Tasks
1. Show current date
2. Show current time
3. Extract joining year from employee table
4. Find employees joined in specific month
5. Calculate days between two dates
⚡ Mini Challenge 🔥
👉 Find employees who joined in the last 30 days
✅ Solution Using DATEDIFF()
SELECT * FROM employees WHERE DATEDIFF(CURDATE(), joining_date) <= 30;
✅ Alternative Solution Using DATE_SUB()
SELECT * FROM employees WHERE joining_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
🔥 Pro Tip
Date functions are heavily used in:
👉 Sales reports
👉 Monthly dashboards
👉 Retention analysis
👉 Time-series analytics 💯
✅ SQL String Functions
✅ SQL String Functions
🧠1. What are String Functions?
String functions are used to
- 👉 manipulate text data
- 👉 clean messy data
- 👉 format outputs
Used heavily in:
✔️ Data Analytics
✔️ Reporting
✔️ ETL processes
⚡ 2. Common String Functions
Function : Purpose
UPPER() : Convert to uppercase
LOWER() : Convert to lowercase
LENGTH() : Count characters
CONCAT() : Join strings
SUBSTRING() : Extract part of string
TRIM() : Remove spaces
REPLACE() : Replace text
🔥 3. UPPER() & LOWER()
SELECT UPPER(name) AS upper_name FROM employees;
SELECT LOWER(name) AS lower_name FROM employees;
🔥 4. LENGTH()
👉 Count number of characters
SELECT name, LENGTH(name) AS total_chars FROM employees;
🔥 5. CONCAT()
👉 Combine strings
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
🔥 6. SUBSTRING()
👉 Extract part of string
SELECT SUBSTRING(name, 1, 3) FROM employees;
✔️ Extracts first 3 characters
🔥 7. TRIM()
👉 Remove extra spaces
SELECT TRIM(' SQL ');
✔️ Result → SQL
🔥 8. REPLACE()
👉 Replace text inside string
SELECT REPLACE('I love Java', 'Java', 'SQL');
✔️ Result → I love SQL
🎯 9. Practice Tasks
1. Convert names to uppercase
2. Convert emails to lowercase
3. Combine first & last names
4. Extract first 4 letters of names
5. Remove extra spaces from city names
⚡ Mini Challenge 🔥
👉 Create employee usernames using:
first 3 letters of name + employee ID
Example:
Amit + 101 → Ami101
🔥 Mini Challenge Solution 💯
👉 Requirement:
Create username using:
- First 3 letters of name
- Employee ID
Example:
Amit + 101 → Ami101
✅ SQL Solution
SELECT name,
emp_id,
CONCAT(SUBSTRING(name, 1, 3), emp_id) AS username
FROM employees;
✅ Example Output
name : emp_id : username
Amit : 101 : Ami101
Neha : 102 : Neh102
Ravi : 103 : Rav103
🧠How It Works
👉 SUBSTRING(name, 1, 3)
Extracts first 3 letters
👉 CONCAT()
Combines extracted text with employee ID
🔥 Real-World Usage:
String functions are commonly used for:
👉 Username generation
👉 Email formatting
👉 Data cleaning
👉 Customer IDs 💯
COALESCE & NULL Handling in SQL
🧠1. What is NULL in SQL?
NULL means :
- 👉 missing value
- 👉 unknown value
- 👉 no data available
⚠️ NULL is NOT:
❌ 0
❌ Empty string
⚡ 2. Problems with NULL Values
NULL can affect:
- ❌ Calculations
- ❌ Comparisons
- ❌ Reports
Example 👇
SELECT salary + bonus
FROM employees;
If bonus is NULL → result becomes NULL ❌
========================================================
🔥 3. COALESCE Function
👉 Replaces NULL with another value
✅ Syntax
COALESCE(column, value)
⚡ 4. Basic Example
SELECT name,
COALESCE(bonus, 0) AS bonus
FROM employees;
✔️ If bonus is NULL → shows 0 instead
⚡ 5. Multiple Values with COALESCE
SELECT name,
COALESCE(phone, email, 'No Contact') AS contact
FROM employees;
✔️ Returns first non-NULL value
🔥 6. IS NULL & IS NOT NULL
👉 Find employees without bonus
SELECT * FROM employees
WHERE bonus IS NULL;
👉 Find employees with bonus
SELECT * FROM employees
WHERE bonus IS NOT NULL;
⚡ 7. NULL Handling in Aggregation
SELECT AVG(COALESCE(bonus, 0))
FROM employees;
✔️ Prevents NULL issues in calculations
🎯 8. Practice Tasks
1. Replace NULL bonus with 0
2. Find rows with NULL values
3. Find rows without NULL values
4. Use COALESCE with multiple columns
5. Calculate total salary safely using COALESCE
⚡ Mini Challenge 🔥
👉 Show employee total income:
salary + bonus
(If bonus is NULL → treat as 0)
🔥 Mini Challenge Solution 💯
👉 Requirement:
total_income = salary + bonus
If bonus is NULL → treat it as 0
✅ SQL Solution Using COALESCE
SELECT name,
salary,
COALESCE(bonus, 0) AS bonus,
salary + COALESCE(bonus, 0) AS total_income
FROM employees;
✅ Example Output
name : Amit, salary : 70000, bonus : 5000, total_income : 75000
name : Neha, salary : 50000, bonus : 0, total_income : 50000
name : Ravi, salary : 60000, bonus : 3000, total_income : 63000
🧠How It Works
👉 COALESCE(bonus, 0)
means:
- If bonus exists → use bonus
- If bonus is NULL → use 0
✅ CASE Statement in SQL
✅ CASE Statement in SQL
🧠1. What is CASE Statement?
- CASE is used for conditional logic in SQL
- It's like if-else in programming
- Helps categorize data
- Create custom labels
- Build smart reports
⚡ 2. Basic Syntax
SELECT column_name,
CASE
WHEN condition THEN result
ELSE result
END AS alias_name
FROM table_name;
📊 Example Table
name : Ajit, Neha, Sujit
salary : 70000, 40000, 55000
🔥 3. Basic CASE Example
👉 Categorize employees by salary
SELECT name, salary,
CASE
WHEN salary >= 60000 THEN 'High Salary'
WHEN salary >= 50000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS salary_category
FROM employees;
✅ Output
name : Ajit, Sujit, Neha
salary : 70000, 55000, 40000
salary_category : High Salary, Medium Salary, Low Salary
⚡ 4. CASE with Aggregation
👉 Count employees department-wise
SELECT department,
SUM(
CASE
WHEN salary > 50000 THEN 1
ELSE 0
END
) AS high_salary_count
FROM employees
GROUP BY department;
⚡ 5. CASE in ORDER BY
SELECT name, department
FROM employees
ORDER BY
CASE
WHEN department = 'IT' THEN 1
WHEN department = 'HR' THEN 2
ELSE 3
END;
🎯 6. Practice Tasks
1. Categorize salary as High/Low
2. Create age groups using CASE
3. Use CASE with GROUP BY
4. Count employees based on salary condition
5. Use CASE in ORDER BY
What will this query return?
SELECT name, salary,
CASE
WHEN salary >= 50000 THEN 'High'
ELSE 'Low'
END AS category
FROM employees;
A. Deletes salaries
B. Sorts employees
C. Add employees
D. Categorizes salary as High or Low
Ans : D
✅ UNION & UNION ALL in SQL
✅ UNION & UNION ALL in SQL
🧠1. What is UNION?
UNION is used to combine results from multiple SELECT queries
"Merge data from two tables into one result”
⚡ 2. Rules for UNION
- Same number of columns
- Same datatype/order of columns
📊 Example Tables
👨💼 employees_2025
Name
- Ajit
- Neha
👨💼 employees_2026
name
- Sujit
- Neha
🔥 3. UNION Example
SELECT name FROM employees_2025
UNION
SELECT name FROM employees_2025;
✔️ Removes duplicates automatically
✅ Result
name
- Ajit
- Neha
- Sujit
⚡ 4. UNION ALL
SELECT name FROM employees_2025
UNION ALL
SELECT name FROM employees_2026;
- Keeps duplicates
- Faster than UNION
✅ Result
name
- Ajit
- Neha
- Sujit
- Neha
🔥 5. UNION vs UNION ALL
UNION
- Removes duplicates
- Slower
- Doesn't keep all rows
UNION ALL
- Doesn't remove duplicates
- Faster
- Keeps all rows
⚡ 6. ORDER BY with UNION
SELECT name FROM employees_2025
UNION
SELECT name FROM employees_2026
ORDER BY name;
🎯 7. Practice Tasks
1. Combine employee names using UNION
2. Combine employee names using UNION ALL
3. Identify duplicate removal
4. Sort UNION result using ORDER BY
5. Compare UNION vs UNION ALL output
🧠Why UNION ALL?
👉 UNION → removes duplicates
👉 UNION ALL → keeps duplicates + faster
#union #union_alll
Filtering and Sorting data using SQL statements
Filtering & Sorting Data using SQL
Once you know the basics (SELECT, FROM, WHERE), filtering
and sorting helps you get the exact rows from tables .
- Use WHERE to filter rows.
- Combine with logical operators:
• AND: all
conditions true
• OR: any condition true
• NOT: negate condition
-- All conditions true (AND)
SELECT * FROM employees
WHERE department = 'Sales' AND salary > 50000;
-- Any condition true (OR)
SELECT * FROM employees
WHERE department = 'Sales' OR department = 'Marketing';
-- Negate condition (NOT)
SELECT * FROM employees
WHERE NOT department = 'HR';
- % = any sequence, _ = single char
• Names starting
with 'J'
• Names with 4 letters starting with 'J'
-- Names starting with 'J'
SELECT * FROM customers
WHERE name LIKE 'J%';
-- Names with four letters starting with 'J'
SELECT * FROM customers
WHERE name LIKE 'J___';
- Check if value matches any in list
SELECT * FROM
products WHERE category IN ('Electronics', 'Furniture');
4. Range Checking with BETWEEN
- Filter values in a range (inclusive)
SELECT * FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
- Find NULL:
SELECT * FROM
employees WHERE manager_id IS NULL;
- Find NOT NULL:
SELECT * FROM
employees WHERE manager_id IS NOT NULL;
- Ascending (default):
SELECT * FROM
employees ORDER BY salary;
- Descending:
SELECT * FROM
employees ORDER BY salary DESC;
SELECT * FROM
employees ORDER BY department, salary DESC;
List Of Table Operations in SQL
List of Table Operations in SQL [1. CREATE, 2. INSERT,
3.UPDATE, 4. ALTER, 5. DELETE, 6. DROP, 7. TRUNCATE ]
1.
CREATE : To define a new Table.
2.
INSERT : Add rows to the table.
3.
UPDATE : Modify existing rows in the
table.
4.
ALTER : Modify the structure of the
table.
5.
DELETE : Remove Rows from the table.
6.
DROP : Removes the entire table.
7.
TRUNCATE : Removes the all rows of the
table but it keeps the table structure.
1> CREATE : To define a new Table.
|
CREATE
TABLE jobs ( |
|
job_id INT PRIMARY KEY, |
|
job_title VARCHAR(100), |
|
job_description TEXT, |
|
min_salary DECIMAL(10, 2), |
|
max_salary DECIMAL(10, 2) |
|
); |
2 INSERT : Add rows to the table
VALUES
(100, ‘Manager’,
‘Manage the Team', 800000, 1500000);
3> UPDATE : Modify existing rows in the
table.
UPDATE jobs SET min_salary = 100000
WHERE job_id = 100;
Note : It will change the min salary to 100000 from 800000 for the job_id 100.
4> ALTER : Modify the structure of the table.
ALTER TABLE jobs ADD COLUMN dept_id INT;
5> DELETE : Remove Rows from the table
DELETE FROM jobs WHERE job_id = 100;
6> DROP : Removes the entire table.
DROP TABLE jobs;
7> TRUNCATE : Removes the all rows of the
table but it keeps the table structure
TRUNCATE TABLE jobs;
Note : > It removes all rows from the
table.
Ø It
retains the Table Structure
Ø It
is faster then DELETE statement
The "Dual Table" in Oracle
About Oracle Buffer
- All Commands of SQL are typed at the SQL prompt.
- Only one SQL statement is managed in the SQL buffer.
- The current SQL statement replaces the previous SQL statement in the buffer.
- The SQL statements can be divided into different lines within the SQL buffer.
- Only one line i.e, the current line can be active at a time in the SQL buffer.
- At SQL prompt, editing is possible only in the current SQL buffer line.
- Every statement of SQL should be terminated using semi colon ";".
- One sql statement can contain only one semi colon.
- To run the previous or current SQL statement in the bufer type "/" at SQL prompt.
- To open the SQL editor type "ED" at SQL prompt.
Introduction to SQL
- SQL usually pronounced as “Sequel” stands for Structured Query
Language.
- SQL is the native language of the Oracle Server. It is the language
used to communicate with the database. Again SQL consists of SQL
statements and SQL*Plus commands. SQL statements are used to talk to the
database. When you enter a SQL statement, it is stored in a part of the
memory called the SQL Buffer and remains there until a new statement is
entered. SQL*Plus is an Oracle tool that recognizes and submits
- SQL statements to the Oracle server for execution and contains its own
command language.
- It is very easy to write, it can be used by all kinds of users with
little or not programming experience.
- It is a non-procedural language.
- It reduces the amount of time required for creating and maintaining
systems.
- It is based on American National Standards Iinstitute (ANSI) standard
SQL.
- It manipulates data and tables definition in the database.
- It is entered into SQL buffer on one or more lines.
- It does not have a continuation character.
- It cannot be abbreviated.
- It uses a termination character to execute command immediately.
- Uses functions to perform some formatting.
- Recognizes SQL statements and sends them to the server.
- It accepts SQL input from files.
- It provides a line editor for modifying SQL statements.
- It controls environmental settings.
- Accesses local and remote databases.
- It doesn’t allow manipulation of values in the database.
- It is entered one line at a time and is not stored in the SQL buffer.
- Has a dash(-) as a continuation character if command exceed one line.
- Doesn’t require any termination character, commands are executed
immediately.
- It uses commands to format data.
- SQL is a high level language that provides a greater degree of
abstraction than procedural languages. It is designed so that the
programmer can specify what data is needed but need not specify how to
retrieves it.
- Applications written in SQL can be easily ported across systems.
- SQL as a language is independent of the way it is implemented
internally.
- The language even being simple and easy to learn can handle complex
situations.
- It is not just a query language, it can be used to define data
structures, control access to the data and delete, insert, modify occurrences
of the data.
- The results to be expected are well defined i.e, there is no ambiguity
about the way a query will interpret the data and produce the result.
- Querying data.
- Updating, inserting and deleting database objects.
- Controlling access to the database.
- Providing data integrity and consistency.
- Data Definition Language (DDL)
- Data Manipulation Language (DML)
- Transaction Control Lauguage (TCL)
- Data Control Language (DCL)
- CREATE statement.
- ALTER statement.
- DROP statement.
- RENAME statement.
- TRUNCATE statement.
- INSERT statement.
- UPDATE statement.
- DELETE statement.
- COMMIT statement.
- ROLLBACK statement.
- SAVEPOINT statement.
- GRANT statement.
- REVOKE statement.