0% found this document useful (0 votes)
97 views32 pages

Unit 1. RDBMS 12

This document covers the fundamental concepts of Relational Database Management Systems (RDBMS) in MySQL, including the definition of databases, tables, and keys. It explains the importance of database schema, constraints, and the use of SQL for data manipulation. Additionally, it addresses the limitations of file systems and how DBMS overcomes these challenges, along with various data types and features of MySQL.

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)
97 views32 pages

Unit 1. RDBMS 12

This document covers the fundamental concepts of Relational Database Management Systems (RDBMS) in MySQL, including the definition of databases, tables, and keys. It explains the importance of database schema, constraints, and the use of SQL for data manipulation. Additionally, it addresses the limitations of file systems and how DBMS overcomes these challenges, along with various data types and features of MySQL.

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/ 32

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
Answer:A file system
system?isWrite
a waydown limitations
of organizing andofstoring
file system.
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
systems, suchlimitations haveand
as databases ledcontent
to the development
managementofsystems.
alternative data storage and management

2. Why foreign
Answer: Foreignkeys
keysare
areallowed
allowedtotohave
haveNULL
NULLvalues?
values Explain
becausewith
theyanmight
example.
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,
"CustomerID" in the
the "CustomerID" fieldHowever,
Customers table. in the Orders
if an table
order isis aplaced
foreign
bykey that references
a customer the created
who hasn't
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
relationship values tables
between in foreign keys
might notprovides flexibility in handling such scenarios, where the
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
ensuring and Duplication*: DBMS stores data in a single place, reducing duplication and
data consistency.
2. *Data Inconsistency*: DBMS enforces data integrity constraints, ensuring data accuracy and
consistency.
3. *Data
access Search and Retrieval*: DBMS provides efficient search and retrieval mechanisms, making data
faster.
4. *DatatoSecurity
logging ensure and
dataIntegrity*: DBMS
integrity and offers robust security features, access control, and transaction
security.
5. *Data
scales Isolation and
horizontally, Scalability*:
ensuring DBMS allows
data availability andconcurrent access, supports large data volumes, and
performance.

Additionally, DBMS provides features like:

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

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

4. What is database schema?


Answer :A database
relationships schema
between is the
different overall
data structure
entities. or organization
It defines how data is of a database,
stored, linked, including the within a
and accessed
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
scripts. can be represented visually through entity-relationship diagrams (ERDs) or in code through SQL

5. What is data
Answer:Data redundancy
redundancy and to
refers its the
associated problems?
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.
to *Data inconsistency*: Updates to one copy of the data may not be reflected in other copies, leading
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 avoiddata
ensure these problems,and
consistency data normalization techniques are used to eliminate data redundancy and
efficiency.
6. How data redundancy problem is solved in DBMS?
Answer:In DBMS, data redundancy is solved through:

1. *Data
into Normalization*:
smaller ones. Organizing data into tables and removing duplicates by splitting large tables

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
Fourth Normal
Normal FormForms*:
(4NF), Further
and Fifthnormalization
Normal Formtechniques,
(5NF). like Boyce-Codd Normal Form (BCNF),

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
storage these
needs, andtechniques, DBMSretrieval
improving data minimizes data redundancy, ensuring data consistency, reducing
performance.

7. What is
Answer: MYSQL
MySQL is and its features?
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
Answer:MySQL data various
supports types available in MYSQL?
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
Degree between:
and cardinality of a(a)relation
Database state and database schema (b) Primary key and foreign key (c)

Answer: Here are the differences:

(a) Database state vs Database schema:

-set
Database state:
of values Refers
in the to the actual data stored in the database at a given point in time. It's the current
database.
-relationships,
Database schema: Refers to the
and constraints. It'sstructure or organization
the blueprint or design ofofthe
thedatabase.
database, including table definitions,

(b) Primary key vs Foreign key:

-It's
Primary key or
a column (PK):
setAofunique identifier
columns for a record
that uniquely in a table,
identifies ensuring data consistency and uniqueness.
each row.
-relationship
Foreign keybetween
(FK): A field in a table that references the primary key of another table, establishing a
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.
KeyExplain the terms
(h) Foreign Key (a) Relation (b) Domain (c) Tuple (d) Attribute (e) Degree (f) Cardinality (g) Primary
Answer: Here are the explanations:

(a) Relation:
concept A relation
in relational is a table in a database that contains a set of related data. It's a fundamental
databases.

(b) Domain:
values A domain
for a specific is the set of possible values that an attribute can take. It defines the range of
attribute.

(c) Tuple:
single A tuple
entity is a single row or record in a relation (table). It's a collection of values that represent a
or instance.

(d) Attribute:
feature of theAn attribute is a column or field in a relation (table). It defines a specific characteristic or
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
attribute orKey
a set(PK): A primarythat
of attributes key uniquely
is a unique identifier
identifies fortuple.
each a tuple (row) in a relation. It's a single

(h) Foreign
relation. Key (FK): A aforeign
It establishes key is an
relationship attribute
between twoinrelations.
a relation that references the primary key of another
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
-relation,
Foreign it's
Key: If another
a Foreign relation "Courses" has an attribute "Student_ID" that references the Students
Key.

11. Describe the various


Answer:Integrity integrity
constraints 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.
set*Domain Integrity*: Ensures that data values conform to the defined domain (e.g., format, range, or
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
reliableintegrity constraints help maintain data consistency, prevent errors, and ensure that data is
and trustworthy.
Chapter
SUMMARY 2. Structured Query Language (SQL)

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.
2. INSERT clauseisisused
ALTER clause usedto
toadd
addaaPrimary
Foreignkey
keyconstraint
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
Ans:SQL you understand
(Structured by SQL? is a programming language designed for managing and
Query Language)
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 asupported
widely standard language
by variousfor interacting
database with relational
management databases,
systems and its
like MySQL, commandsMicrosoft
PostgreSQL, and syntax
SQLare
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 andata
analyze essential tool for database administrators, developers, and data analysts to manage and
effectively.
2. SQL
Ans: Statements
SQL areare
statements classified in into
classified how several
many ways?
categories, including:

1. *DDLTRUNCATE.
DROP, (Data Definition Language)*: used to define and modify database structure, e.g., CREATE, ALTER,

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 thatway
common sometosources
classify may group SQL statements slightly differently, but these five categories are a
SQL statements.
3. Differentiate
Ans:Here's between
a clear DDL andbetween
differentiation DML? 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 asdata)!


(manipulating building the house (database structure) and DML as furnishing and living in the house

4. Differentiate
Ans:Here's between
a clear DCL and between
differentiation TCL? 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 and


transactions as managing the database security and access, and TCL as managing the database
consistency!
5. What is
Ans:The the difference
ALTER and UPDATEbetween ALTERinand
commands SQLUPDATE command.
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
(changing as renovating the house (changing the structure), and UPDATE as redecorating the house
the contents)!
6. Differentiate
Ans:The DELETEbetween DELETE
and DROP and DROP
commands command
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
including all filesas
andremoving specific
the folder itself!files from a folder, and DROP as deleting the entire folder,
7. What is
Ans:The createstatement
CREATE statement?is How
a SQLmany database
command usedobjects canabe
to create created
new usingobject,
database this? 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
used,CREATE statement
but it generally variesadepending
follows on the
similar syntax andspecific database management system (DBMS) being
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. WriteTitle
(Text), the(Text),
CREATE statement
Author (Text),toPubID(Text),
create the following relationsPages
Price (Numeric), with given constraints.
(Numeric)). Book(ISBN
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.
-values
All other
mustcolumns (Title,for
be provided Author,
thesePubID,
fields. Price, and Pages) are defined as NOT NULL, ensuring that

Note
beingthat the specific syntax may vary slightly depending on the database management system (DBMS)
used.
9. Modify isthe
Ans:Here theBook table
ALTER in previous
TABLE question
statement to addand
theadd
newone
fieldmore new field
Discount Discount
(Numeric) (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
canyou want the
modify to specify a default
statement value for the Discount column or add a constraint (e.g., NOT NULL), you
accordingly:
```
ALTER TABLE Book
ADD COLUMN Discount NUMERIC NOT NULL DEFAULT 0;
```
This will add
this field (NOTthe Discount column with a default value of 0 and ensure that a value must be provided for
NULL).

Note
beingthat the specific syntax may vary slightly depending on the database management system (DBMS)
used.
10. ShyamWhat
database. has created
commandoneshould
database name
Shyam beMycontacts
used beforebut he is not
creating theable to create new table in this
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
the current tells the
database fordatabase management
subsequent system to switch to the Mycontacts database, making it
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.while
Table2 Sachininserting
Agrawalnew
created
row two tablesTable2
in second with Course as Primary
Mr Agrawal is notKey
ableinto
Table1
insertand
newForeign
value inkey
thein
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
this case,Key constraints
Course ensure
in Table2) data consistency
matches byprimary
a value in the requiringkeythat the value
column in the
(Course foreign key
in Table1). column
If the value(in
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 thethe
consider removing CityForeign
columnKey
in Table2 is not
constraint dependent
from the City on the Foreign
column Key constraint, he can
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
Ans:Here's between
a clear single row
differentiation functions
between androw
single aggregate functions.
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
collections row functions as processing individual items, while aggregate functions process
of items!
2. List theare
Ans:Here single rowcommon
some functions withrow
single example.
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


management are for
system being illustrative purposes and may vary depending on the specific database
used.
3. Differentiate
Ans:The TRIM(),between
LTRIM(), TRIM( ), LTRIM(
and RTRIM() ) and RTRIM(
functions ) 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:
5. List theare
Ans:Here datesome
functions
commonwithdate
example.
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
management are for
system being illustrative purposes and may vary depending on the specific database
used.
6. What is
Ans:The the difference
NOW() between
and DATE() NOW(
functions both) and
dealDATE( ) function?
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
Ans:The the AVG()
SUM() and difference between
functions SUM(used
are both ) andtoAVG( ) function?
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()
count adds up all the values, while AVG() calculates the average value by dividing the sum by the
of values.
8. A table
rows Student has
and columns will 4berows and
there 2 column
if we obtain and another table
the Cartesian has 3ofrows
product theseand
two4 tables?
columns. How many
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
in aa new
Cartesian
table product,
with the each row ofcolumns
combined the firstand
table is paired
a larger with each
number row of the second table, resulting
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
d) Selectlength (‘Vocational Education’);
year (‘1978/08/17’), month (‘1978/08/17’), day (‘1978/08/17’), monthname (‘1978/08/17’);
e)Select
Ans:Hereleft
are('Central', 3), of
the outputs right
the('Institute',
given SQL 4), mid ('Vocational', 3, 4), substr ('Education', 3);
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
beingthat the exact output may vary slightly depending on the specific database management system
used.
10. Write the SQL functions to perform the following operations.
a)
b) To
To display
display the
the day like “Monday”,
specified number of“Tuesday”,
charactersfrom
fromthe date when
a particular India got
position independence.
of the given string.
c) To display the name of the month in which you were born.
d) To display
Ans:Here are your name
the SQL in capital
functions to letters.
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 displayEducation",
"Vocational the specified number
starting of characters
from position 3, from a particular
display position of the given string (e.g.,
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
database functions are
management basedbeing
system on MySQL
used. syntax. The exact syntax may vary depending on the

End of Unit One

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

You might also like