Unit-2 Important Questions & Answers (1)
Unit-2 Important Questions & Answers (1)
UNIT-2
10M Q &A
In SQL, string conversion functions are used to manipulate and convert data types, particularly converting
between strings and other data types, or modifying strings themselves. Here are some commonly used SQL string
conversion functions along with examples:
1. CAST() Function
The CAST() function is used to convert one data type to another. It can be used for converting strings to integers,
dates, etc.
Syntax:
sql
Copy code
CAST(expression AS data_type)
Example:
sql
Copy code
SELECT CAST('2024-10-17' AS DATE) AS ConvertedDate;
2. CONVERT() Function
The CONVERT() function is similar to CAST() but provides more formatting options, especially for date and
time.
Syntax:
sql
Copy code
CONVERT(data_type, expression [, style])
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 1 of 17
Example:
sql
Copy code
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS USFormattedDate;
Syntax:
sql
Copy code UPPER(string)
LOWER(string)
Example:
sql
Copy code
SELECT UPPER('hello world') AS UppercaseString,
LOWER('HELLO WORLD') AS LowercaseString;
Syntax:
sql
Copy code LTRIM(string)
RTRIM(string)
Example:
sql
Copy code
SELECT LTRIM(' Hello World') AS TrimmedLeft,
RTRIM('Hello World ') AS TrimmedRight;
5. TRIM() Function
The TRIM() function is used to remove both leading and trailing spaces from a string.
Syntax:
sql
Copy code TRIM(string)
Example:
sql
Copy code
SELECT TRIM(' Hello World ') AS TrimmedString;
Syntax:
sql
Copy code
SUBSTRING(string, start_position, length)
Example:
sql
Copy code
SELECT SUBSTRING('Hello World', 1, 5) AS SubStringResult;
7. LEN() Function
The LEN() function returns the length of a string.
Syntax:
sql
Copy code LEN(string)
Example:
sql
Copy code
SELECT LEN('Hello World') AS StringLength;
8. REPLACE() Function
The REPLACE() function replaces all occurrences of a specified substring with another substring.
Syntax:
sql
Copy code
REPLACE(string, old_substring, new_substring)
Example:
sql
Copy code
SELECT REPLACE('Hello World', 'World', 'SQL') AS ReplacedString;
9. CONCAT() Function
The CONCAT() function is used to concatenate two or more strings.
Syntax:
sql
Copy code
CONCAT(string1, string2, ...)
Example:
sql
Copy code
SELECT CONCAT('Hello', ' ', 'World') AS ConcatenatedString;
2.Write and explain the SQL functions (i)Date and Time(ii) Numeric.
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 3 of 17
ANS:
SQL provides a variety of functions for handling date and time data as well as numeric data. Below is an overview
of some commonly used functions in both categories, along with explanations and examples.
Syntax:
sql
Copy code
GETDATE()
Example:
sql
Copy code
SELECT GETDATE() AS CurrentDateTime;
2. DATEADD()
Adds a specified interval to a date.
Syntax:
sql
Copy code
DATEADD(interval, number, date)
Example:
sql
Copy code
SELECT DATEADD(DAY, 5, GETDATE()) AS NewDate;
This adds 5 days to the current date and returns the new date.
3. DATEDIFF()
Calculates the difference between two dates.
Syntax:
sql
Copy code
DATEDIFF(interval, start_date, end_date)
Example:
sql
Copy code
SELECT DATEDIFF(DAY, '2024-10-01', GETDATE()) AS DaysDifference;
This calculates the number of days between October 1, 2024, and the current date.
4. FORMAT()
Formats a date/time value according to a specified format.
Syntax:
sql
Copy code FORMAT(value,
format)
Example:
sql
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 4 of 17
Copy code
SELECT FORMAT(GETDATE(), 'dd/MM/yyyy') AS FormattedDate;
Syntax:
sql
Copy code YEAR(date)
MONTH(date) DAY(date)
Example:
sql
Copy code
SELECT YEAR(GETDATE()) AS CurrentYear,
MONTH(GETDATE()) AS CurrentMonth,
DAY(GETDATE()) AS CurrentDay;
This returns the current year, month, and day as separate columns.
6. CONVERT()
Used to convert a date to a specific format.
Syntax:
sql
Copy code
CONVERT(data_type, expression [, style])
Example:
sql
Copy code
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS USFormattedDate;
Syntax:
sql
Copy code
LAST_DAY(date)
Example:
sql
Copy code
SELECT LAST_DAY('2024-10-17') AS LastDayOfMonth;
Syntax:
sql
Copy code ABS(number)
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 5 of 17
Example:
sql
Copy code
SELECT ABS(-10) AS AbsoluteValue;
Syntax:
sql
Copy code
ROUND(number, decimal_places)
Example:
sql
Copy code
SELECT ROUND(123.4567, 2) AS RoundedValue;
3. CEILING()
Returns the smallest integer greater than or equal to a specified number.
Syntax:
sql
Copy code
CEILING(number)
Example:
sql
Copy code
SELECT CEILING(123.45) AS CeilingValue;
4. FLOOR()
Returns the largest integer less than or equal to a specified number.
Syntax:
sql
Copy code FLOOR(number)
Example:
sql
Copy code
SELECT FLOOR(123.45) AS FloorValue;
5. POWER()
Raises a number to a specified power.
Syntax:
sql
Copy code POWER(base,
exponent)
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 6 of 17
Example:
sql
Copy code
SELECT POWER(2, 3) AS PowerValue;
6. SQRT()
Returns the square root of a specified number.
Syntax:
sql
Copy code SQRT(number)
Example:
sql
Copy code
SELECT SQRT(16) AS SquareRoot;
This returns 4.
7. SUM()
Calculates the sum of a set of values.
Syntax:
sql
Copy code SUM(column)
Example:
sql
Copy code
SELECT SUM(Salary) AS TotalSalary FROM Employees;
8. AVG()
Calculates the average of a set of values.
Syntax:
sql
Copy code AVG(column)
Example:
sql
Copy code
SELECT AVG(Salary) AS AverageSalary FROM Employees;
9. COUNT()
Counts the number of rows that match a specified condition.
Syntax:
sql
Copy code COUNT(column)
Example:
sql
Copy code
SELECT COUNT(*) AS TotalEmployees FROM Employees;
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 7 of 17
3. Explain creating and modifying relations in SQL. With examples
ANS:
Creating and modifying relations (or tables) in SQL is fundamental for managing a database. Here’s a detailed
explanation of how to create, modify, and manage these relations.
Creating a Table
To create a table, you use the CREATE TABLE statement. This statement defines the table structure, including
the names and types of columns.
Syntax:
sql
Copy code
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
);
Example:
sql
Copy code
CREATE TABLE Employees ( EmployeeID
INT PRIMARY KEY, FirstName
VARCHAR(50) NOT NULL, LastName
VARCHAR(50) NOT NULL,
HireDate DATE,
Salary DECIMAL(10, 2)
);
In this example, we created an Employees table with five columns. The EmployeeID is defined as the primary
key, ensuring that each employee has a unique identifier.
Modifying a Table
You can modify an existing table using the ALTER TABLE statement. This allows you to add, modify, or delete
columns and constraints.
1. Adding a Column
Example:
sql
Copy code
ALTER TABLE Employees ADD
Email VARCHAR(100);
2. Modifying a Column
Example:
sql
Copy code
ALTER TABLE Employees
MODIFY COLUMN Salary DECIMAL(12, 2);
This changes the Salary column to allow for larger decimal values.
3. Dropping a Column
Example:
sql
Copy code
ALTER TABLE Employees DROP
COLUMN Email;
2. Modifying a Column:
sql
Copy code
ALTER TABLE Products
MODIFY COLUMN Price DECIMAL(15, 2);
3. Dropping a Column:
sql
Copy code
ALTER TABLE Products DROP COLUMN Stock
4. Explain about integrity constraints over relations.
ANS:
Integrity constraints are rules that ensure the accuracy and consistency of data in a relational database. They help
maintain the correctness of the data by enforcing specific conditions that the data must satisfy. Here are the main
types of integrity constraints in the context of relational databases:
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 9 of 17
1. Entity Integrity
Definition: This constraint ensures that each entity (row) in a table is unique and identifiable.
Key Points:
o Every table must have a primary key.
o The primary key must contain unique values, and it cannot contain NULL values.
2. Referential Integrity
Definition: This constraint ensures that relationships between tables remain consistent.
Key Points:
o Foreign keys are used to create links between tables.
o A foreign key in one table must match a primary key in another table or be NULL. This
prevents orphaned records and ensures valid relationships.
3. Domain Integrity
Definition: This constraint ensures that all values in a column fall within a defined domain or set of
acceptable values.
Key Points:
o Each column in a table must have a defined data type (e.g., integer, varchar).
o Constraints such as CHECK can be used to restrict values (e.g., age must be greater than 0).
4. User-Defined Integrity
Definition: These are specific rules defined by users based on business requirements.
Key Points:
o They can include complex constraints that might not fit into standard types, like ensuring that a
project start date must be before its end date.
o Implemented using triggers, stored procedures, or application logic.
5. Unique Constraints
Definition: This constraint ensures that all values in a column or a set of columns are unique across
the table.
Key Points:
o Unlike the primary key, a table can have multiple unique constraints.
o Columns with unique constraints can accept NULL values, but each NULL is considered distinct.
6. Check Constraints
Definition: This constraint allows for the specification of a condition that must be met for values in a
column.
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 11 of 17
o Benefits:
Accurate representation of data: It’s clear which fields have no data.
Easier data management: Specific queries can filter based on nulls, such as
SELECT * FROM Customers WHERE Phone IS NULL;.
2. Not Using Null Values
o Table Structure:
In SQL (Structured Query Language), operations are typically categorized into two main types: Data Definition
Language (DDL) and Data Manipulation Language (DML). Here’s a breakdown of each category along with
examples:
4. TRUNCATE: Used to remove all records from a table without logging individual row deletions. This
operation is faster than DELETE but cannot be rolled back.
o Example: Truncating the Employees table.
sql
Copy code
TRUNCATE TABLE Employees;
4. SELECT: Although primarily used to query data, it’s also considered part of DML as it retrieves data
from a table.
o Example: Selecting all employees from the Employees table.
sql
Copy code
SELECT * FROM Employees;
Arithmetic and logical operations in SQL are fundamental for manipulating data, allowing you to perform
calculations and control the flow of data. Let’s dive into both types of operations with examples.
Arithmetic Operations
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 13 of 17
Arithmetic operations are used to perform mathematical calculations. The main arithmetic operators in SQL are:
sql
Copy code
SELECT Item, Quantity, Price, (Quantity *
Price) AS TotalSales
FROM Sales;
Result:
sql
Copy code
SELECT SUM(Quantity) AS TotalQuantity
FROM Sales;
Result:
TotalQuantity
45
Logical Operations
Logical operations allow you to evaluate conditions and return boolean values (TRUE, FALSE, or
UNKNOWN). The main logical operators are:
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 14 of 17
Example of Logical Operations
1. Find Items with Quantity Greater than 15 and Price Less than 2.00
sql
Copy code
SELECT Item, Quantity, Price FROM
Sales
WHERE Quantity > 15 AND Price < 2.00;
Result:
2. Find Items that are Either Bananas or Have a Price Greater than 1.50
sql
Copy code
SELECT Item, Quantity, Price FROM
Sales
WHERE Item = 'Bananas' OR Price > 1.50;
Result:
sql
Copy code
SELECT Item, Quantity, Price FROM
Sales
WHERE NOT Item = 'Apples';
Result:
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 15 of 17
UNIT-2
2M Q&A
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 16 of 17
4. Define primary key. Give example.
ANS:
A primary key is a specific type of database constraint that uniquely identifies each record in a table. It ensures
that no two rows in the table can have the same value for the primary key column(s) and that the primary key value
cannot be NULL. This uniqueness constraint helps maintain data integrity and allows for efficient data retrieval.
Consider a table named Students that stores information about students in a school. Here’s how it might look:
StudentID FirstName LastName DateOfBirth
1 John Doe 2000-01-01
2 Jane Smith 1999-05-12
3 Mike Brown 2001-09-22
In this example:
The primary key is StudentID.
Each student has a unique StudentID, ensuring that no two students share the same ID, and it cannot
be NULL.
For example, in a relational database, if you have a "Customers" table and an "Orders" table, the
"Orders" table might have a foreign key that references the "Customers" table's primary key. Referential
integrity makes sure that every order in the "Orders" table corresponds to a valid customer in the "Customers"
table.
Prepared by: Pavan Kumar Ravinuthala, Asst. Prof., Dept. of CSE, PACE ITS, Vallur-523272. Page 17 of 17