DBMS Unit-2 Q&a
DBMS Unit-2 Q&a
10M Q &A
1. Explain SQL functions for string conversions with examples.
2. Write and explain the SQL functions (i)Date and Time(ii) Numeric.
3. Explain creating and modifying relations in SQL. With examples
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])
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
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.
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()
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()
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()
Syntax:
sql
Copy code
FORMAT(value, format)
Example:
sql
Copy code
SELECT FORMAT(GETDATE(), 'dd/MM/yyyy') AS FormattedDate;
These functions extract the year, month, and day from a date.
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)
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()
Syntax:
sql
Copy code
CEILING(number)
Example:
sql
Copy code
SELECT CEILING(123.45) AS CeilingValue;
4. FLOOR()
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)
Example:
sql
Copy code
SELECT POWER(2, 3) AS PowerValue;
6. SQRT()
Syntax:
sql
Copy code
SQRT(number)
Example:
sql
Copy code
SELECT SQRT(16) AS SquareRoot;
This returns 4.
7. SUM()
Syntax:
sql
Copy code
SUM(column)
Example:
sql
Copy code
SELECT SUM(Salary) AS TotalSalary FROM Employees;
8. AVG()
Example:
sql
Copy code
SELECT AVG(Salary) AS AverageSalary FROM Employees;
9. COUNT()
Syntax:
sql
Copy code
COUNT(column)
Example:
sql
Copy code
SELECT COUNT(*) AS TotalEmployees FROM Employees;
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;
Here’s a complete example illustrating creating a table, modifying it, and altering it further:
3. Modifying a Column:
sql
Copy code
ALTER TABLE Products
MODIFY COLUMN Price DECIMAL(15, 2);
4. 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:
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.
5. Explain domain constraints & key constraints with an example.
ANS:
In the context of databases and relational data models, domain constraints and key constraints are
important concepts used to maintain data integrity. Here's an explanation of both, along with examples:
Domain Constraints
Domain constraints define the allowable values for an attribute (or column) in a database table. These
constraints ensure that data entered into a column adheres to specific rules related to its type, format, or
range.
DDL commands are used to define, modify, and manage the structure of database objects such as
tables, indexes, and schemas. Common DDL operations include:
sql
Copy code
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
BirthDate DATE,
HireDate DATE
);
sql
Copy code
ALTER TABLE Employees
ADD Email VARCHAR(100);
sql
Copy code
DROP TABLE Employees;
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;
sql
Copy code
RENAME TABLE Employees TO Staff;
DML commands are used to manipulate data within existing database objects. Common DML
operations include:
sql
Copy code
INSERT INTO Employees (EmployeeID, FirstName, LastName, BirthDate, HireDate, Email)
VALUES (1, 'John', 'Doe', '1985-06-15', '2023-01-10', 'john.doe@example.com');
sql
Copy code
UPDATE Employees
SET Email = 'john.new@example.com'
WHERE EmployeeID = 1;
sql
Copy code
DELETE FROM Employees
WHERE EmployeeID = 1;
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 Operations
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:
Item Quantity Price TotalSales
Apples 10 2.00 20.00
Bananas 20 1.50 30.00
Oranges 15 1.75 26.25
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:
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:
Item Quantity Price
Bananas 20 1.50
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:
UNIT-2
2M Q&A
1. Explain any two TCL commands
2. Give brief description of DCL command.
3. Why does SQL allow duplicate tuples in a table or in a query result?
4. Define primary key. Give example.
5. What is the difference between primary key and foreign key?
6. Define referential integrity.
1. GRANT: This command is used to give users specific privileges to perform actions on database
objects (e.g., tables, views).
2. REVOKE: This command removes previously granted privileges from users, restricting their
access to certain database operations.
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.