Predict the output of the following SQL queries :
- SELECT TRIM(“ ALL THE BEST ”) ;
- SELECT POWER(5,2);
- SELECT UPPER(MID(“start up india”,10)); OR Consider a table “MYPET” with the following data : Table : MYPET
| Pet_id | Pet_Name | Breed | LifeSpan | Price | Discount |
|---|---|---|---|---|---|
| 101 | Rocky | Labrador Retriever | 12 | 16000 | 5 |
| 202 | Duke | German Shepherd | 13 | 22000 | 10 |
| 303 | Oliver | Bulldog | 10 | 18000 | 7 |
| 404 | Cooper | Yorkshire Terrier | 16 | 20000 | 12 |
| 505 | Oscar | Shih Tzu | NULL | 25000 | 8 |
Write SQL queries for the following :
- Display the Breed of all the pets in uppercase.
- Display the total price of all the pets.
- Display the average life span of all the pets.
🔒You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
🔒 Start your 14-day free trial to unlock the full solution →Part (a)Concept understanding — String Functions
String Functions: A First Look
Think of a string as a piece of text — a word, a sentence, a name, or even a single character. In computing, strings are everywhere: your name in a form, a product code in a database, a tweet, a paragraph in a document. String functions are the tools that let you work with that text: cut it, join it, clean it, search inside it, or change its appearance.
You already use these ideas in everyday life. When you take a long sentence and pick out just the first word, you are performing a "substring" operation. When you combine your first name and last name into a full name, you are "concatenating" two strings. When you check whether an email address contains an "@" symbol, you are "searching" within a string. String functions are just these familiar actions, given precise names and made available in software.
The Core Idea
A string function takes one or more strings as input and returns a new string or a piece of information about the string. The function does not change the original string — it produces a result based on it. This is important: the original data stays untouched unless you explicitly replace it.
Strings are treated as sequences of characters. Each character — letter, digit, space, punctuation — occupies a position. In most systems, counting starts at 1 (the first character is position 1), though some languages start at 0. Always check which convention your tool uses.
Common Types of String Functions
1. Changing Case
These functions convert text to uppercase or lowercase. They are useful when you want to compare names or addresses without worrying about whether someone typed "Delhi" or "delhi".
- UPPER or UCASE: converts all letters to capitals
- LOWER or LCASE: converts all letters to small letters
- PROPER or TITLE: capitalises the first letter of each word
2. Extracting Parts of a String
You often need to pull out a specific portion of text — the first name from a full name, the area code from a phone number, the year from a date.
- LEFT: returns a given number of characters from the start
- RIGHT: returns a given number of characters from the end
- MID or SUBSTRING: returns characters starting from a specified position for a specified length
3. Finding and Replacing
These functions let you search inside text and optionally replace what you find.
- FIND or INSTR: locates the position of one string inside another
- REPLACE: substitutes all occurrences of a substring with another string
- TRIM: removes extra spaces from the beginning and end of a string
4. Joining and Splitting
- CONCAT or the ampersand (&): joins two or more strings end to end
- SPLIT (in some systems): breaks a string into parts based on a delimiter (like a comma or space)
5. Measuring Length
- LEN or LENGTH: returns the number of characters in a string
Why They Matter
In any real-world data task — whether you are cleaning a customer list, generating reports, validating user input, or preparing data for analysis — you will work with text. String functions give you the power to:
- Standardise messy data (e.g., "john", "John", "JOHN" all become "John")
- Extract meaningful pieces from longer text (e.g., get the domain from an email) …
Part (b)Concept understanding — SQL Aggregate Functions
Imagine you have a giant box of receipts from a month of sales at a small shop. You don't want to look at every single receipt one by one — you want a single, useful number that summarises the whole pile. How much total money came in? What was the average sale? How many customers bought something? That instinct — to collapse a pile of raw details into one meaningful number — is exactly what an SQL aggregate function does.
In a database, a table might hold thousands of rows of data: one row for every sale, every student, every product. An aggregate function takes all those rows in a column and boils them down to a single value. It doesn't change the data; it answers a question about the whole set. The most common ones are COUNT, SUM, AVG, MIN, and MAX. Each one has a clear, everyday meaning.
COUNT tells you how many rows there are — like counting how many students are in a class list. SUM adds up all the numbers in a column — like totalling the marks of every student in an exam. AVG gives the average of those numbers. MIN and MAX find the smallest and largest values — the lowest temperature recorded or the highest sale of the day.
Aggregate functions work on a column of data, not across rows. You always write them as FUNCTION_NAME(column_name). For example, AVG(price) gives the average of all prices in that column.
The real power comes when you combine them with the GROUP BY clause. Without GROUP BY, an aggregate function summarises the entire table. With GROUP BY, you split the table into groups first, then apply the function to each group separately. Think of it like this: you don't just want the average sale for the whole year — you want the average sale per month. GROUP BY month creates twelve groups, and AVG(sale_amount) runs once for each group, giving you twelve averages.
This is why aggregate functions matter in business, economics, and any data-driven decision. A manager doesn't ask "what was every single transaction?" They ask "what was the total revenue last quarter?" or "which product category had the highest average rating?" Aggregate functions turn raw, overwhelming data into actionable summaries. …
Part (a)
TRIM(" ALL THE BEST ")removes the leading and trailing spaces →ALL THE BEST.POWER(5, 2)= 5² = 25.MID("start up india", 10)starts at the 10th character ('i') and runs to the end →india;UPPER("india")→INDIA.
SELECT TRIM(" ALL THE BEST "); -- ALL THE BEST
SELECT POWER(5,2); -- 25
SELECT UPPER(MID("start up india",10)); -- INDIA …
Part (a): TRIM(" ALL THE BEST ") = ALL THE BEST, POWER(5,2) = 25, UPPER(MID("start up india",10)) = INDIA.
Part (b): use UPPER(Breed), SUM(Price)=101000, and AVG(LifeSpan)=12.75 (NULL ignored).
Part (a)
(i) SELECT TRIM(" ALL THE BEST "); — TRIM() strips leading and trailing spaces from a string.
ALL THE BEST
(ii) SELECT POWER(5,2); — POWER(base, exp) returns base raised to exp, so 5² .
25
(iii) SELECT UPPER(MID("start up india",10)); — evaluate the inner function first. Counting from 1, the 10th character of start up india is i; with no length given MID takes everything to the end → india. UPPER() then makes it uppercase.
INDIA …
Showing the 12 most recent of 17 on this concept.
- CBSE 2026Set 91/41 markMCQQ.Which aggregate function in SQL returns the smallest value from a column in a table ? (A) MIN() (B) MAX() (C) SMALL() (D) LOWER()
›Reveal solutionSolution
The aggregate function that returns the smallest value from a column in SQL is MIN().
In SQL, aggregate functions are used to perform calculations on a set of rows and return a single summary value. They are a core part of querying databases, especially when you need to analyse data — finding totals, averages, counts, or extremes. Among these, the function that specifically returns the smallest value from a column is
MIN().The
MIN()function works on numeric, date, or text columns. For text, it returns the value that comes first alphabetically. For dates, it returns the earliest date. This makes it versatile for many real-world queries — for example, finding the lowest price in a products table, the earliest order date, or the shortest employee name.NoteThe
MIN()function ignores NULL values by default. If a column has NULLs, they are simply not considered in the result.Let’s look at the options given:
- (A) MIN() — Correct. This is the standard SQL aggregate function for the smallest value.
- (B) MAX() — Returns the largest value, not the smallest.
- (C) SMALL() — This is not a valid SQL aggregate function. No such function exists in standard SQL or in any major database system. …
- CBSE 2026Set 90/1/11 markQ.State whether the following statement is True or False : In SQL, an aggregate function returns multiple values for each column on which it is applied.
›Reveal solutionSolution
Aggregate functions in SQL collapse multiple rows into a single summary value per group. The statement is False.
Why aggregate functions exist
SQL aggregate functions exist to summarize data across rows. When you have a table with thousands of transactions and want to know the total sales, you don't want thousands of numbers back—you want one number that represents the sum. That's the entire purpose of aggregation: to reduce many values to a single, meaningful summary.
Think of it this way: if you ask "What is the average age of students in this class?", you expect one number as the answer, not a list repeating some value for each student. Aggregate functions work the same way.
How aggregate functions actually behave
The standard aggregate functions in SQL are:
Function Purpose Output COUNT()Counts rows Single number SUM()Adds values Single number AVG()Computes mean Single number MAX()Finds maximum Single value MIN()Finds minimum Single value Each of these takes multiple input rows and produces one output value.
For example:
SELECT AVG(salary) FROM employees;If the
employeestable has 500 rows, this query returns exactly one row with one value—the average salary across all 500 employees.What about GROUP BY?
When you use
GROUP BY, aggregate functions return one value per group, not one value per original row:SELECT department, AVG(salary) FROM employees GROUP BY department; ``` … - CBSE 2026Set 90/1/11 markMCQQ.What will be the result of the following SQL command ? SELECT LENGTH ('Data Base'); (Note : There is single space between the words Data and Base.) (A) 7 (B) 8 (C) 9 (D) Error
›Reveal solutionSolution
The
LENGTHfunction counts every character in the string including spaces, so'Data Base'returns 9.The
LENGTHfunction in SQL is one of the most straightforward string functions you'll encounter. It does exactly what its name suggests: it counts the number of characters in a string and returns that count as an integer. The beauty of this function lies in its simplicity, but that simplicity can sometimes trip up students who forget one crucial detail.When SQL evaluates
LENGTH('Data Base'), it examines the string character by character. The string contains:- The letter D
- The letter a
- The letter t
- The letter a
- A space character (this is the key!)
- The letter B
- The letter a
- The letter s
- The letter e
That gives us a total of nine characters. The space between "Data" and "Base" is not invisible to the function — it's a legitimate character that occupies a position in the string, just like any letter or number would. Many students instinctively think of spaces as "nothing" or as mere separators, but in the world of string processing, a space is as real as any other character. …
- CBSE 2026Set 90/1/11 markQ.State whether the following statement is True or False : The INSTR(string1, string2) function in SQL returns 0 if string2 is not present as a substring in string1.
›Reveal solutionSolution
The
INSTRfunction in SQL returns the starting position of a substring; if the substring is not found, it returns 0. Therefore, the statement is True.The
INSTRfunction in SQL is designed to locate the starting position of a specified substring (string2) within a larger string (string1). Understanding its behavior, especially when the substring is absent, is crucial for writing correct SQL queries. The core idea is that if a substring is found,INSTRgives you its 1-based starting index. If it's not found, it needs a distinct value to signal this absence, and0is the standard convention forINSTR.Let's break down how
INSTRworks.-
Understanding
INSTRFunctionality:The
INSTR(string1, string2)function searches for the first occurrence ofstring2withinstring1. It returns an integer representing the starting position ofstring2instring1. SQL string positions are typically 1-based, meaning the first character is at position 1, the second at position 2, and so on.For example:
SELECT INSTR('HELLO WORLD', 'WORLD'); -- This would return 7, because 'W' is the 7th character.SELECT INSTR('ANUMEDHA', 'NUM'); -- This would return 2, because 'N' is the 2nd character. -
Behavior When Substring is Not Found:
When
string2is not present anywhere withinstring1, theINSTRfunction cannot return a valid 1-based position. In such cases, it returns0to indicate that the substring was not found. This0acts as a clear signal for conditional logic in your SQL queries.For example:
SELECT INSTR('HELLO WORLD', 'Z'); -- This would return 0, because 'Z' is not in 'HELLO WORLD'. …
-
- CBSE 2026Set 90/1/11 markMCQQ.Q. 20 and Q. 21 are Assertion (A) and Reason (R) Type questions. Choose the correct option as : (A) Both (A) and (R) are True, and (R) correctly explains (A). (B) Both (A) and (R) are True, but (R) does not correctly explain (A). (C) (A) is True, but (R) is False. (D) (A) is False, but (R) is True. Assertion (A) : The output of the SQL query SELECT COUNT (name) FROM students; will differ from the output of SELECT COUNT () FROM students; if there are some NULL values in the name column. Reason (R) : COUNT(column_name) returns the count of NON NULL values in that column, whereas COUNT() returns the number of records in the table.
›Reveal solutionSolution
COUNT(column_name)excludes NULL values whileCOUNT(*)counts all rows; therefore the two queries will differ when the name column contains NULLs. Both assertion and reason are true, and the reason correctly explains the assertion.The heart of this question lies in understanding how SQL's
COUNTfunction behaves differently depending on what you pass to it.When you write
COUNT(*), you're asking SQL to count every row in the table, regardless of whether any particular column contains NULL values. It's a row counter, pure and simple.When you write
COUNT(column_name), you're asking SQL to count only those rows wherecolumn_nameis NOT NULL. SQL silently skips over any row where that column holds a NULL value.This distinction matters enormously in practice. Imagine a
studentstable with 100 rows, but 5 students have NULL in thenamecolumn (perhaps their names weren't recorded yet). Then:SELECT COUNT(*) FROM students;returns 100 (all rows)SELECT COUNT(name) FROM students;returns 95 (only non-NULL names)
Now let's evaluate the assertion and reason:
Assertion (A): "The output of
SELECT COUNT(name) FROM students;will differ fromSELECT COUNT(*) FROM students;if there are some NULL values in the name column."This is true. As we just saw, the presence of NULLs in the
namecolumn causesCOUNT(name)to return a smaller number thanCOUNT(*). … - CBSE 2025Set 91/41 markMCQQ.Which aggregate function in SQL displays the number of values in the specified column ignoring the NULL values ? (A) len() (B) count() (C) number() (D) num()
›Reveal solutionSolution
The
COUNT()aggregate function in SQL is used to display the number of values in a specified column, inherently ignoring NULL values.In SQL, aggregate functions are powerful tools designed to perform calculations on a set of rows and return a single summary value. These functions are fundamental for data analysis, allowing us to derive insights like sums, averages, maximums, minimums, and counts from large datasets. When dealing with real-world data, it's common to encounter
NULLvalues, which represent missing or unknown data. How theseNULLvalues are handled by aggregate functions is a crucial aspect of understanding their behavior.The question specifically asks for an aggregate function that counts the number of values in a column while ignoring
NULLentries. Among the standard SQL aggregate functions,COUNT()is precisely designed for this purpose.Let's break down how
COUNT()works:-
COUNT(column_name): When you specify a column name inside theCOUNT()function, likeCOUNT(EmployeeID)orCOUNT(ProductName), SQL will iterate through each row in that column. For every row where the specifiedcolumn_namehas a non-NULL value, it increments the count. Rows where thecolumn_nameisNULLare simply skipped and do not contribute to the total count. This is the exact behavior requested by the question. -
COUNT(*): It's important to distinguishCOUNT(column_name)fromCOUNT(*). TheCOUNT(*)function counts the total number of rows in the result set, regardless of whether any specific column in those rows containsNULLvalues. It essentially counts the rows themselves, not the non-NULL values within a particular column.
ImportantCOUNT(column_name)counts only non-NULL values in the specified column, whereasCOUNT(*)counts all rows, irrespective of NULLs in any column.Now, let's consider the other options provided: …
-
- CBSE 2025Set 90/1/11 markMCQQ.Which of the following is not an aggregate function in SQL? (A) COUNT(*) (B) MIN() (C) LEFT() (D) AVG()
›Reveal solutionSolution
LEFT() is a string manipulation function, not an aggregate function — it extracts characters from the left side of a string, while COUNT(*), MIN(), and AVG() all perform calculations across multiple rows.
Aggregate functions in SQL are designed to perform calculations on a set of values and return a single summary value. They work across multiple rows of data, collapsing them into one meaningful result. Think of them as tools that answer questions like "How many records are there?", "What's the smallest value?", or "What's the average?" — they digest entire columns of data and give you one number back.
COUNT(*) counts the total number of rows in a result set, including those with NULL values. It's the go-to function when you need to know "how many" of something exists in your database.
MIN() finds the smallest value in a column. Whether you're looking for the lowest price, the earliest date, or the minimum score, MIN() scans through all the rows and returns that single smallest value.
AVG() calculates the arithmetic mean of a numeric column. It adds up all the values and divides by the count, giving you the average — essential for understanding central tendencies in your data.
Now LEFT() operates on an entirely different principle. It's a string function that extracts a specified number of characters from the left side of a text string. For example, LEFT('Database', 4) would return 'Data'. Notice what's happening here: LEFT() works on a single string value at a time, not across multiple rows. It doesn't summarize or aggregate anything — it simply manipulates one piece of text. …
- CBSE 2024Set 90/1/11 markMCQQ.What will be the output of the following query ? SELECT SUBSTR(“G20 2023 INDIA”,5,4); (A) G20 2 (B) 2023 (C) INDI (D) 023
›Reveal solutionSolution
The query extracts a substring of length 4 starting from the 5th character of the given string, so the output is "2023".
The
SUBSTRfunction in SQL is used to extract a portion of a string. It takes three arguments: the original string, the starting position, and the length of the substring to be extracted. The starting position is counted from the left, beginning with 1 for the first character.In the query
SELECT SUBSTR("G20 2023 INDIA",5,4);, the string is "G20 2023 INDIA". Let's count the characters carefully:- Position 1: G
- Position 2: 2
- Position 3: 0
- Position 4: (space)
- Position 5: 2
- Position 6: 0
- Position 7: 2
- Position 8: 3
So starting from position 5, the characters are "2", "0", "2", "3". The length specified is 4, so we take exactly these four characters, giving us "2023".
NoteIn SQL, string positions typically start at 1, not 0. This is different from some programming languages like Python or C where indexing starts at 0.
Watch outA common mistake is to miscount the space at position 4. The space is a valid character and must be counted. If you forget the space, you might think position 5 is "0" instead of "2", leading to the wrong answer.
Now let's look at the options: …
- CBSE 2024Set 90/1/11 markMCQQ.Which MySQL string function is used to extract a substring from a given string based on a specified starting position and length ? (A) SUBSTRING_INDEX() (B) LENGTH() (C) MID() (D) TRIM()
›Reveal solutionSolution
The MID() function extracts a substring from a string by specifying a starting position and length.
When working with text data in MySQL, you often need to pull out just a portion of a string rather than the whole thing. Think of a database storing full names where you want only the first few characters, or product codes where specific segments carry meaning. MySQL provides several string functions for different slicing and extraction tasks, and understanding which does what is essential for efficient querying.
The function designed specifically to extract a substring based on both a starting position and a length is MID(). Its syntax is straightforward:
MID(string, start, length). You tell it which string to work with, where to begin counting (the position), and how many characters to grab from that point forward. For example,MID('Database', 5, 4)would return 'base' — starting at the 5th character and taking 4 characters total.Let's see why the other options don't fit:
-
SUBSTRING_INDEX() works differently — it splits a string based on a delimiter (like a comma or space) and returns everything before or after a specified occurrence of that delimiter. It doesn't use position and length; it uses pattern matching.
-
LENGTH() doesn't extract anything at all. It simply counts and returns the number of characters in a string, giving you a numeric value rather than a substring. …
-
- CBSE 2024Set 91/41 markMCQQ.In SQL, the aggregate function which will display the cardinality of the table is ____. (A) sum() (B) count() (C) avg() (D) sum()
›Reveal solutionSolution
The
count(*)function returns the total number of rows in a table, which is its cardinality.When we talk about the cardinality of a table in database terminology, we mean the number of rows (or tuples) it contains. It's a fundamental measure of the table's size — how many records exist in that relation. SQL provides a family of aggregate functions that perform calculations across multiple rows and return a single summary value, and understanding which one gives us cardinality is essential for querying databases effectively.
Aggregate functions operate on sets of values from a column (or columns) and collapse them into one result. The most common ones include:
sum()— adds up all the values in a numeric columnavg()— calculates the arithmetic mean of values in a numeric columncount()— counts rows or non-null valuesmax()andmin()— find the largest or smallest value
The question asks specifically which function reveals how many rows are in the table. The
count(*)function does exactly this: it counts every row in the table, regardless of whether individual columns contain null values or not. The asterisk*tells SQL to count all rows without filtering by any particular column's content. … - CBSE 2023Set 90/1/11 markMCQQ.To remove the leading and trailing space from data values in a column of MySql Table, we use (A) Left ( ) (B) Right ( ) (C) Trim ( ) (D) Ltrim ( )
›Reveal solutionSolution
Removing both leading and trailing spaces requires a function that works on both ends of the string; TRIM() does exactly that, while LTRIM() and RTRIM() handle only one side each.
Why TRIM() is the answer
When you store text data in a MySQL table, extra spaces can creep in—sometimes users accidentally type a space before or after their input, or data imports include padding. These invisible characters cause problems: searches fail, comparisons break, and your data looks messy.
MySQL gives you three functions to clean up whitespace:
- LTRIM() removes spaces from the left (leading) side only
- RTRIM() removes spaces from the right (trailing) side only
- TRIM() removes spaces from both ends
The question asks for a function that handles both leading and trailing spaces. That immediately tells us we need something that works on both ends simultaneously.
LEFT() and RIGHT() are completely different—they extract a specified number of characters from the left or right side of a string. They don't remove anything; they're substring functions. So options (A) and (B) are out.
LTRIM() only handles the left side. If your data is
" hello ", LTRIM() gives you"hello "with the trailing spaces still there. Option (D) is incomplete. … - CBSE 2023Set 90/1/11 markMCQQ.If the substring is not present in a string, the INSTR ( ) returns: (A) - 1 (B) 1 (C) NULL (D) 0
›Reveal solutionSolution
The
INSTR()function in SQL returns the starting position of a substring within a string. If the substring is not found, it returns 0, not NULL or -1. The correct answer is (D) 0.The Concept: Why
INSTR()Returns 0The
INSTR()function is a standard string function in SQL (used in Oracle, MySQL, and others) that searches for a substring inside a larger string. It returns the character position where the substring first appears, counting from 1. This is a positional index, not a boolean flag.The key intuition: in SQL, positions are 1-based. If the substring is the very first character, the result is 1. If it's the second character, the result is 2, and so on. But what happens when the substring simply isn't there? The function cannot return a valid position — so it returns 0, meaning "no match found." This is consistent with how many other SQL string functions (like
LOCATE()orPOSITION()) behave.Watch outA common mistake is to think
INSTR()returns -1 or NULL when no match is found, as some other programming languages do (e.g., Python'sstr.find()returns -1). But SQL'sINSTR()returns 0 — a clean, non-negative integer that fits naturally with 1-based indexing.Step-by-Step Reasoning
-
Understand the function signature.
INSTR(string, substring)returns the starting position of the first occurrence ofsubstringwithinstring. For example:INSTR('Hello World', 'World')returns7(since 'W' is the 7th character).INSTR('Hello World', 'o')returns5(the first 'o' is at position 5). -
Consider the case of no match.
If the substring does not appear anywhere in the string, there is no valid starting position. The function cannot return a position number (1, 2, 3, …), so it returns 0. This is the standard SQL convention.
-
Eliminate the other options. …
-
🎓Unlock everything free for 14 days
- ✓Full step-by-step solutions
- ✓Concept-first explanations
- ✓Methods, shortcuts & mistakes
- ✓PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.