0% found this document useful (0 votes)
226 views31 pages

RDBMS 12 Question Answer

The document provides an overview of RDBMS concepts in MySQL, including definitions of databases, schemas, and constraints. It discusses the role of keys in relational databases, the importance of normalization to reduce data redundancy, and the features of MySQL as an RDBMS. Additionally, it includes various questions and answers related to database concepts, data types, and integrity constraints.

Uploaded by

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

RDBMS 12 Question Answer

The document provides an overview of RDBMS concepts in MySQL, including definitions of databases, schemas, and constraints. It discusses the role of keys in relational databases, the importance of normalization to reduce data redundancy, and the features of MySQL as an RDBMS. Additionally, it includes various questions and answers related to database concepts, data types, and integrity constraints.

Uploaded by

Radhika Shongi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT 1.

RDBMS CONCEPTS IN MYSQL

Chapter 1. RDBMS Concepts

Summary

A file in a file system is a container to store data in a computer.

File system suffers from Data Redundancy, Data Inconsistency, Data Isolation, Data

Dependence and Controlled Data sharing.

Database Management System (DBMS) is a software to create and manage databases. A database is a
collection of tables.

Database schema is the design of a database

A database constraint is a restriction on the type of data that that can be inserted into the table.

Database schema and database constraints are stored in database Catalog. Whereas the snapshot of
the database at any given time is the database instance.

A query is a request to a database for information retrieval and data manipulation


(insertion, deletion or update). It is written in Structured Query Language (SQL).

Relational DBMS (RDBMS) is used to store data in related tables. Rows and columns of a
table are called tuples and attributed respectively. A table is referred to as a relation.

Restrictions on data stored in a RDBMS is applied by use of keys such as Candidate Key,Primary Key,
Composite Primary Key, Foreign Key.

Primary key in a relation is used for unique identification of tuples.

Foreign key is used to relate two tables or relations.

Each column in a table represents a feature (attribute) of a record. Table stores the information for an
entity whereas a row represents a record.

Each row in a table represents a record. A tuple is a collection of attribute values that makes a record
unique.

A tuple is a unique entity whereas attribute values can be duplicate in the table.
A. Multiple choice questions

1. A database is a (a) organized collection of information that cannot be accessed, updated,


and managed (b) collection of data or information without organizing (c) organized

collection of data or information that can be accessed, updated, and managed (d)

organized collection of data that cannot be updated

2. Which of the following is not a valid SQL type? (a) float (c) numeric (c) decimal (d) character

3. In DBMS, table is known as _________ and row is known as __________. (a) relation, tuple

(b) tuple, tuple (c) tuple, relation (d) relation, relation

4. In any table, the data types describe the kind of _________ that it can contain. (a) table (b)

data (c) number (d) column

5. The SQL statement used to select data items from the database is (a) SELECT (b) USE (c)

ALTER (d) CREATE

6. The database can be renamed using __________ SQL statement (a) CREATE DATABASE (b)

RENAME DATABASE (c) DROP DATABASE (d) SELECT DATABASE

7. The syntax used to show all databases is (a) USE DATABASES (b) SELECT DATABASES (c)

SHOW DATABASES (d) DISPLAY DATABASE

8. In a database table the field which uniquely identifies each row in the table is known as

______ (a) primary key (b) unique key (c) composite key (d) foreign key
9. Foreign key is a _______ key in another table. (a) primary (b) unique (c) composite (d)

candidate key

10. The multiple columns that are used as primary key is known as (a) unique key (b)

composite key (c) foreign key (d) candidate key

11. Which of the following key is used to link between two tables (a) primary (b) foreign (c) composite
(d) unique

12. A primary key cannot be (a) Zero (b) foreign key (c) duplicate (d) NULL

B. Fill in the blanks

1. In DBMS, table is known as ______and row is known as ______.

2. Organized collection of data or information for accessing, updating and management is

known as __________ .

3. A relational database consists of a collection of _____________.

4. To see all available databases in MySQL; __________ command is used.

5. Data Definition language is the language which is used to defining the ______of relation.

6. In order to build a link between two tables, ___________is used.

7. In order to make multiple columns as a Primary Key, ___________ can be used.

8. Foreign key is a field in a table that is __________ in another table.


9. A Key which uniquely identifies each row in the table is known as __________.

10. A foreign key can be ________ or _______________. (null, duplicate)

C. State whether True or False

1. DBMS is an interface between Database application and database.

2. Using the SQL statement RENAME DATABASE; a database can be renamed.

3. To see all existing databases; SHOW DATABASES; syntax is used.

4. A Primary Key is basically a Column or Columns.

5. To make a link between two tables, We can use foreign key constraints.

6. A Primary Key can be NULL

7. A Foreign Key can not be Duplicate.

8. If multiple columns are used as Primary Key, it is known as Composite Key.

9. There could be two Primary keys constraints in a single table.

10. A Foreign Key can not have NULL value


D. Short answer questions.
1. What is file system? Write down limitations of file system.

Answer:A file system is a way of organizing and storing files on a computer or storage device. It
provides
a structure for naming, storing, and retrieving files.

Limitations of File System:


- Hierarchical structure can become complex and difficult to navigate
- File names and locations can be easily forgotten or lost
- Data redundancy and duplication can occur
- Security and access control can be challenging
- Scalability can become an issue with large amounts of data
- Data search and retrieval can be slow and inefficient

Note: These limitations have led to the development of alternative data storage and
management
systems, such as databases and content management systems.

2. Why foreign keys are allowed to have NULL values? Explain with an example.
Answer: Foreign keys are allowed to have NULL values because they might not always have a
matching
value in the referenced table.

Example:

Suppose we have two tables:

*Orders*

- OrderID (primary key)


- CustomerID (foreign key referencing the Customers table)
- OrderDate

*Customers*

- CustomerID (primary key)


- Name
- Address

In this example, the "CustomerID" field in the Orders table is a foreign key that references the
"CustomerID" in the Customers table. However, if an order is placed by a customer who hasn't
created
an account (a "guest" customer), there won't be a matching CustomerID in the Customers table.
In this
case, the CustomerID field in the Orders table would be NULL, indicating that there is no
associated
customer.

Allowing NULL values in foreign keys provides flexibility in handling such scenarios, where the
relationship between tables might not always exist.
3. What are the limitations of file system and how that are overcome by DBMS?
Answer: Limitations of File System:

1. Data Redundancy and Duplication


2. Data Inconsistency
3. Difficulty in Data Search and Retrieval
4. Data Security and Integrity Issues
5. Data Isolation and Scalability Issues

How DBMS overcomes these limitations:

1. *Data Redundancy and Duplication*: DBMS stores data in a single place, reducing duplication
and
ensuring data consistency.
2. *Data Inconsistency*: DBMS enforces data integrity constraints, ensuring data accuracy and
consistency.
3. *Data Search and Retrieval*: DBMS provides efficient search and retrieval mechanisms,
making data
access faster.
4. *Data Security and Integrity*: DBMS offers robust security features, access control, and
transaction
logging to ensure data integrity and security.

5. *Data Isolation and Scalability*: DBMS allows concurrent access, supports large data
volumes, and scales horizontally, ensuring data availability and performance.

Additionally, DBMS provides features like:


- Data Normalization
- Query Language (e.g., SQL)
- Transaction Management
- Concurrency Control
- Backup and Recovery ko

By overcoming these limitations, DBMS provides a more efficient, secure, and scalable way to
manage
data compared to traditional file systems.

4. What is database schema?


Answer :A database schema is the overall structure or organization of a database, including the
relationships between different data entities. It defines how data is stored, linked, and accessed
within a
database management system (DBMS).

A schema typically includes:

1. Tables or relations: Define the structure of data storage, including columns (fields) and data
types.
2. Relationships: Define how tables are connected, such as one-to-one, one-to-many, or many-to
-.many
relationships.
3. Indexes: Define how data is indexed for efficient retrieval.
4. Views: Define virtual tables based on queries.
5. Constraints: Define rules for data integrity, such as primary keys, foreign keys, and check
constraints.
6. Stored procedures: Define reusable code blocks for performing specific tasks.

Having a well-designed database schema is crucial for:

- Data organization and structure


- Data integrity and consistency
- Query performance and efficiency
- Scalability and maintainability
Schemas can be represented visually through entity-relationship diagrams (ERDs) or in code
through SQL scripts.

5. What is data redundancy and its associated problems?


Answer:Data redundancy refers to the duplication of data values in a database or file system,
where the
same data is stored in multiple places. This can occur due to various reasons like:

- Duplicate records
- Multiple copies of the same data in different tables or files
- Unnormalized data structures

Problems associated with data redundancy:


1. *Data inconsistency*: Updates to one copy of the data may not be reflected in other copies,
leading
to inconsistencies.
2. *Data duplication*: Storage space is wasted by storing multiple copies of the same data.
3. *Data updating difficulties*: Updating data in multiple locations can be time-consuming and
error-
prone.
4. *Data retrieval complexities*: Retrieving accurate data becomes challenging due to multiple
versions.
5. *Data security risks*: Multiple copies of sensitive data increase the risk of unauthorized
.access.
6. *Data maintenance challenges*: Maintaining data integrity and consistency becomes more
difficult.
7. *Performance issues*: Data redundancy can lead to slower query performance and data
retrieval.

To avoid these problems, data normalization techniques are used to eliminate data redundancy
and
ensure data consistency and efficiency.
6. How data redundancy problem is solved in DBMS?
Answer:In DBMS, data redundancy is solved through:

1. *Data Normalization*: Organizing data into tables and removing duplicates by splitting large
tables
into smaller ones.
2. *First Normal Form (1NF)*: Ensuring each table cell contains a single value.
3. *Second Normal Form (2NF)*: Moving redundant data to a separate table.
4. *Third Normal Form (3NF)*: Removing data that depends on another field's value.

5. *Higher Normal Forms*: Further normalization techniques, like Boyce-Codd Normal


Form(BCNF),
Fourth Normal Form (4NF), and Fifth Normal Form (5NF).
6. *Denormalization*: Controlled redundancy introduction for performance optimization.
7. *Indexing*: Creating indexes on columns to speed up data retrieval.
8. *Data Partitioning*: Dividing large tables into smaller, more manageable pieces.
9. *Data Compression*: Storing data in a compact format to reduce storage needs.
10. *Data Backup and Recovery*: Regular backups and recovery processes to ensure data
consistency.
By applying these techniques, DBMS minimizes data redundancy, ensuring data consistency,
reducing
storage needs, and improving data retrieval performance.

7. What is MYSQL and its features?


Answer: MySQL is a relational database management system (RDBMS) based on structured
query
language (SQL) queries ¹ ² ³:

- Open-source and free software


- Easy to use
- Strong data security layer
- Follows client/server architecture
- Supports multi-threading and can handle a large amount of data
- Available for many operating systems
- Allows transactions to be rolled back, commit, and crash recovery
- High efficiency and low memory leakage
- Provides very high-performance results
- Support for dual passwords

Some other features of MySQL include ² ⁴:

- Quick and reliable data access and manipulation


- Scalable and can work easily with small or large amounts of data
- Contains multiple data types
- Supports different character sets
- Can be run on various operating systems in several programming languages
- Comes with many client and utility programs
8. What are various data types available in MYSQL?
Answer:MySQL supports various data types, including ¹ ² ³ ⁴ ⁵:

- Numeric data types:


- Integer types: TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT
- Fixed-point types: DECIMAL, NUMERIC
- Floating-point types: FLOAT, DOUBLE
- Bit-value type: BIT
- Date and time data types:
- DATE
- DATETIME, TIMESTAMP
- TIME
- YEAR
- String data types:
- CHAR, VARCHAR
- BINARY, VARBINARY
- TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT
- TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB
- ENUM
- SET
- Spatial data types
- JSON data type
Each data type has its own specific characteristics and uses
9. Differentiate between: (a) Database state and database schema (b) Primary key and foreign
key (c)
Degree and cardinality of a relation
Answer: Here are the differences:

(a) Database state vs Database schema:

- Database state: Refers to the actual data stored in the database at a given point in time. It's the
current
set of values in the database.
- Database schema: Refers to the structure or organization of the database, including table
definitions,
relationships, and constraints. It's the blueprint or design of the database.
(b) Primary key vs Foreign key:
- Primary key (PK): A unique identifier for a record in a table, ensuring data consistency and
uniqueness.
It's a column or set of columns that uniquely identifies each row.
- Foreign key (FK): A field in a table that references the primary key of another table, establishing a
relationship between tables.
(c) Degree and cardinality of a relation:
- Degree: The number of attributes or columns in a relation (table).
- Cardinality: The number of tuples or rows in a relation (table).
Example:
- A relation (table) with 5 columns (attributes) has a degree of 5.
- A relation (table) with 10 rows (tuples) has a cardinality of 10.
In summary:
- Database state is the data, while schema is the structure.
- Primary key identifies a record, while foreign key links records between tables.
- Degree is the number of columns, and cardinality is the number of rows in a table.
10. Explain the terms (a) Relation (b) Domain (c) Tuple (d) Attribute (e) Degree (f) Cardinality (g)
Primary
Key (h) Foreign Key
Answer: Here are the explanations:
(a) Relation: A relation is a table in a database that contains a set of related data. It's a
fundamental
concept in relational databases.
(b) Domain: A domain is the set of possible values that an attribute can take. It defines the
range of
values for a specific attribute.
(c) Tuple: A tuple is a single row or record in a relation (table). It's a collection of values that
represent a
single entity or instance.
(d) Attribute: An attribute is a column or field in a relation (table). It defines a specific
characteristic or
feature of the data.
(e) Degree: The degree of a relation is the number of attributes (columns) it contains.
(f) Cardinality: The cardinality of a relation is the number of tuples (rows) it contains.
(g) Primary Key (PK): A primary key is a unique identifier for a tuple (row) in a relation. It's a
single
attribute or a set of attributes that uniquely identifies each tuple.
(h) Foreign Key (FK): A foreign key is an attribute in a relation that references the primary key of
another
relation. It establishes a relationship between two relations.
Example:
Consider a relation "Students" with attributes:
- Student_ID (Primary Key)
- Name
- Age
- Major
- Relation: Students
- Domain: The set of possible values for Age (e.g., 18-25)
- Tuple: A single row representing a student (e.g., John, 20, Computer Science)
- Attribute: Student_ID, Name, Age, Major
- Degree: 4 (four attributes)
- Cardinality: The number of students ( tuples) in the relation
- Primary Key: Student_ID
- Foreign Key: If another relation "Courses" has an attribute "Student_ID" that references the
Students
relation, it's a Foreign Key.
11. Describe the various integrity constraints?
Answer:Integrity constraints are rules that ensure the accuracy, consistency, and reliability of
data in a
database. The following are various types of integrity constraints:
1. *Entity Integrity*: Ensures that each row in a table has a unique primary key value.
2. *Referential Integrity*: Ensures that a foreign key value matches a primary key value in
another table.
3. *Domain Integrity*: Ensures that data values conform to the defined domain (e.g., format,
range, or
set of values).
4. *Unique Constraint*: Ensures that all values in a column or set of columns are unique.
5. *Check Constraint*: Ensures that data values meet specific conditions or rules (e.g., age > 18).
6. *Not Null Constraint*: Ensures that a column cannot contain null values.
7. *Default Constraint*: Provides a default value for a column when no value is specified.
8. *Primary Key Constraint*: Ensures that a primary key value is unique and not null.
These integrity constraints help maintain data consistency, prevent errors, and ensure that data is
reliable and trustworthy.

Chapter 2. Structured Query Language (SQL)


SUMMARY
 SQL is a domain-specific language that is used to manage relational databases.
 Currently almost all RDBMS such as MySQL, Oracle, Informix, SQL server, MS Access,

and Sybase uses SQL as their standard database language.

 SQL is easy to learn as the statements comprise of descriptive English words.

 SQL is a open source, interactive, portable, faster query processing, standardized and

universal language to work with with RDBMS.

 SQL is divided into five types like DDL, DML, DQL, TCL and DCL.

DDL (Data Definition Language) includes SQL statements such as, Create table, Alter table

and Drop table.

Create command is used to create database and its further objects like Table, View.

DML (Data Manipulation Language) includes SQL statements such as, insert, select,

update and delete.

A table is a collection of rows and columns, where each row is a record and columns

describe the feature of records.

DESCRIBE TABLE statement is used to view the structure of an already existing table

ALTER TABLE statement is used to make changes in the structure of a table like adding,

removing column and changing datatype of column(s). It is also used to apply/remove any

constraints like Primary Key, Foreign Key etc.

DROP statement is used to remove a database or a table permanently from the database

system.

TRUNCATE statement is used to delete all records from the table but table structure will

exist in database.

INSERT INTO statement is used to insert new records in any existing table

UPDATE statement is used to make required changes in records of any table.

DELETE statement is used to delete/remove one or more records from a table.

CREATE TABLE statement can also be used to create new table from existing tables/s.

RENAME statement is used to change the name of existing tables of other database
objects.

Views in any database is a special kind of virtual table that is created from one or more

table and having no data of its own.

WHERE clause in SQL query is used to enforce condition(s).

DISTINCT clause is used to eliminate repetition and display the values only once.

The BETWEEN operator defines the range of values inclusive of boundary values.

The IN operator selects values that match any value in the given list of values.

NULL values can be tested using IS NULL and IS NOT NULL.

ORDER BY clause is used to display the result of a SQL query in ascending or descending

order with respect to specified attribute values. By default, the order is ascending.

LIKE operator is used for pattern matching. % and _ are two wild card characters. The per

cent (%) symbol is used to represent zero or more characters. The underscore (_) symbol is

used to represent a single character.


CHECK YOUR PROGRESS

A. Multiple choice questions

1.Which of the following is not a valid aggregate function? (a) COUNT (b) COMPUTE (c) SUM

(d) MAX

2.DDL stands for (a) Data Describe Language (b) Definition Data Language (c) Data

Definition Language (d) Data Distinct Language

3.Which of the following SQL command is used to remove data from table (a) Collapse (b)

Remove (c) Alter (d) Delete

4.The records and structure of a table may be removed or deleted from the database using

which command? (a) Remove (b) Delete (c) Drop (d) Truncate

5.SQL ___ statement can be used to delete or drop existing databases in a SQL schema. (a)

Create Database (b) Rename Database (c) Drop Database (d) Select Database

6.Using DROP TABLE command in SQL (a) Drop the table structure (b) Drop the Integrity

constraints (c) Drop the Relationship (d) All of the above

7.Using DROP TABLE command in SQL (a) Drop the table structure (b) Drop the Integrity
constraints (c) Drop the Relationship (d) Noe of the above

8.TRUNCATE TABLE requires (a) Where Clause (b) Having Clause (c) Both A And B (d) None

of the above

9.Which of the following clause is used to add a Primary Key constraint after creating table

(a) Update (b) Add (c) Alter (d) Join

10. Which of the following clause is used to remove a primary key constraint (a) Delete (b)

Drop (c) Alter (d) Remove

11. Which of the following SQL statement is used to give result in sorted order (a) Sort By (b)

Order (c) Order By (d) Sort

12. Commands under DCL are (a) GRANT (b) REVOKE (c) Both A. and B. (d) None of the above

13. The SQL command to retrieve table records is (a) RETRIEVE (b) SELECT (c) CREATE (d)

ALTER

14. Which of the following operator is used for pattern matching in SQL? (a) BETWEEN

operator (b) LIKE operator (c) EXISTS operator (d) None of these

15. Which operator is used to check the absence of data in any column (a) EXISTS operator (b)

NOT operator (c) IS NULL operator (d) None of these

16. Which of the following keyword is used to select only unique values from any column (a)

DISTINCTIVE (b) UNIQUE (c) DISTINCT (d) DIFFERENT

B. Fill in the blanks

1. SQL is divided in ___________ category.

2. The _______ command is used to see the structure of table.

3. The _______ command is used to remove all records.

4. The _______ command is used to add an attribute in an existing table.

5. The _______ command is used to remove all records only from a table.

6. The _______ command is used to remove a attribute from a table.

7. A view is a special kind of _____________ table.

8. Views can be created form _________ or more tables.

9. Grant and Revoke are part of _____________ in SQL.


10. Commit and Savepoint are part of ___________ in SQL.

11. To sort the result of a query in descending order, we can use clause ______

12. To extract unique values from a column, user can use __________ clause.

C. State whether True or False

1. INSERT clause is used to add a Foreign key constraint.


2. ALTER clause is used to add a Primary key constraint after table is created.

3. DROP command is used to delete the structure of a table from the database.

4. Updation and deletion of records are part of DDL.

5. Insert into statement is useful to insert a new field in any table.

6. Aggregate functions are used to perform calculations on multiple values and returns a

single value.

7. Aggregate functions are mostly used with the SELECT statement.

8. DML is used to create a new database objects like table and view.

9. A new table can be created from existing table(s).

10. The name of any tables once its created and records are inserted cannot be change.

D. Short answers questions

1. What do you understand by SQL?


Ans:SQL (Structured Query Language) is a programming language designed for managing and
manipulating data stored in relational database management systems (RDBMS). It's used to
perform
various operations such as:
- Creating and modifying database structures (tables, indexes, views, etc.)
- Inserting, updating, and deleting data
- Querying data (retrieving specific data or aggregations)
- Managing user permissions and access control
SQL is a standard language for interacting with relational databases, and its commands and
syntax are
widely supported by various database management systems like MySQL, PostgreSQL, Microsoft
SQL
Server, Oracle, and many others.
Some common SQL commands include:
- SELECT (retrieve data)
- INSERT (add new data)
- UPDATE (modify existing data)
- DELETE (remove data)
- CREATE (create new database objects)
- DROP (delete database objects)
- ALTER (modify database objects)
SQL is an essential tool for database administrators, developers, and data analysts to manage
and
analyze data effectively.
2. SQL Statements are classified in how many ways?
Ans: SQL statements are classified into several categories, including:
1. *DDL (Data Definition Language)*: used to define and modify database structure, e.g.,
CREATE, ALTER,
DROP, TRUNCATE.
2. *DML (Data Manipulation Language)*: used to manipulate data, e.g., INSERT, UPDATE,
DELETE.
3. *DQL (Data Query Language)*: used to retrieve data, e.g., SELECT.
4. *TCL (Transaction Control Language)*: used to manage transactions, e.g., COMMIT,
ROLLBACK,
SAVEPOINT.
5. *DCL (Data Control Language)*: used to control access and permissions, e.g., GRANT,
REVOKE.
Note that some sources may group SQL statements slightly differently, but these five
categories are a
common way to classify SQL statements.
3. Differentiate between DDL and DML?
Ans:Here's a clear differentiation between DDL and DML:
*DDL (Data Definition Language)*
- Used to define and modify database structure
- Creates, alters, or drops database objects (tables, indexes, views, etc.)
- Defines relationships between tables
- Specifies data types, constraints, and storage parameters
- Examples: CREATE, ALTER, DROP, TRUNCATE, COMMENT
*DML (Data Manipulation Language)*
- Used to manipulate data in database tables
- Inserts, updates, or deletes data in existing tables
- Does not change the database structure
- Examples: INSERT, UPDATE, DELETE, MERGE, LOCK TABLE
In summary:
- DDL is used to design and modify the database structure (schema)
- DML is used to manipulate the data within that structure
Think of DDL as building the house (database structure) and DML as furnishing and living in the
house
(manipulating data)!
4. Differentiate between DCL and TCL?
Ans:Here's a clear differentiation between DCL and TCL:
DCL (Data Control Language)_
- Used to control access and permissions to database objects
- Defines user roles, privileges, and access rights
- Grants or revokes permissions to users or roles
- Examples: GRANT, REVOKE, CREATE USER, ALTER USER
_TCL (Transaction Control Language)_

- Used to manage database transactions


- Controls the consistency and integrity of data
- Commits or rolls back changes made by DML statements
- Examples: COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
In summary:
- DCL is used to control who can access and manipulate data
- TCL is used to control how data changes are executed and committed
Think of DCL as managing the database security and access, and TCL as managing the
database
transactions and consistency!
5. What is the difference between ALTER and UPDATE command.
Ans:The ALTER and UPDATE commands in SQL serve different purposes:
ALTER:
- Modifies the structure of a database object, such as a table, index, or view.
- Used to add, delete, or modify columns, constraints, or other attributes of an existing object.
- Changes the definition of the object, but does not affect the data stored in it.
Example: ALTER TABLE employees ADD COLUMN salary DECIMAL(10, 2);
UPDATE:
- Modifies the data stored in a table.
- Used to change the values of existing columns for one or more rows.
- Does not change the structure of the table, only the data it contains.
Example: UPDATE employees SET salary = 50000 WHERE employee_id = 1;
In summary:
- ALTER changes the database object's structure ( schema ).
- UPDATE changes the data stored in the table (data manipulation).
Think of ALTER as renovating the house (changing the structure), and UPDATE as redecorating
the house
(\changing the contents)!
6. Differentiate between DELETE and DROP command
Ans:The DELETE and DROP commands in SQL serve different purposes:
DELETE:
- Deletes data from a table, removing one or more rows.
- The table structure remains unchanged.
- Data can be recovered using rollback or undo.
- Syntax: DELETE FROM table_name WHERE condition;
EXample: DELETE FROM employees WHERE employee_id = 1;
DROP:
- Deletes the entire table, index, view, or other database object.
- Removes the object's structure and all associated data.
- Data cannot be recovered once the object is dropped.
- Syntax: DROP object_type object_name;
Example: DROP TABLE employees;
In summary:
- DELETE removes data from a table (data manipulation).
- DROP removes the table itself, along with its data and structure (schema modification).
Think of DELETE as removing specific files from a folder, and DROP as deleting the entire folder,
including all files and the folder itself!
7. What is create statement? How many database objects can be created using this?
Ans:The CREATE statement is a SQL command used to create a new database object, such as:
1. *Table*: Define a new table with its columns, data types, and constraints.
2. *Index*: Create an index on one or more columns of a table.
3. *View*: Define a virtual table based on a SELECT statement.
4. *Procedure*: Create a stored procedure for encapsulating a set of operations.
5. *Function*: Define a user-defined function for calculations or transformations.
6. *Trigger*: Create a trigger for automatic actions on specific table events.
7. *Database*: Create a new database (depending on the DBMS).
8. *Schema*: Define a new schema (a namespace for database objects).
9. *Sequence*: Create a sequence for generating unique numeric values.
10. *Synonym*: Define an alias for a database object (e.g., a shortcut for a long table name).
The CREATE statement varies depending on the specific database management system (DBMS)
being
used, but it generally follows a similar syntax and structure.
Here's a simple example of creating a table:
`
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);
```
This creates a new table named "employees" with three columns: id, name, and salary.
8. Write the CREATE statement to create the following relations with given constraints.
Book(ISBN
(Text), Title (Text), Author (Text), PubID(Text), Price (Numeric), Pages (Numeric)). Here ISBN is
Primary
Key field and remaining all are Not Null.

Ans:Here is the CREATE statement to create the Book relation with the given constraints:
```
CREATE TABLE Book (
ISBN TEXT PRIMARY KEY,
Title TEXT NOT NULL,
Author TEXT NOT NULL,
PubID TEXT NOT NULL,
Price NUMERIC NOT NULL,
Pages NUMERIC NOT NULL
);
```
This CREATE statement defines the Book table with the specified columns and constraints:
- ISBN is the primary key, ensuring unique values.

- All other columns (Title, Author, PubID, Price, and Pages) are defined as NOT NULL, ensuring
that
values must be provided for these fields.
Note that the specific syntax may vary slightly depending on the database management system
(DBMS)
being used.
9. Modify the Book table in previous question and add one more new field Discount (Numeric).
Ans:Here is the ALTER TABLE statement to add the new field Discount (Numeric) to the existing
Book
table:
```
ALTER TABLE Book
ADD COLUMN Discount NUMERIC;
```
This will add the new column Discount to the Book table, with a numeric data type.
If you want to specify a default value for the Discount column or add a constraint (e.g., NOT
NULL), you
can modify the statement accordingly:
```
ALTER TABLE Book
ADD COLUMN Discount NUMERIC NOT NULL DEFAULT 0;
```
This will add the Discount column with a default value of 0 and ensure that a value must be
provided for
this field (NOT NULL).
Note that the specific syntax may vary slightly depending on the database management system
(DBMS)
being used.
10. Shyam has created one database name Mycontacts but he is not able to create new table in
this
database. What command should Shyam be used before creating the table?

Ans:Before creating a table in the Mycontacts database, Shyam needs to switch to that
database using
the USE command. The syntax is:
USE Mycontacts;
This command tells the database management system to switch to the Mycontacts database,
making it
the current database for subsequent commands.
After executing the USE command, Shyam can create a new table using the CREATE TABLE
command.
Example:
```
USE Mycontacts;
CREATE TABLE contacts (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);
```
This will create a new table named "contacts" in the Mycontacts database.
11. Mr. Sachin Agrawal created two tables with Course as Primary Key in Table1 and Foreign
key in
Table2 while inserting new row in second Table2 Mr Agrawal is not able to insert new value in
the
column City. What could be the possible reason for this?

Ans:The possible reason for this issue is that the Foreign Key constraint in Table2 is referencing
the
Course column in Table1, and the value being inserted into the City column in Table2 does not
have a
matching Course value in Table1.
Foreign Key constraints ensure data consistency by requiring that the value in the foreign key
column (in
this case, Course in Table2) matches a value in the primary key column (Course in Table1). If
the value
doesn't exist in Table1, the insert operation in Table2 will fail.
To resolve this, Mr. Agrawal can:
1. Insert the corresponding Course value in Table1 first.
2. Then, insert the new row in Table2, including the City value.
Alternatively, if the City column in Table2 is not dependent on the Foreign Key constraint, he can
consider removing the Foreign Key constraint from the City column in Table2.
Chapter 3. Functions In SQL
SUMMARY

A Function is used to perform a particular task and return a value as a result.

Single Row functions work on a single row of the table and return a single value.

Multiple Row functions work on a set of records as a whole and return a single value.

Examples include COUNT, MAX, MIN, AVG and SUM.

GROUP BY function is used to group rows of a table that contain the same values in a

specified column.

Join is an operation which is used to combine rows from two or more tables based on one

or more common fields between them.

CHECK YOUR PROGRESS

A. Multiple choice questions

1. Which of the following is not an example of single row function (a) MATH (b) STRING (c)
DATE (d) COUNT

2. Which of the following is not an example of multiple row function (a) MAX ( ) (b) MIN ( ) (c)

STRING (d) COUNT (*)

3. What is the functionality of SQL COUNT? (a) It returns the no of record of table (b) It

returns the no of record of database (c) It returns the no of record of row (d) It returns the

no of record of column

4. Date and Time functions accept date and time value as input and return output as (a)

numeric (b) string (c) Date and Time (d) Any of the above

5. String Functions accept character value as input and return output as (a) either character

or numeric values (b) string values (c) numeric values (d) character values

6. Which of the following is aggregate function in SQL (a) LEFT (b) AVG (c) JOIN (d) LEN

7. The SQL statement Select Round (47.956,-1) from Dual; (a) is illegal in SQL (b) prints a

garbage value (c) 045.926 (d) prints 50

8. Which of the following SQL operation cannot be performed on relations (a) Union, (b)

Intersection (c) Difference (d) Merge

9. Which of the following is used to join two tables on equality condition on the common

attribute (a) JOIN with ON clause (b) NATURAL JOIN in FROM clause (c) Any of a or b (d)

NATURAL JOIN

10. What will be the Cartesian product of the two relations having 4 rows and 3 columns for

first relation and 3 rows and 4 columns in second relation. (a) degree 7 cardinality 12 (b)

degree 6 cardinality 16 (c) degree 7 cardinality 16 (d) degree 9 cardinality 16

B. Fill in the blanks

1. Single row functions are applied on a single ______ and return a single value.

2. Aggregate functions work on a ________ as a whole and return a single value.)

3. Math Functions accept numeric value as input and return a ______ value as a result.

4. MONTH (date) returns the month in ________ form from the date.

5. By default, the order by clause lists items in ______ order.

6. INSTR (string, substring) returns the position of the _________ of the substring in the given
string.)

7. MID (string, pos, n) returns a substring of size ___ starting from the specified position

______ of the string. (n, pos).

8. LTRIM (string) returns the given string after removing ________ white space characters.

9. TRIM (string) returns the given string after removing both ________ and _________ white

space characters.

10. The _________ operation is used to get common tuples from two tables.
C. State True or False

1. Aggregate functions are also called Scalar functions.

2. A function always return a single value.

3. Functions can be applied to work on single or multiple records of a table.

4. INSTR (string, substring) returns 0, if the substring is not present in the string.

5. If n is not specified MID (string, pos, n), it returns the substring from the position 1 till end

of the string.

6. RTRIM (string) returns the given string after removing leading white space characters.

7. NOW() returns the current system date and time.

8. Union operation eliminates the duplicate rows.

9. Cartesian product operation combines tuples from two relations.

10. Join statement is used to combine two tables on a specified condition.

C. Short answer questions


1. Differentiate between single row functions and aggregate functions.
Ans:Here's a clear differentiation between single row functions and aggregate functions:
*Single Row Functions:*
- Operate on a single row or value at a time
- Return a result for each individual row
- Do not group or aggregate data
- Examples:
- Mathematical functions (e.g., ABS, SQRT, ROUND)
- String functions (e.g., UPPER, LOWER, TRIM)
- Date functions (e.g., NOW, DATE_FORMAT)
- Conversion functions (e.g., CAST, CONVERT)
*Aggregate Functions:*
- Operate on a group of rows or values
- Return a single result for the entire group
- Group and aggregate data
- Examples:
- SUM, AVG, MAX, MIN, COUNT
- GROUPING functions (e.g., GROUP_CONCAT, ARRAY_AGG)
- Statistical functions (e.g., STDEV, VAR_POP)

In summary:
- Single row functions process individual rows, returning a result for each row.
- Aggregate functions process groups of rows, returning a single result for the entire group.
Think of single row functions as processing individual items, while aggregate functions process
collections of items!
2. List the single row functions with example.
Ans:Here are some common single row functions with examples:
1. *Mathematical functions*
- ABS(-10) returns 10
- SQRT(16) returns 4
- ROUND(3.7) returns 4
- CEIL(3.2) returns 4
- FLOOR(3.8) returns 3
2. *String functions*
- UPPER('hello') returns 'HELLO'
- LOWER('WORLD') returns 'world'
- TRIM(' extra spaces ') returns 'extra spaces'
- LENGTH('hello') returns 5
- CONCAT('hello', 'world') returns 'helloworld'
3. *Date and Time functions*
- NOW() returns the current date and time
- DATE_FORMAT('2022-01-01', '%Y-%m-%d') returns '2022-01-01'
- DAYNAME('2022-01-01') returns 'Saturday'
- HOUR('12:30:00') returns 12
4. *Conversion functions*
- CAST('123' AS INTEGER) returns 123
- CONVERT('2022-01-01', DATE) returns '2022-01-01'
5. *Other functions*
- COALESCE(NULL, 'default') returns 'default'
- NULLIF('value', 'value') returns NULL
Note: These examples are for illustrative purposes and may vary depending on the specific
database
management system being used.
3. Differentiate between TRIM( ), LTRIM( ) and RTRIM( ) functions.
Ans:The TRIM(), LTRIM(), and RTRIM() functions are used to remove unwanted spaces from a
string, but
they differ in which sides of the string they operate on:
- TRIM(): Removes spaces from both the beginning (left) and end (right) of a string.
- Example: TRIM(' extra spaces ') returns 'extra spaces'
- LTRIM(): Removes spaces only from the beginning (left) of a string.
- Example: LTRIM(' extra spaces ') returns 'extra spaces '
- RTRIM(): Removes spaces only from the end (right) of a string.
- Example: RTRIM(' extra spaces ') returns ' extra spaces'
In summary:
- TRIM() removes spaces from both sides.
- LTRIM() removes spaces from the left side only.
- RTRIM() removes spaces from the right side only.
Think of it like trimming a garden:
- TRIM() is like trimming both edges of a hedge.
- LTRIM() is like trimming only the left edge.
- RTRIM() is like trimming only the right edge.
4. Demonstrate the use of LCASE( ) and UCASE( ) function with example.
Ans:The LCASE() and UCASE() functions are used in SQL to convert the case of a string. Here
are examples demonstrating their use:

1. LCASE() Function Example:


sql
Copy code
SELECT LCASE('Hello World') AS LowerCaseString;

This query will return:


markdown
Copy code
lowercasestring
---------------
hello world

Explanation:
 LCASE('Hello World') converts the string 'Hello World' to all lowercase letters.

2. UCASE() Function Example:


sql
Copy code
SELECT UCASE('Hello World') AS UpperCaseString;

This query will return:


markdown
Copy code
uppercasestring
---------------
HELLO WORLD

Explanation:

 UCASE('Hello World') converts the string 'Hello World' to all uppercase letters.

In both cases, the functions LCASE() and UCASE() take a string input and return the string with all
characters converted to lowercase or uppercase, respectively. These functions are useful when you need
to standardize the case of string data for comparison or display purposes in SQL queries.

5. List the date functions with example.


Ans:Here are some common date functions with examples:
1. _NOW()_
- Returns the current date and time.
- Example: NOW() returns '2024-07-28 14:30:00'
2. _CURDATE()_
- Returns the current date.
- Example: CURDATE() returns '2024-07-28'
3. _CURTIME()_
- Returns the current time.
- Example: CURTIME() returns '14:30:00'
4. _DATE()_
- Extracts the date from a datetime value.
- Example: DATE('2024-07-28 14:30:00') returns '2024-07-28'
5. _TIME()_
- Extracts the time from a datetime value.
- Example: TIME('2024-07-28 14:30:00') returns '14:30:00'
6. _DATE_FORMAT()_
- Formats a date in a specified way.
- Example: DATE_FORMAT('2024-07-28', '%Y-%m-%d') returns '2024-07-28'
7. _DAYNAME()_
- Returns the name of the day of the week.
- Example: DAYNAME('2024-07-28') returns 'Saturday'
8. _DAYOFWEEK()_
- Returns the day of the week (1-7).
- Example: DAYOFWEEK('2024-07-28') returns 7
9. _DAYOFMONTH()_
- Returns the day of the month (1-31).
- Example: DAYOFMONTH('2024-07-28') returns 28
10. _YEAR()_, _MONTH()_, _DAY()_
- Extract the year, month, or day from a date.
- Examples:
- YEAR('2024-07-28') returns 2024
- MONTH('2024-07-28') returns 7
- DAY('2024-07-28') returns 28
Note: These examples are for illustrative purposes and may vary depending on the specific
database
management system being used.
6. What is the difference between NOW( ) and DATE( ) function?
Ans:The NOW() and DATE() functions both deal with dates, but they serve different purposes:
NOW():
- Returns the current date and time, including hours, minutes, and seconds.
- Example: NOW() returns '2024-07-28 14:30:00'
DATE():
- Returns the current date, without the time component (hours, minutes, and seconds).
- Example: DATE() returns '2024-07-28'
In other words:
- NOW() gives you the current date and time.
- DATE() gives you only the current date.
Think of it like this:
- NOW() is like getting the current timestamp (date and time).
- DATE() is like getting just the current date (without the time).
Here's a summary:
- NOW() = date + time
- DATE() = date only
7. Demonstrate the difference between SUM( ) and AVG( ) function?
Ans:The SUM() and AVG() functions are both used to calculate aggregate values, but they serve
different
purposes:
SUM():
- Returns the total sum of a set of values.
- Example: SUM(salary) returns the total salary of all employees.

AVG():
- Returns the average value of a set of values.
- Example: AVG(salary) returns the average salary of all employees.
Let's consider a simple example to illustrate the difference:
Suppose we have a table with the following salaries:
| Salary |
| ------ |
| 1000 |
| 2000 |
| 3000 |
| 4000 |
| 5000 |
SUM(salary) would return: 1000 + 2000 + 3000 + 4000 + 5000 = 14000
AVG(salary) would return: 14000 / 5 = 2800
In this example:
- SUM(salary) gives you the total salary (14000).
- AVG(salary) gives you the average salary (2800).
So, SUM() adds up all the values, while AVG() calculates the average value by dividing the sum
by the
count of values.
8. A table Student has 4 rows and 2 column and another table has 3 rows and 4 columns. How
many
rows and columns will be there if we obtain the Cartesian product of these two tables?

Ans:If we obtain the Cartesian product (also known as the cross product or cross join) of the
two tables,
the resulting table will have:
- Rows: 4 (from the first table) x 3 (from the second table) = 12 rows
- Columns: 2 (from the first table) + 4 (from the second table) = 6 columns
So, the resulting table will have 12 rows and 6 columns.

In a Cartesian product, each row of the first table is paired with each row of the second table,
resulting
in a new table with the combined columns and a larger number of rows.
9. What will be the output of following SQL functions.
a)Select pow (3,2);
b) Select round (342.9234, 2);
c)Select length (‘Vocational Education’);

d) Select year (‘1978/08/17’), month (‘1978/08/17’), day (‘1978/08/17’), monthname


(‘1978/08/17’);
e)Select left ('Central', 3), right ('Institute', 4), mid ('Vocational', 3, 4), substr ('Education', 3);

Ans:Here are the outputs of the given SQL functions:


a) Select pow(3,2);
Output: 9 (because 3^2 = 9)

b) Select round(342.9234, 2);


Output: 342.92 (rounded to 2 decimal places)
c) Select length('Vocational Education');
Output: 20 (the length of the string 'Vocational Education')
d) Select year('1978/08/17'), month('1978/08/17'), day('1978/08/17'), monthname('1978/08/17');
Output:
* year: 1978
* month: 8
* day: 17
* monthname: August
e) Select left('Central', 3), right('Institute', 4), mid('Vocational', 3, 4), substr('Education', 3);
Output:
* left('Central', 3): 'Cen' (first 3 characters)
* right('Institute', 4): 'tute' (last 4 characters)
* mid('Vocational', 3, 4): 'ation' (4 characters starting from the 3rd position)
* substr('Education', 3): 'ucation' (substring starting from the 3rd position)
Note that the exact output may vary slightly depending on the specific database management
system
being used.
10. Write the SQL functions to perform the following operations.
a) To display the day like “Monday”, “Tuesday”, from the date when India got independence.

b) To display the specified number of characters from a particular position of the given string.
c) To display the name of the month in which you were born.
d) To display your name in capital letters.
Ans:Here are the SQL functions to perform the operations:
a) To display the day like "Monday", "Tuesday", from the date when India got independence
(August 15,
1947):
```
SELECT DAYNAME('1947-08-15') AS Independence_Day;
```
b) To display the specified number of characters from a particular position of the given string
(e.g., "
Vocational Education", starting from position 3, display 4 characters):
```
SELECT MID('Vocational Education', 3, 4) AS Substring;
```
c) To display the name of the month in which you were born (replace '1990-06-21' with your
birthdate):
```
SELECT MONTHNAME('1990-06-21') AS Birth_Month;
```
d) To display your name in capital letters (replace 'Your_Name' with your actual name):
```
SELECT UPPER('Your_Name') AS Name_In_Capitals;
```
Note: These functions are based on MySQL syntax. The exact syntax may vary depending on the
database management system being used.

End of Unit One

,******************. .*****************.

You might also like