0% found this document useful (0 votes)
50 views26 pages

DBMS Complete

The document describes experiments on applying integrity constraints like primary keys, foreign keys, check constraints, and not null constraints to database tables. It also provides examples of basic SQL queries using SELECT, INSERT, UPDATE, DELETE statements and built-in functions, grouping, having, ordering, different types of joins, and subqueries.
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)
50 views26 pages

DBMS Complete

The document describes experiments on applying integrity constraints like primary keys, foreign keys, check constraints, and not null constraints to database tables. It also provides examples of basic SQL queries using SELECT, INSERT, UPDATE, DELETE statements and built-in functions, grouping, having, ordering, different types of joins, and subqueries.
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/ 26

Experiment 2

Aim of the Experiment: Apply the integrity constraints like Primary Key, Foreign key, Check,
NOT NULL, etc. to the tables.

Primary Key Constraint:

The primary key constraint ensures that a column or a combination of columns uniquely identify
each row in the table.

Example:

CREATE TABLE users

( id INT PRIMARY

KEY,

username VARCHAR(50) NOT NULL,

email VARCHAR(50) UNIQUE NOT NULL,

password VARCHAR(255) NOT NULL

);

In this example, the "id" column is the primary key for the "users" table. The "username" and
"email" columns are also required and must be unique.

Foreign Key Constraint:

The foreign key constraint ensures that the values in a column or a combination of columns in
one table correspond to the values in another table.

Example:

CREATE TABLE orders (

id INT PRIMARY KEY,

customer_id INT,

order_date DATE,
total DECIMAL(10,2),

FOREIGN KEY (customer_id) REFERENCES customers(id)


);

In this example, the "orders" table has a foreign key constraint on the "customer_id" column that
references the "id" column in the "customers" table. This ensures that the "customer_id" values
in the "orders" table correspond to valid "id" values in the "customers" table.

Check Constraint:

The check constraint ensures that the values in a column meet a specific condition or set of
conditions.

Example:

CREATE TABLE products (

id INT PRIMARY KEY,

name VARCHAR(50) NOT NULL,

price DECIMAL(10,2) NOT NULL CHECK (price > 0),

stock_quantity INT NOT NULL CHECK (stock_quantity >= 0)

);

In this example, the "price" column must be greater than 0, and the "stock_quantity" column
must be greater than or equal to 0.

Not Null Constraint:

The not null constraint ensures that a column cannot have a null value.

Example:

CREATE TABLE customers (

id INT PRIMARY KEY,

name VARCHAR(50) NOT NULL,


email VARCHAR(50) UNIQUE NOT NULL,

phone VARCHAR(20) NOT NULL

)
In this example, the "name", "email", and "phone" columns are all required and cannot have null
values. These are some examples of how to apply different types of integrity constraints in
MySQL tables. By applying these constraints, we can ensure data accuracy and consistency in
our database.
Experiment 3
Experiments based on basic DML commands – SELECT, INSERT, UPDATE and DELETE.

SELECT:
The SELECT command is used to retrieve data from one or more tables in a database.
Example:
SELECT * FROM customers;
This command retrieves all columns and all rows from the "customers" table.

INSERT:
The INSERT command is used to insert new rows into a table.
Example:
INSERT INTO customers (name, email, phone)
VALUES ('John Doe', 'john@example.com', '555-1234');
This command inserts a new row into the "customers" table with the name, email, and phone .
UPDATE:
The UPDATE command is used to modify existing data in a table.
Example:
UPDATE customers
SET email = 'johndoe@example.com'
WHERE id = 1;
This command updates the email value for the row with id 1 in the "customers" table.

DELETE:
The DELETE command is used to remove rows from a table.
Example:
This command deletes the row with id 1 from the "customers" table. By experimenting with
these basic DML commands in MySQL, we can perform various operations on data in our
database, such as querying, inserting, updating, and deleting data. These commands are essential
for managing data in a database and can be used to perform complex operations when combined
with other SQL clauses and functions.
Experiment 4
Write the queries for implementing Built-in functions, GROUP BY, HAVING and ORDER BY.

Built-in Functions:
MySQL provides several built-in functions that can be used to manipulate and transform data.
Here's an example of a query that uses some of these functions:

SELECT CONCAT(first_name, ' ', last_name)

AS full_name, UPPER(email)

AS email_uppercase
FROM employees;
This query uses the CONCAT and UPPER functions to concatenate the first and last name
columns into a new "full_name" column and convert the email column to uppercase in the
"email_uppercase" column.
GROUP BY:
The GROUP BY clause is used to group rows in a result set based on a specified column or
expression. Here's an example of a query that uses GROUP BY:
SELECT department, COUNT(*) AS num_employees
FROM employees
GROUP BY department;
This query groups employees by department and counts the number of employees in each
department.

HAVING:
The HAVING clause is used to filter rows in a result set based on a specified condition.
Here's an example of a query that uses HAVING:
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
This query groups employees by department and calculates the average salary for each
department. The HAVING clause filters the result set to show only departments with an average
salary greater than 50,000.

ORDER BY:
The ORDER BY clause is used to sort the rows in a result set based on one or more columns.
Here's an example of a query that uses ORDER BY:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
This query selects the first name, last name, and salary columns from the "employees" table and
sorts the result set in descending order based on the salary column.

By using built-in functions, GROUP BY, HAVING, and ORDER BY clauses in MySQL
queries, we can perform more advanced data manipulations and analysis. These features allow
us to transform data, group and aggregate data, filter data based on conditions, and sort data in
various ways to gain insights from our data.
Experiment 5
Write the queries to implement the joins.

INNER JOIN:
The INNER JOIN keyword returns only the matching rows from both tables. Here's an example
of a query that uses INNER JOIN:

SELECT orders.order_id, customers.customer_name, orders.order_date FROM orders


INNER JOIN customers ON orders.customer_id = customers.customer_id;
This query selects the customer_name and order_id columns from the "customers" and "orders"
tables and joins the two tables on the customer_id column using LEFT JOIN. The result set
includes all rows from the "customers" table and only the matching rows from the "orders"
table.

RIGHT JOIN:
The RIGHT JOIN keyword returns all rows from the right table and the matching rows from the
left table. If there are no matching rows in the left table, the result set will contain NULL values.
Here's an example of a query that uses RIGHT JOIN: SELECT orders.order_id,
customers.customer_name
FROM orders
RIGHT JOIN customers ON orders.customer_id = customers.customer_id;

This query selects the order_id and customer_name columns from the "orders" and "customers" tables
and joins the two tables on the customer_id column using RIGHT JOIN. The
result set includes all rows from the "orders" from the "customers" table.
FULL OUTER JOIN:
MySQL does not support FULL OUTER JOIN, but we can simulate it using UNION and LEFT
JOIN and RIGHT JOIN. Here's an example of a query that simulates FULL OUTER JOIN:
SELECT customers.customer_name, orders.order_id
FROM customers
LEFT JOIN orders ON customers.customer_id =
orders.customer_id UNION
SELECT customers.customer_name, orders.order_id
FROM customers
RIGHT JOIN orders ON customers.customer_id = orders.customer_id This query selects the
customer_name and order_id columns from the "customers" and "orders" tables and simulates
FULL OUTER JOIN using UNION, LEFT JOIN, and RIGHT JOIN. The result set includes all
rows from both tables.

By using different types of joins in MySQL, we can combine data from multiple tables based on
common columns and perform more complex queries on our data. This allows us to retrieve and
analyze data that is stored across multiple tables in a database.
Experiment 6
Write the queries to implement the subqueries.
Basic Subquery:
A subquery is a query that is nested inside another query. Here's an example of a basic subquery:
SELECT customer_name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE
order_date = '2022-01-01');
This query selects the customer_name column from the "customers" table where the
customer_id is in the result set of a subquery that selects customer_id from the "orders" table
where the order_date is '2022-01-01'. The subquery is enclosed in parentheses and is executed
first.
Correlated Subquery:
A correlated subquery is a subquery that references a column from the outer query. Here's an
example of a correlated subquery:
SELECT customer_name, order_date, order_amount
FROM orders o
WHERE order_amount =
( SELECT
MAX(order_amount) FROM
orders
WHERE o.customer_id = customer_id
);
This query selects the customer_name, order_date, and order_amount columns from the "orders"
table where the order_amount is equal to the maximum order_amount for that customer. The
subquery is correlated with the outer query by referencing the customer_id column from the
outer query.
Subquery in a FROM Clause: A subquery can also be used in the FROM clause to create a
temporary table that can be used in the outer query. Here's an example of a subquery in a FROM
clause:
SELECT customer_name, num_orders
FROM (
SELECT customer_id, COUNT(*) AS num_orders
FROM orders
GROUP BY customer_id
) AS order_counts
JOIN customers ON order_counts.customer_id = customers.customer_id;
This query selects the customer_name and num_orders columns from a subquery that counts the
number of orders for each customer and groups them by customer_id. The subquery is used to
create a temporary table called "order_counts" that is joined with the "customers" table to get
the customer_name column.
By using subqueries in MySQL, we can perform more
complex queries that involve multiple tables and
conditions. Subqueries can also be used to create temporary
tables that can be joined with other tables to retrieve the
desired data.
Experiment 11:
Demonstrate the concept of Functions and Procedures.

In MySQL, functions and procedures are two types of database objects that can be used to execute a set of SQL
statements. Both functions and procedures can accept parameters, perform calculations or operations, and
return results. However, there are some differences between them.

Functions:
Functions in MySQL are used to perform a specific task and return a single value. Here's an example of how to
create a function:
CREATE FUNCTION my_function (param1 INT, param2 INT) RETURNS INT
BEGIN
DECLARE result INT;
SET result = param1 + param2; RETURN
result;
END;
In this example, we create a function called my_function that accepts two integer parameters and returns their
sum. We declare a local variable called result to store the calculated value and then use the RETURN statement
to return the result to the caller. To call the function, we can use the following query:
SELECT my_function(2,3);
This will return the value 5, which is the sum of the two parameters.

Procedures:
Procedures in MySQL are similar to functions, but they can be used to perform a set of operations that may not
necessarily return a value. Here's an example of how to create a procedure:
CREATE PROCEDURE my_procedure (IN param1 INT, IN param2 INT) BEGIN
UPDATE my_table SET column1 = param1 WHERE column2 = param2; END;
In this example, we create a procedure called my_procedure that accepts two integer parameters and updates a
table based on those parameters. We use the UPDATE statement to modify the data in the table.
To call the procedure, we can use the following query: CALL
my_procedure(1, 2);z
This will execute the procedure and update the my_table table accordingly.
Overall, functions and procedures are powerful tools in MySQL for performing calculations, operations, and
data manipulation. By defining custom functions and procedures, you can create more efficient and flexible
SQL code that can be reused across multiple queries and applications.
Experiment 12
Demonstrate the concept of Triggers.

In MySQL, triggers are special database objects that can be used to automatically execute SQL statements in
response to certain events or changes in the database. Triggers can be useful for implementing data validation,
auditing, or other types of business logic that require automatic responses to database events.

Here's an example of how to create a trigger in MySQL:


CREATE TRIGGER my_trigger
AFTER INSERT ON my_table FOR
EACH ROW
BEGIN
INSERT INTO my_log_table (timestamp, message) VALUES (NOW(), 'A new row was
inserted into my_table.');
END; CREATE TRIGGER my_trigger AFTER
INSERT ON my_table
FOR EACH ROW
BEGIN
INSERT INTO my_log_table (timestamp, message) VALUES (NOW(), 'A new row was
inserted into my_table.');
END;
In this example, we create a trigger called my_trigger that is fired after a new row is inserted into the my_table
table. We use the AFTER INSERT ON syntax to specify the event that triggers the trigger. We also use the
FOR EACH ROW clause to indicate that the trigger should be executed once for each row affected by the
event.

Inside the trigger, we use the INSERT INTO statement to insert a new row into the my_log_table table, which
records information about the event. We use the NOW() function to retrieve the current timestamp, and we
include a message to indicate that a new
row was inserted into the original table.

Once the trigger is created, it will automatically execute whenever a new row is inserted into the my_table
table. The trigger will insert a new row into the my_log_table table, recording the event.

Overall, triggers in MySQL are a powerful tool for implementing automatic responses to database events. By
defining custom triggers, you can automate tasks, enforce data integrity, and add auditing capabilities to your
database.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy