0% found this document useful (0 votes)
18 views6 pages

SQL Commands and Queries Explained

The document contains a series of SQL questions and answers covering various SQL commands, operators, and clauses. It includes multiple-choice questions about SQL functionalities like data retrieval, filtering, sorting, and aggregate functions, along with assertions and reasons. Additionally, it provides SQL queries for specific tasks related to an EMPLOYEE table, demonstrating practical applications of the discussed concepts.

Uploaded by

vishuddha2769u
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

SQL Commands and Queries Explained

The document contains a series of SQL questions and answers covering various SQL commands, operators, and clauses. It includes multiple-choice questions about SQL functionalities like data retrieval, filtering, sorting, and aggregate functions, along with assertions and reasons. Additionally, it provides SQL queries for specific tasks related to an EMPLOYEE table, demonstrating practical applications of the discussed concepts.

Uploaded by

vishuddha2769u
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1. Which SQL command is used to retrieve data from a database?

A) INSERT B) DELETE C) SELECT D) UPDATE

Answer: C) SELECT

Q2. Which operator is used to filter records that match multiple specific values?
A) LIKE B) BETWEEN C) IN D) OR

Answer: C) IN

Q3. The WHERE clause is used to:


A) Group rows B) Filter rows C) Sort rows D) Join tables

Answer: B) Filter rows

Q4. Which SQL keyword is used to sort the result set?


A) SORT B) ORDER BY C) GROUP BY D) HAVING

Answer: B) ORDER BY

Q5. To filter data for a range of values, we use:


A) BETWEEN B) JOIN C) IN D) OR

Answer: A) BETWEEN

Q6. The GROUP BY clause is used with:


A) INSERT B) Aggregate Functions C) WHERE D) ORDER BY

Answer: B) Aggregate Functions

Q7. Which of the following is NOT an aggregate function?


A) COUNT ()B) SUM() C) AVG() D) WHERE()

Answer: D) WHERE()

Q8. The HAVING clause is used to:


A) Filter groups B) Sort records C) Filter rows before grouping

D) Insert records

Answer: A) Filter groups

Q9. Which statement retrieves unique values?


A) SELECT ALL B) SELECT * C) SELECT DISTINCT D) SELECT UNIQUE

Answer: C) SELECT DISTINCT


Q11. The LIKE 'A%' condition will return:
A) Records starting with A B) Records ending with A
C) Records containing A anywhere D) Records where A is in the middle

Answer: A) Records starting with A

Q12. Which symbol is used for pattern matching for any number of characters in LIKE?
A) _ (underscore) B) % (percent) C) * (asterisk) D) & (ampersand)

Answer: B) % (percent)

Assertion and Reason Questions - SQL

A) Both A and R are true, and R is the correct explanation of A.


B) Both A and R are true, but R is not the correct explanation of A.
C) A is true, but R is false.
D) A is false, but R is true.

Question 1

Assertion (A): The WHERE clause is used to filter rows before grouping takes place.
Reason (R): The HAVING clause filters groups after applying aggregate functions.

Answer: A) Both A and R are true, and R is the correct explanation of A.

Question 2

Assertion (A): The ORDER BY clause sorts the rows returned by a query.
Reason (R): GROUP BY is used to arrange rows in alphabetical order.

Answer: C) A is true, but R is false.

Question 3

Assertion (A): The IN operator is used to filter rows that match any value in a given list.
Reason (R): The IN operator allows the use of aggregate functions like SUM or AVG.

Answer: C) A is true, but R is false.

Question 4

Assertion (A): The HAVING clause can be used without the GROUP BY clause.
Reason (R): HAVING can act as a filter for aggregated conditions even without grouping.

Answer: A) Both A and R are true, and R is the correct explanation of A.

Question 5

Assertion (A): The BETWEEN operator includes both boundary values specified in the
condition.
Reason (R): The BETWEEN operator works only with numeric columns.
Answer: C) A is true, but R is false.

Question 6

Assertion (A): The DISTINCT keyword helps remove duplicate records from the result set.
Reason (R): Using DISTINCT slows down query execution as duplicates are retained.

Answer: C) A is true, but R is false.

Question 7

Assertion (A): The LIKE operator is used to search for patterns in text fields.
Reason (R): The % symbol in LIKE represents any sequence of characters.

Answer: A) Both A and R are true, and R is the correct explanation of A.

Question 8

Assertion (A): COUNT(*) counts only non-null values from a column.


Reason (R): COUNT(column_name) excludes NULL values while counting.

Answer: D) A is false, but R is true.

Question 9

Assertion (A): The GROUP BY clause can be used with aggregate functions like SUM() and
AVG().
Reason (R): Without GROUP BY, aggregate functions operate on the entire table.

Answer: A) Both A and R are true, and R is the correct explanation of A.

Question 10

Assertion (A): The AND operator is used when all conditions specified must be true.
Reason (R): The OR operator is used to combine mutually exclusive conditions.

Answer: B) Both A and R are true, but R is not the correct explanation of A.

Write a SQL query for the following:


Table: EMPLOYEE

EmpID Name Department Salary Age City JoiningDate

101 John HR 55000 28 New York 2018-05-23

102 Priya IT 75000 32 Delhi 2017-11-12

103 Amir IT 72000 35 Mumbai 2019-03-15


EmpID Name Department Salary Age City JoiningDate

104 Sara Finance 68000 30 London 2020-07-01

105 Vikram HR 58000 29 Delhi 2016-01-10

106 Emma IT 80000 27 New York 2018-09-20

107 Raj Finance 67000 33 Mumbai 2017-06-18

108 Anjali HR 60000 31 Delhi 2019-12-05

1. Display all employees with Salary greater than 60000.


SELECT * FROM EMPLOYEE WHERE Salary > 60000;
2. Show employees who belong to the IT department and have Salary
between 70000 and 80000.
SELECT * FROM EMPLOYEE WHERE Department = 'IT' AND Salary BETWEEN
70000 AND 80000;
3. List employees whose name starts with 'A'.
SELECT * FROM EMPLOYEE WHERE Name LIKE 'A%';
4. Find employees who work in 'Delhi' or 'New York'.
SELECT * FROM EMPLOYEE WHERE City IN ('Delhi', 'New York');
5. Show employees ordered by Salary in descending order.
SELECT * FROM EMPLOYEE ORDER BY Salary DESC;
6. Display total salary paid to employees in each department.
SELECT Department, SUM(Salary) AS Total_Salary FROM EMPLOYEE GROUP
BY Department;
7. Find the maximum salary in each city.
SELECT City, MAX(Salary) AS Max_Salary FROM EMPLOYEE GROUP BY City;
8. Show departments having more than 2 employees.
SELECT Department, COUNT(*) AS Total_Employees FROM EMPLOYEE GROUP
BY Department HAVING COUNT(*) > 2;
9. List employees whose age is between 28 and 32.
SELECT * FROM EMPLOYEE WHERE Age BETWEEN 28 AND 32;
10. Find average salary of employees in the Finance department.
SELECT AVG(Salary) AS Avg_Salary FROM EMPLOYEE WHERE Department =
'Finance';
11. Display employees who joined after 2018.
SELECT * FROM EMPLOYEE WHERE JoiningDate > '2018-12-31';
12. Show employees whose name contains 'a' as the second character.
SELECT * FROM EMPLOYEE WHERE Name LIKE '_a%';
13. List cities with average salary greater than 60000.
SELECT City, AVG(Salary) AS Avg_Salary FROM EMPLOYEE GROUP BY City
HAVING AVG(Salary) > 60000;
14. Find total employees in each department.
SELECT Department, COUNT(EmpID) AS Total_Employees FROM EMPLOYEE
GROUP BY Department;
15. Show employees not from 'HR' or 'IT' departments.
SELECT * FROM EMPLOYEE WHERE Department NOT IN ('HR', 'IT');
16. Display employees whose name ends with 'a' and age is greater than 28.
SELECT * FROM EMPLOYEE WHERE Name LIKE '%a' AND Age > 28;
17. Find highest salary in the company.
SELECT MAX(Salary) AS Highest_Salary FROM EMPLOYEE;
18. Find minimum age of employees in each department.
SELECT Department, MIN(Age) AS Youngest_Age FROM EMPLOYEE GROUP BY
Department;
19. List employees whose salary is not between 60000 and 75000.
SELECT * FROM EMPLOYEE WHERE Salary NOT BETWEEN 60000 AND 75000;
20. Display department-wise average age, but only for departments where
average age is above 30.
SELECT Department, AVG(Age) AS Avg_Age FROM EMPLOYEE GROUP BY
Department HAVING AVG(Age) > 30;
22. Show employees whose name starts with 'P' or ends with 'm'.
SELECT * FROM EMPLOYEE WHERE Name LIKE 'P%' OR Name LIKE '%m';
23. Find total number of employees city-wise, ordered by total employees
descending.
SELECT City, COUNT(*) AS Total_Employees FROM EMPLOYEE GROUP BY City
ORDER BY Total_Employees DESC;
24. List departments where the maximum salary exceeds 70000.
SELECT Department, MAX(Salary) AS Max_Salary FROM EMPLOYEE GROUP BY
Department HAVING MAX(Salary) > 70000;
25. Display employees who are from 'Mumbai' and age is exactly 35.
SELECT * FROM EMPLOYEE WHERE City = 'Mumbai' AND Age = 35;
26. Show all employees along with their annual salary (Salary × 12) using
alias.
SELECT Name, Salary, (Salary * 12) AS Annual_Salary FROM EMPLOYEE;

Common questions

Powered by AI

Using aggregate functions with the GROUP BY clause transforms the data retrieval process into summarizing data for each category defined in the grouping. For instance, calculating the total salary paid within each department involves grouping the dataset by department and utilizing SUM(Salary) to compute department-specific totals . This approach streamlines the analysis of large datasets by categorizing data into manageable subsets, allowing calculations specific to each group instead of the entire dataset, thus optimizing performance and readability . It enables businesses to efficiently collate insights like departmental budgets and staffing requirements based on cumulated employee data. Combined with the ORDER BY clause, it enhances data presentation and interpretation further .

A SQL query might use both WHERE and HAVING clauses when the aim is to filter records before and after aggregation, respectively. For example, a query that selects departments with more than ten employees whose salary exceeds a certain amount might look like this: SELECT Department, COUNT(*) FROM EMPLOYEE WHERE Salary > 50000 GROUP BY Department HAVING COUNT(*) > 10. Here, WHERE filters before aggregation by excluding lower-salary employees, while HAVING excludes less populous departments post-aggregation . Combining these clauses allows for more granular and efficient dataset refinement, facilitating complex data extractions and insights that cannot be achieved by either clause alone .

The WHERE clause is used to filter rows before any grouping occurs, meaning it is applied to individual rows in the database. In contrast, the HAVING clause filters the results of an aggregated query after the grouping has been applied . While WHERE takes effect prior to aggregation, HAVING applies conditions on aggregated data like COUNT(), SUM(), etc., after the data has been grouped . This means HAVING is specifically used with GROUP BY to filter out data grouped by certain fields .

The ORDER BY clause in SQL is used to sort a result set of a query by one or more columns either in ascending (ASC) or descending (DESC) order. This feature is pivotal for improving data readability, allowing results to be presented in a meaningful sequence. For instance, ordering employees by salary in descending order presents the highest salaries first, aiding in analyses like identifying top earners efficiently . When sorting large datasets, it's important to consider the performance impact, as sorting operations like ORDER BY can be resource-intensive and may necessitate additional time or server resources. Database optimization indexes can mitigate performance issues by reducing the time complexity of sorting operations .

The BETWEEN operator in SQL is used to filter the dataset for any records within a specified range of values, inclusive of the boundary values. For example, the condition 'WHERE Age BETWEEN 28 AND 32' will include ages 28 and 32 in the result set. This inclusivity of boundary values makes it useful for queries needing exclusive ranges. It functions seamlessly with numeric, date, and text data types for specifying intervals . However, a common misconception is that BETWEEN can potentially work only with numeric values, which is false since it can also apply to dates and times .

Aggregate functions such as COUNT(), SUM(), and AVG() compute a single result from a set of input values. These functions can be combined with the GROUP BY clause to return a separate result for each group, which allows for aggregation of data divided across specific categories or columns. The GROUP BY clause enables these aggregate functions to process and summarize data effectively by grouping it into subsets that the functions then evaluate . This interaction is crucial for reporting statistical insights like total sales per department or average salary per city, where data needs to be grouped and then aggregated . Without GROUP BY, aggregate functions would operate over the entire dataset rather than specific subgroups based on distinct values of a column .

The LIKE operator in SQL is used for pattern matching within text fields, offering flexibility in searching for specific string patterns. The % symbol represents any sequence of characters, while the _ (underscore) symbol denotes a single character. An advantage of using LIKE is its ability to handle complex text queries where precise matching is difficult. However, LIKE can be slower than direct equality conditions due to the complexity of pattern matching. It also may not use indexes efficiently in certain database implementations, which could affect performance with large datasets . These pattern-matching capabilities are useful in scenarios such as filtering rows where names start with a certain letter or have specific character structures within text fields .

The SELECT DISTINCT statement in SQL is used to retrieve unique values from a dataset by removing duplicates, while a regular SELECT statement returns all data, including duplicate entries. Using SELECT DISTINCT is beneficial when you want to evaluate or report distinct entries, such as when determining all unique cities from a list of employees' records . This can be particularly useful in scenarios like eliminating redundancy from datasets to ensure better data analysis and storage efficiency. However, it may slow down the query execution slightly due to the need to filter out duplicates .

SQL JOIN operations are essential in complex queries for combining rows from different tables based on related columns, allowing for comprehensive data analysis across multiple data sources. They enable datasets to be 'joined' or brought together, based on commonalities such as primary keys, providing a more rounded view of data relationships. However, JOIN operations can significantly impact query performance, especially as the number of joined tables or the size of the tables increases. This is due to the complexity and volume of data processed in matching rows across tables. Optimization techniques, such as indexing on join keys and limiting the number of columns returned, can mitigate performance drawbacks. This is crucial in transactional databases where real-time performance is necessary . Complex queries often require careful optimization to balance detailed data retrieval needs against processing constraints.

The SQL IN operator is used to filter records to match any value in a specified list and is typically more concise and easier to read than using multiple OR conditions. Using IN is beneficial especially when the list of values is long, as it simplifies the query significantly. For example, to find employees who work in 'Delhi' or 'New York', you could write: SELECT * FROM EMPLOYEE WHERE City IN ('Delhi', 'New York') instead of using multiple OR conditions. This enhances query readability and maintenance . The IN operator is a more succinct alternative to chaining multiple OR conditions, aiding in clearer stakeholder comprehension of the query logic and reducing chances of errors in listing conditions .

You might also like