0% found this document useful (0 votes)
23 views

Dbms 2

concepts of databases

Uploaded by

Adilyt ytt
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)
23 views

Dbms 2

concepts of databases

Uploaded by

Adilyt ytt
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/ 17

1. Define SQL.

SQL (Structured Query Language) is a standardized programming language


used for managing and manipulating relational databases. It enables users to
perform various operations such as querying data, updating records, creating
and modifying database structures, and managing user access.

2. Describe the data types available for attributes with syntax and
examples.
SQL supports several data types, including:
 Numeric:
o INT: Integer values.

sql
Copy code
age INT;
o DECIMAL(p, s): Fixed-point numbers.

sql
Copy code
price DECIMAL(10, 2);
 String:
o VARCHAR(n): Variable-length strings.

sql
Copy code
name VARCHAR(50);
o TEXT: Long text data.

sql
Copy code
description TEXT;
 Date/Time:
o DATE: Stores dates.

sql
Copy code
birth_date DATE;
 Boolean:
o BOOLEAN: Stores TRUE or FALSE values.

sql
Copy code
is_active BOOLEAN;

3. Explain the CREATE TABLE command in SQL and write the syntax and
example.
The CREATE TABLE command is used to create a new table in a database.
Syntax:
sql
Copy code
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
);
Example:
sql
Copy code
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);

4. Describe the basic constraints that can be specified in SQL as part of


table creation.
Basic constraints in SQL include:
 PRIMARY KEY: Uniquely identifies each row.
 FOREIGN KEY: Ensures referential integrity between tables.
 UNIQUE: Ensures all values in a column are different.
 NOT NULL: Prevents NULL values in a column.
 CHECK: Validates data against a specified condition.
Example:
sql
Copy code
CREATE TABLE Products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) CHECK (price > 0)
);

5. Write the basic form of the SELECT statement with an example.


The SELECT statement is used to retrieve data from a database.
Syntax:
sql
Copy code
SELECT column1, column2
FROM table_name;
Example:
sql
Copy code
SELECT first_name, last_name
FROM Employees;

6. Discuss the importance of ambiguous attribute names, aliasing, and


tuple variables.
Ambiguous attribute names arise when two or more tables in a query have
columns with the same name. Aliasing allows for clearer references by giving
temporary names to tables or columns, improving readability. Tuple variables can
differentiate between records in subqueries.
Example:
sql
Copy code
SELECT e.first_name, e.last_name
FROM Employees AS e
JOIN Departments AS d ON e.dept_id = d.id;

7. Explain substring pattern matching and arithmetic operators.


Substring Pattern Matching allows querying based on partial strings using
LIKE, often with wildcards:
 % (matches any sequence of characters)
 _ (matches a single character)
Example:
sql
Copy code
SELECT * FROM Students WHERE name LIKE 'A%'; -- Names starting with 'A'
Arithmetic Operators include:
 + (addition)
 - (subtraction)
 * (multiplication)
 / (division)
Example:
sql
Copy code
SELECT price * quantity AS total_cost FROM Orders;

8. Explain the INSERT, DELETE, and UPDATE statements in SQL.


 INSERT: Adds new records to a table.
sql
Copy code
INSERT INTO Employees (first_name, last_name) VALUES ('John', 'Doe');
 DELETE: Removes records from a table.
sql
Copy code
DELETE FROM Employees WHERE employee_id = 1;
 UPDATE: Modifies existing records in a table.
sql
Copy code
UPDATE Employees SET last_name = 'Smith' WHERE employee_id = 2;

9. Comparisons Involving NULL and Three-Valued Logic.


NULL represents missing data in SQL. Three-valued logic includes:
 TRUE
 FALSE
 UNKNOWN (when a comparison involves NULL)
Example:
sql
Copy code
SELECT * FROM Employees WHERE middle_name IS NULL; -- Retrieves records
with NULL middle names.

10. What is the importance of nested queries and correlated nested


queries? Give syntax and examples.
Nested Queries allow for complex queries by using a query inside another
query, which helps in filtering and processing data.
Syntax:
sql
Copy code
SELECT column1
FROM table1
WHERE column2 IN (SELECT column2 FROM table2 WHERE condition);
Example:
sql
Copy code
SELECT name FROM Students WHERE student_id IN (SELECT student_id FROM
Enrollments);
Correlated Nested Queries reference columns from the outer query, allowing
row-by-row processing.
Example:
sql
Copy code
SELECT s.name
FROM Students s
WHERE EXISTS (SELECT 1 FROM Enrollments e WHERE e.student_id =
s.student_id);

11. Write the EXISTS and UNIQUE Functions in SQL with syntax and
example.
EXISTS: Checks for the existence of rows returned by a subquery.
Syntax:
sql
Copy code
SELECT column
FROM table
WHERE EXISTS (SELECT 1 FROM another_table WHERE condition);
Example:
sql
Copy code
SELECT name FROM Students WHERE EXISTS (SELECT 1 FROM Enrollments
WHERE student_id = Students.student_id);
UNIQUE: Typically used in table definitions to enforce uniqueness; in queries,
use DISTINCT.
Example:
sql
Copy code
SELECT DISTINCT course_name FROM Enrollments;

12. What are the different types of joining the tables with syntax and
example?
Different types of joins in SQL include:
 INNER JOIN: Returns matching rows from both tables.
sql
Copy code
SELECT * FROM A INNER JOIN B ON A.id = B.id;
 LEFT JOIN: Returns all rows from the left table and matched rows from the
right.
sql
Copy code
SELECT * FROM A LEFT JOIN B ON A.id = B.id;
 RIGHT JOIN: Returns all rows from the right table and matched rows from
the left.
sql
Copy code
SELECT * FROM A RIGHT JOIN B ON A.id = B.id;
 FULL OUTER JOIN: Returns all rows when there is a match in either table.
sql
Copy code
SELECT * FROM A FULL OUTER JOIN B ON A.id = B.id;

13. Explain all the aggregate functions in SQL.


Aggregate functions perform calculations on a set of values and return a single
value. Common aggregate functions include:
 COUNT(): Counts the number of rows.
sql
Copy code
SELECT COUNT(*) FROM Employees;
 SUM(): Calculates the total sum of a numeric column.
sql
Copy code
SELECT SUM(salary) FROM Employees;
 AVG(): Calculates the average value of a numeric column.
sql
Copy code
SELECT AVG(salary) FROM Employees;
 MAX(): Finds the maximum value.
sql
Copy code
SELECT MAX(salary) FROM Employees;
 MIN(): Finds the minimum value.
sql
Copy code
SELECT MIN(salary) FROM Employees;

14. Illustrate the GROUP BY and HAVING clauses with syntax and
example.
GROUP BY groups rows that have the same values in specified columns,
allowing aggregate functions to be applied.
Syntax:
sql
Copy code
SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1;
Example:
sql
Copy code
SELECT product, SUM(amount) AS total_sales FROM sales GROUP BY product;
HAVING filters groups based on a condition after aggregation.
Syntax:
sql
Copy code
SELECT column1, aggregate_function(column2)
FROM table
GROUP BY column1
HAVING condition;
Example:
sql
Copy code
SELECT product, SUM(amount) AS total_sales FROM sales GROUP BY product
HAVING SUM(amount) > 400;
15. What is a trigger? Explain the mechanism of a trigger with syntax
and example.
A trigger is a special type of stored procedure that automatically executes in
response to certain events on a specified table, such as INSERT, UPDATE, or
DELETE.
Syntax:
sql
Copy code
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic
END;
Example:
sql
Copy code
CREATE TRIGGER after_employee_insert
AFTER INSERT ON Employees
FOR EACH ROW
BEGIN
INSERT INTO AuditLog (action, employee_id) VALUES ('INSERT',
NEW.employee_id);
END;

16. Describe before and after triggers with examples.


Before Triggers: Execute before an INSERT, UPDATE, or DELETE operation.
Useful for validation.
Example:
sql
Copy code
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON Employees
FOR EACH ROW
BEGIN
IF NEW.salary < 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary cannot be
negative';
END IF;
END;
After Triggers: Execute after the operation. Useful for logging changes.
Example:
sql
Copy code
CREATE TRIGGER after_employee_delete
AFTER DELETE ON Employees
FOR EACH ROW
BEGIN
INSERT INTO DeletedRecords (employee_id, deleted_at) VALUES
(OLD.employee_id, NOW());
END;

17. Define a view. Discuss the SQL CREATE VIEW statement with
example.
A view is a virtual table based on the result of a query. It can simplify complex
queries, encapsulate complex joins, and restrict access to data.
Syntax:
sql
Copy code
CREATE VIEW view_name AS
SELECT column1, column2
FROM table
WHERE condition;
Example:
sql
Copy code
CREATE VIEW ActiveEmployees AS
SELECT first_name, last_name
FROM Employees
WHERE is_active = TRUE;

18. How do you declare and invoke SQL functions?


Declaring a Function: Functions are created using the CREATE FUNCTION
statement.
Syntax:
sql
Copy code
CREATE FUNCTION function_name(parameters)
RETURNS return_type
BEGIN
-- Function logic
RETURN value;
END;
Example:
sql
Copy code
CREATE FUNCTION GetFullName(first VARCHAR(50), last VARCHAR(50))
RETURNS VARCHAR(100)
BEGIN
RETURN CONCAT(first, ' ', last);
END;
Invoking a Function:
sql
Copy code
SELECT GetFullName('John', 'Doe');

19. Illustrate stored procedures with syntax and example.


Stored Procedures are precompiled collections of SQL statements stored in the
database.
Syntax:
sql
Copy code
CREATE PROCEDURE procedure_name (parameters)
BEGIN
-- SQL statements
END;
Example:
sql
Copy code
CREATE PROCEDURE AddEmployee(IN first_name VARCHAR(50), IN last_name
VARCHAR(50))
BEGIN
INSERT INTO Employees (first_name, last_name) VALUES (first_name,
last_name);
END;
Invoking a Procedure:
sql
Copy code
CALL AddEmployee('Jane', 'Smith');

20. Discuss update of a View with example.


Views can be updated under certain conditions. If the view is updatable, you can
perform INSERT, UPDATE, or DELETE on it.
Example:
Assume we have an ActiveEmployees view:
sql
Copy code
CREATE VIEW ActiveEmployees AS
SELECT first_name, last_name
FROM Employees
WHERE is_active = TRUE;
Update Statement:
sql
Copy code
UPDATE ActiveEmployees SET last_name = 'Johnson' WHERE first_name = 'Jane';
This updates the corresponding record in the Employees table.

21. What is ALTER and DROP command? Give syntax and example.
ALTER: Used to modify an existing database object.
Syntax:
sql
ALTER TABLE table_name
ADD column_name datatype;
Example:
sql
Copy code
ALTER TABLE Employees ADD email VARCHAR(100);
DROP: Used to delete a database object.
Syntax:
sql
Copy code
DROP TABLE table_name;
Example:
sql
Copy code
DROP TABLE Employees;

22. What is normalization? Explain the practical use of normal forms.


Normalization is the process of organizing data in a database to reduce
redundancy and improve data integrity. It involves dividing a database into
tables and establishing relationships between them.
Practical Uses:
 Reduces data duplication.
 Enhances data integrity.
 Simplifies data management.
The main normal forms (1NF, 2NF, 3NF) are used to achieve these goals.

23. Illustrate First, Second, and Third Normal Forms with examples.
 First Normal Form (1NF): Ensures that all attributes contain atomic
values.
o Example: A table of student courses should not have a multi-valued
column.
 Second Normal Form (2NF): Achieved when it is in 1NF and all non-key
attributes are fully functionally dependent on the primary key.
o Example: In a table with StudentID and CourseID, ensure no partial
dependencies.
 Third Normal Form (3NF): Achieved when it is in 2NF and there are no
transitive dependencies.
o Example: If a student’s department is stored in the same table, it
should be moved to a separate table to eliminate dependency.

24. Define functional dependency with a suitable example.


Functional Dependency (FD) is a relationship between two attributes, typically
between a primary key and non-key attributes. It states that if two rows have the
same value for attribute X, they must also have the same value for attribute Y.
Example:
In a table of Students:
 If StudentID → StudentName, then knowing StudentID allows you to
determine StudentName.

25. Write all the inference rules for functional dependency.


The inference rules, also known as Armstrong's Axioms, include:
1. Reflexivity: If Y is a subset of X, then X → Y.
2. Augmentation: If X → Y, then XZ → YZ for any Z.
3. Transitivity: If X → Y and Y → Z, then X → Z.
Additional rules include:
 Union: If X → Y and X → Z, then X → YZ.
 Decomposition: If X → YZ, then X → Y and X → Z.
 Pseudotransitivity: If X → Y and WY → Z, then WX → Z.
26. Explain the Equivalence of sets of functional dependencies.
Two sets of functional dependencies are equivalent if they imply each other. This
means that if every functional dependency in one set can be derived from the
other, they are considered equivalent.
Example:
 Set A: {A → B, B → C}
 Set B: {A → C}
Set A implies Set B, and vice versa, if you can derive one from the other using
inference rules.

27. What is JDBC? Write the JDBC classes and interfaces with examples.
JDBC (Java Database Connectivity) is an API in Java for connecting and
executing queries with databases.
Key Classes and Interfaces:
 DriverManager: Manages database drivers.
 Connection: Represents a connection to a database.
 Statement: Used to execute SQL queries.
 ResultSet: Represents the result set of a query.
Example:
java
Copy code
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
while (rs.next()) {
System.out.println(rs.getString("first_name"));
}

28. Write a note on SQLJ and Stored Procedures.


SQLJ is an extension of SQL that allows embedding SQL statements directly in
Java code. It provides type safety and integrates seamlessly with Java
applications, enabling developers to write portable and efficient database access
code.
Stored Procedures are precompiled SQL code stored in the database. They
allow for complex operations and can be reused, improving performance and
maintaining business logic within the database.
Example of Stored Procedure:
sql
Copy code
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT * FROM Employees;
END;

29. Discuss the steps of JDBC connections for an Internet Bookshop.


1. Load the JDBC Driver: Load the appropriate database driver.
java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection: Use DriverManager to connect to the database.
java
Copy code
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "user",
"password");
3. Create a Statement: Use the connection to create a Statement or
PreparedStatement.
java
Copy code
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM Books
WHERE price < ?");
pstmt.setDouble(1, 20.0);
4. Execute the Query: Execute the query and retrieve results.
java
Copy code
ResultSet rs = pstmt.executeQuery();
5. Process the Results: Iterate through the ResultSet.
java
Copy code
while (rs.next()) {
System.out.println(rs.getString("title"));
}
6. Close Connections: Finally, close the ResultSet, Statement, and
Connection.
java
Copy code
rs.close();
pstmt.close();
conn.close();

You might also like