(a) Shalini, who works as a database designer in the hotel industry, has created a table named Guest to keep track of guest details as shown below : Table : Guest
| GuestID | GuestName | RoomNumber | CheckInDate | Charges |
|---|---|---|---|---|
| G101 | Harish | 101 | 2025-04-03 | 3000 |
| G102 | Sunita | 101 | 2025-04-03 | 3000 |
| G103 | Ramesh | 102 | 2025-05-04 | 5000 |
| G104 | Bhumika | 103 | 2025-06-02 | 3500 |
Write a suitable SQL query for the following : I. Display last 3 characters of guest name in upper case. II. Display the name of the guest along with the day name of check-in date. III. Display the remainder when charges are divided by 1000. IV. Extract and display three characters, starting from the second character, of each guest name. OR (b) Consider the following table and write the output of the following SQL Queries. Table : ORDERS
| ORDERID | CUSTOMERNAME | TOTALAMOUNT | DISCOUNT | ORDERDATE |
|---|---|---|---|---|
| 101 | Hemant | 5000 | 10 | 2024-03-01 |
| 102 | Neha | 7000 | 15 | NULL |
| 103 | Keshav | 3000 | 5 | 2024-01-20 |
| 104 | Sandhya | 4500 | NULL | 2023-12-25 |
Write the output of the following SQL Queries : I. SELECT CUSTOMERNAME FROM ORDERS WHERE DISCOUNT IS NOT NULL; II. SELECT CUSTOMERNAME, DISCOUNT FROM ORDERS WHERE DISCOUNT BETWEEN 5 AND 10; III. SELECT MONTHNAME(ORDERDATE) FROM ORDERS WHERE ORDERDATE IS NOT NULL; IV. SELECT ORDERID, DAY(ORDERDATE) FROM ORDERS;
🔒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 — Database Querying
Database Querying: Asking Questions of a Data Collection
Think of a library. You walk in, and instead of wandering through endless shelves, you go to the librarian and say: "I need all books by R. K. Narayan published after 1980." The librarian knows exactly where to look, finds the relevant books, and hands you a short list. That act of asking — of specifying exactly what you want from a large, organised collection — is the essence of querying.
A database is like that library, but for digital information. It stores data in a structured way, typically in tables with rows and columns. A query is simply a question you ask of that database. You don't need to know where the data lives or how it's stored internally. You just need to state what you want.
The Precise Meaning
In formal terms, a database query is a request for data or information from a database. The request is written in a special language that the database understands. The most common such language is SQL (Structured Query Language), but the concept of querying exists in every database system.
When you query a database, you are doing one of four things:
- Retrieving data (the most common — "show me the customers who live in Delhi")
- Inserting new data ("add this new student record")
- Updating existing data ("change this address")
- Deleting data ("remove this old order")
For a commerce or humanities student, the retrieval part is where the real power lies. You are not just pulling out raw data — you are filtering, sorting, and combining it to get answers.
Why It Matters
A database without querying is like a library with the lights off. The data exists, but you cannot use it. Querying turns stored facts into actionable information.
Consider a small business owner who keeps customer records in a spreadsheet. Without querying, they might scroll through hundreds of rows to find customers who haven't purchased in six months. With a query, they type one request and get the answer instantly. That answer might lead to a targeted marketing campaign, which brings in revenue.
Querying is not about memorising commands. It is about thinking in terms of conditions and relationships. The skill is learning to translate a real-world question — "Which products are out of stock?" — into a precise, unambiguous request the database can process.
The Intuition Behind It
Every query has a simple structure at its core:
- What data do you want? (Which columns or fields?)
- Where is it? (Which table or collection?)
- Under what conditions? (Which rows match your criteria?)
If you can answer those three questions in plain English, you are already thinking like someone who queries databases. The technical language (SQL) is just a way to write those answers down so the computer understands.
A Real-World Example …
Part (a)
-- I. last 3 characters of guest name in upper case
SELECT UPPER(RIGHT(GuestName, 3)) FROM Guest;
-- II. guest name with the day name of check-in date
SELECT GuestName, DAYNAME(CheckInDate) FROM Guest;
-- III. remainder when charges are divided by 1000
SELECT MOD(Charges, 1000) FROM Guest;
-- IV. three characters starting from the 2nd character of each name
SELECT MID(GuestName, 2, 3) FROM Guest;
``` …
Part (a): use UPPER(RIGHT(...)), DAYNAME(...), MOD(...,1000) and MID(...,2,3) on the Guest table.
Part (b): outputs are I {Hemant,Neha,Keshav}; II {Hemant 10, Keshav 5}; III {March,January,December}; IV {101→1,102→NULL,103→20,104→25}.
Part (a)
I. Last 3 characters of guest name in upper case — RIGHT() takes the last 3 letters, UPPER() capitalises them.
SELECT UPPER(RIGHT(GuestName, 3)) FROM Guest;
Harish→ISH, Sunita→ITA, Ramesh→ESH, Bhumika→IKA.
II. Guest name with the day name of the check-in date — DAYNAME() returns the weekday.
SELECT GuestName, DAYNAME(CheckInDate) FROM Guest;
III. Remainder when charges are divided by 1000 — use MOD() (or the % operator).
SELECT MOD(Charges, 1000) FROM Guest;
3000→0, 3000→0, 5000→0, 3500→500.
IV. Three characters starting from the 2nd character — MID(str, start, length) (SQL positions start at 1).
SELECT MID(GuestName, 2, 3) FROM Guest;
``` …
- 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 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.The SELECT statement when combined with ____ clause, returns records without repetition. (A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULL
›Reveal solutionSolution
SQL's
DISTINCTkeyword filters out duplicate rows from query results, ensuring each record appears only once. The answer is (A).When you query a database table, you often retrieve multiple rows that may contain identical values across all selected columns. Think of a customer orders table where the same customer ID appears dozens of times—one for each order. If you only want to see which customers have placed orders (not how many times), you need a mechanism to collapse duplicates into a single representative row.
The
SELECTstatement by itself returns every row that matches your conditions, duplicates and all. SQL provides theDISTINCTkeyword specifically to eliminate repetition: it compares the entire result set row-by-row and keeps only unique combinations.How each option relates to SQL
-
DISTINCT – This is the standard SQL keyword placed immediately after
SELECTto remove duplicate rows. For example:SELECT DISTINCT customer_id FROM orders;returns each customer ID exactly once, no matter how many orders they placed.
-
DESCRIBE – A command (or keyword in some databases) used to show the structure of a table—its column names, data types, constraints—not to filter query results. It's a metadata inspection tool, not a result-set modifier.
-
UNIQUE – In SQL,
UNIQUEis a constraint applied to columns during table creation to enforce that no two rows have the same value in that column. It's not a clause you combine withSELECTto filter results. You might see it in:CREATE TABLE users (email VARCHAR(100) UNIQUE); …
-
- 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. …
-
- CBSE 2020Set 91/D1 markQ.Which clause is used with a SELECT command in SQL to display the records in ascending order of an attribute?
›Reveal solutionSolution
The
ORDER BYclause is used with theSELECTcommand in SQL to display records in ascending order of an attribute.When we work with databases using SQL (Structured Query Language), the
SELECTcommand is our primary tool for retrieving information. Imagine a vast library of books;SELECTis like asking the librarian to fetch specific books or details about them. However, when the librarian hands you the books, they might not be in any particular order – perhaps by the order they were found, or by some internal system. For us to make sense of the data, especially when dealing with many records, we often need them arranged in a logical sequence.This need for structured presentation is where ordering comes in. Displaying records in ascending order of an attribute means arranging them from the smallest value to the largest, or alphabetically from A to Z for text. For instance, if you're looking at a list of students, you might want them sorted by their roll numbers from lowest to highest, or by their names alphabetically. This makes the data much easier to read, analyze, and understand.
To achieve this specific ordering in SQL, we use a special clause called
ORDER BY. This clause is appended to theSELECTstatement and tells the database system exactly how we want the retrieved records to be sorted.ImportantThe
ORDER BYclause is crucial for presenting query results in a meaningful and organized manner, making data analysis and reporting much more efficient.Here's how the
ORDER BYclause works:- Specifying the Attribute: You must specify one or more attributes (columns) by which you want to sort the data. For example, if you have a table of
Studentswith columns likeRollNo,Name, andMarks, you could choose to sort byRollNoorName. - Ascending Order (ASC): By default, if you just specify an attribute with
ORDER BY, the records will be sorted in ascending order. However, it's good practice to explicitly use theASCkeyword to make your intention clear.ASCstands for Ascending. This means numbers will go from smallest to largest, and text will go from A to Z. …
- Specifying the Attribute: You must specify one or more attributes (columns) by which you want to sort the data. For example, if you have a table of
- CBSE 2019Set 90/1/11 markQ.Consider the following table ‘Transporter’ that stores the order details about items to be transported. Table : TRANSPORTERWrite SQL command for the following statement :
ORDERNO DRIVERNAME DRIVERGRADE ITEM TRAVELDATE DESTINATION 10012 RAM YADAV A TELEVISION 2019-04-19 MUMBAI 10014 SOMNATH SINGH FURNITURE 2019-01-12 PUNE 10016 MOHAN VERMA B WASHING MACHINE 2019-06-06 LUCKNOW 10018 RISHI SINGH A REFRIGERATOR 2019-04-07 MUMBAI 10019 RADHE MOHAN TELEVISION 2019-05-30 UDAIPUR 10020 BISHEN PRATAP B REFRIGERATOR 2019-05-02 MUMBAI 10021 RAM TELEVISION 2019-05-03 PUNE (viii) To display names of drivers whose names are three characters long.›Reveal solutionSolution
Use the
LENGTH()function in SQL to filter driver names that are exactly three characters long.String functions in SQL are powerful tools that let you manipulate and filter text data stored in your database. When you need to work with character-based columns—like names, addresses, or codes—these functions become indispensable. They allow you to search, measure, extract, and transform text in ways that would be tedious or impossible with simple equality checks.
In this problem, you're working with a table called TRANSPORTER that tracks delivery orders. Each row records details about a shipment: who's driving, what's being transported, where it's going, and when. The DRIVERNAME column holds the names of the drivers, and your task is to find those drivers whose names are exactly three characters long.
The key function here is
LENGTH(), which counts the number of characters in a string. When you writeLENGTH(DRIVERNAME), SQL evaluates the length of each driver's name in turn. You then use aWHEREclause to filter only those rows where the length equals 3.Looking at the table, you can see that most driver names are longer—RAM YADAV, SOMNATH SINGH, MOHAN VERMA, and so on. But one name stands out: RAM. It's exactly three characters, and that's the name your query should return.
NoteSome database systems use
LEN()instead ofLENGTH(). MySQL, PostgreSQL, and SQLite useLENGTH(), while SQL Server usesLEN(). Always check your database's documentation if a function doesn't work as expected. …
🎓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.