0% found this document useful (0 votes)
38 views72 pages

DBMS Lab1

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

DBMS Lab1

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

MySQL Tutorial

CLASS 1
MySQL commands
□ help \h
□ Quit /exit \q
□ Cancel the command \c
□ Change database use
Info about databases and tables
□ Listing the databases on the MySQL server host
■ >show databases;
□ Access/change database
■ >Use [database_name]
□ Showing the current selected database
■ > select database();
□ Showing tables in the current database
■ >show tables;
□ Showing the structure of a table
■ > describe [table_name]; or
■ > desc [table_name];
CREATE DATABASE
□ An SQL relation is defined using the CREATE
DATABASE command:
■ create database [database name];

□ Example
■ create database mydatabase;
SQL commands – Subgroups
DDL, DML, DCL, and TCL.
DDL Commands
□ DDL is short name of Data Definition Language, which deals
with database schemas and descriptions, of how the data
should reside in the database.

□ CREATE - to create a database and its objects like (table, index, views,
store procedure, function, and triggers)
□ ALTER - alters the structure of the existing database
□ DROP - delete objects from the database
□ TRUNCATE - remove all records from a table, including all spaces allocated
for the records are removed
□ COMMENT - add comments to the data dictionary
□ RENAME - rename an object
DML Commands
□ DML is short name of Data Manipulation Language which deals
with data manipulation and includes most common SQL
statements such SELECT, INSERT, UPDATE, DELETE, etc., and it is
used to store, modify, retrieve, delete and update data in a
database.
□ SELECT - retrieve data from a database
□ INSERT - insert data into a table
□ UPDATE - updates existing data within a table
□ DELETE - Delete all records from a database table
□ MERGE - UPSERT operation (insert or update)
□ CALL - call a PL/SQL or Java subprogram
□ EXPLAIN PLAN - interpretation of the data access path
□ LOCK TABLE - concurrency Control
DCL Commands
□ DCL is short name of Data Control Language which includes
commands such as GRANT and mostly concerned with rights,
permissions and other controls of the database system.

□ GRANT - allow users access privileges to the database


□ REVOKE - withdraw users access privileges given by using the GRANT
command
TCL Commands
□ TCL is short name of Transaction Control Language which
deals with a transaction within a database.
□ COMMIT - commits a Transaction
□ ROLLBACK - rollback a transaction in case of any error occurs
□ SAVEPOINT - to rollback the transaction making points within groups
□ SET TRANSACTION - specify characteristics of the transaction
MySQL data types

□ Supports a number of SQL standard data types in various categories.

Three main categories


□ Numeric types
□ DATE and TIME type
□ String
MySQL Numeric types
□MySQL supports all standard SQL numeric data types
▪ INTEGER
▪ SMALLINT
▪ DECIMAL
▪ NUMERIC

□Also supports approximate numeric data types


▪ FLOAT
▪ REAL
▪ DOUBLE PRECISION
DATETIME, DATE, and
TIMESTAMP Types
Types Description Display Format Range

DATETIME Use when you need YYYY-MM-DD '1000-01-01 00:00:00' to


values containing both HH:MM:SS '9999-12-31 23:59:59'.
date and time
information

DATE Use when you need only YYYY-MM-DD '1000-01-01' to '9999-


date information. 12-31'.

TIMESTAMP Values are converted YYYY-MM-DD '1970-01-01 00:00:01'


from the current time HH:MM:SS UTC to '2038-01-19
zone to UTC while 03:14:07' UTC
storing, and converted
back from UTC to the
current time zone when
retrieved
String
Types

□ The string types:


□ CHAR
□ VARCHAR
□ BINARY
□ VARBINARY
□ BLOB
□ TEXT
Type Description Display format Range in characters

CHAR Contains non- binary strings. Length is Trailing spaces are The length can be any value from 0 t
fixed as you declare while creating a table. removed. 255.
When stored, they are right-padded with
spaces to the specified length
VARCHAR Contains non- binary strings. Columns As stored. A value from 0 to
are variable-length strings 255 before MySQL
5.0.3, and 0 to
65,535 in 5.0.3 and later versions
BINARY Contains binary strings 0 to 255 BINARY

VARBINAR Y Contain binary strings. A value from 0 to 255 VARBINARY


before MySQL 5.0.3, and 0
to 65,535 in
5.0.3 and later versions

BLOB Large binary object that containing a TINYBLOB Maximum length of 255 characters.
variable amount of data. Values are treated
as binary strings. You don't need to MEDIUMBLOB Maximum length of 16777215
specify length while creating a column characters.
LONGBLOB Maximum length of 4294967295
characters
TEXT Values are treated as character TINYBLOB Maximum length of 255 characters.
strings having a character set
MEDIUMBLOB Maximum length of 16777215
characters.
Creation of Database Schema
and DML Commands
CREATE TABLE EMPLOYEE(Fname VARCHAR(20),Minit CHAR,Lname
VARCHAR(20),SSN INT,Bdate DATE,Address VARCHAR(50),Sex
CHAR,Salary INT,Super_ssn INT,Dno INT,PRIMARY KEY(SSN));
CREATE TABLE DEPARTMENT(Dname VARCHAR(20),Dnumber INT,Mgr_ssn
INT,Mgr_start_date DATE,PRIMARY KEY(Dnumber));
CREATE TABLE DEPT_LOCATIONS(Dnumber INT NOT NULL,Dlocation
VARCHAR(20),PRIMARY KEY(Dnumber, Dlocation));
CREATE TABLE PROJECT(Pname VARCHAR(20),Pnumber INT,Plocation
VARCHAR(20),Dnum INT,PRIMARY KEY(Pnumber));
CREATE TABLE WORKS_ON(Essn INT,Pno INT,Hours FLOAT,PRIMARY
KEY(Essn, Pno));
CREATE TABLE DEPENDENT(Essn INT,Dependent_name VARCHAR(20),Sex
CHAR,Bdate DATE,Relationship VARCHAR(20),PRIMARY KEY(Essn,
Dependent_name));
SHOW TABLES;
DESC DEPARTMENT;
ALTER TABLE DEPT_LOCATIONS ADD FOREIGN KEY(Dnumber)
REFERENCES DEPARTMENT(Dnumber);
ALTER TABLE PROJECT ADD FOREIGN KEY(Dnum) REFERENCES
DEPARTMENT(Dnumber);
ALTER TABLE WORKS_ON ADD FOREIGN KEY(Essn) REFERENCES
EMPLOYEE(SSN);
ALTER TABLE WORKS_ON ADD FOREIGN KEY(Pno) REFERENCES
PROJECT(Pnumber);
ALTER TABLE DEPENDENT ADD FOREIGN KEY(Essn) REFERENCES
EMPLOYEE(SSN);
ALTER TABLE EMPLOYEE ADD email VARCHAR(25);
DESC EMPLOYEE;
ALTER TABLE EMPLOYEE MODIFY email VARCHAR(10) NOT NULL;
SHOW COLUMNS FROM EMPLOYEE;
ALTER TABLE EMPLOYEE DROP COLUMN email;
DML COMMANDS

INSERT INTO EMPLOYEE VALUES('Jennifer', 'S', 'Wallace',


987654321,'19410620', '291 Berry, Bellaire, TX', 'F', 43000, NULL, 4 );
SELECT * FROM EMPLOYEE;
UPDATE EMPLOYEE SET Super_ssn = 888665555 where ssn = 987654321;
INSERT INTO PROJECT VALUES('ProductX', 1, 'Bellaire', 5);
CLASS 2
Create an ER diagram for the following scenario:
Shop Rite is a nationwide retail chain with their head office in New York has its retail
outlet presence across various cities in USA, and is popular for the various schemes and
the value for money that they bring to their customers. The customer can purchase items
from various retail outlets. Every retail outlet has a retail outlet manager and several
employees who are responsible for the operations at the retail outlet. An employee is
assigned to only one retail outlet. The Shop Rite management has an option to nominate
the dependents of employees for various beneficial schemes. Items can belong to three
categories namely A,B, and C as per the below table: Price Range Category
1-999 C
1000-4999 B
5000-99999 A

The purchasing of the items from different suppliers is based on the quotations that are
provided by various suppliers. The rules to purchase the items are defined as follows:
One supplier can provide quotations for different items. Different suppliers can provide
the quotation for the same item. For each item, a supplier has to provide a separate
quotation. Shop Rite management has the right to accept or reject a quotation based on
the quoted price. The management places the orders for the accepted quotations. Once
the supplier has supplied the ordered quantity, the quotation status will become closed.
• Create a database named COMPANY.
• For storing the supplier details, the supplier table needs to be
created. Table is created without any constraints.
Column name Data type

supplierid VARCHAR(6)

suppliername VARCHAR(30)

suppliercontactno VARCHAR(12)

supplieremailid VARCHAR(30)

Insert a record in the supplier table


VALUES('S1001','Giant Store', '203-237-2079’,'rachel1@easy.com’)

Write SQL statement to add a record into the “supplier” table for a supplier
without email id is as follows VALUES ('S1002’,'EBATs’,'115‐340‐2345’,
NULL)

Write SQL Query to retrieve the details of suppliers.


Alter table supplier with supplier id as primary key.
Alter table supplier where supplier id must not be left blank and it should not repeat too.

Create the table Retailstock with Retailoutletid and Itemcode as composite primary
key.
Column name Data type

Retailoutletid VARCHAR(6)

Itemcode VARCHAR(6)

Retailunitprice INT

Quantityavailable INT
Insert a record into retailstock table with:
1) Retailoutletid as ‘R1001’ and Itemcode as ‘I1001’.
2) Retailoutletid as ‘R1001’ and Itemcode as ‘I1002’.
3) Retailoutletid as ‘R1001’ and Itemcode as ‘I1001’.
4) Retailoutletid as ‘R1002’ and Itemcode as ‘I1001’.
5) Retailoutletid as NULL and Itemcode as ‘I1001’.
Create quotation table with supplierid as foreign key:

Column name Data type

quotationid VARCHAR(6)

supplierid VARCHAR(6)

itemcode VARCHAR(10)

quotedprice INT

quotationdate DATE

quotationstatus VARCHAR(10)
CLASS 3

DISTINCT, ORDER BY ,COUNT,GROUP BY,COUNT,


HAVING QUERIES
AIM

To familiarize DISTINCT, ORDER BY Commands.

• The SELECT DISTINCT command returns only distinct (different) values in the result
set.
• The ORDER BY command is used to sort the result set in ascending or descending
order.

To get a list of unique departments and their highest salaries, sorted by salary in
descending order.
Create item table is as mentioned
below.
1. Retrieve the different item types.
2. Retrieve the different item types and categories of the items.
3. Retrieve the itemcode, description and price with the increasing order of item’s
price.
4. Retrieve the different item types and categories of the items in the increasing order
of item types and categories.

Column Name Data Type Constraint


INSERT INTO
ITEMTABLE itemcode VARCHAR(6) Primary Key
VALUES ('1111',
'PC', 'INTEL itemtype VARCHAR(30)
PROCESSOR',
2000, 'A'); description VARCHAR(255) NOT NULL

price INT
COUNT ,GROUP BY , HAVING
AIM

To familiarize COUNT,GROUP BY & HAVING Commands.

COUNT: This function returns the number of rows


that matches a specified criterion.

GROUP BY: This clause groups rows that have the


same values into summary rows.

HAVING: This clause is used to filter groups based


on a specified condition.
CREATE TABLE workers
Column Name Data Type Constraint

id INT Primary Key

name VARCHAR(30) NOT NULL

email VARCHAR(25) DISTINCT

phone_no INT

salary INT

city VARCHAR(255)
• Insert to workers 10 tuples like (1, 'John', 'john@example.com', 1234567890,
40000, 'New York’)
• Count the number of workers in each city
• Count the number of workers for each combination of city and salary
• Count the number of workers in each city and order the results by the number
of employees in descending order
• Count the number of workers in each city where the average salary is greater
than $30,000
Create Column Name Data Type Constraint

order_id INT Primary Key


order
customer_id INT NOT NULL
table product_id INT NOT NULL

order_date DATE

quantity INT

total_amount INT

city VARCHAR(255)
• Count the number of orders in each city
• Count the number of orders in each city and order the results by the number of
orders in descending order
• Count the number of orders in each city where the average total amount is
greater than $100
• Count the number of distinct customers in each city
• Find the total quantity of products ordered in each city
• List the average total amount for each city, ordered by average total amount in
descending order
CLASS 4

VIEW
1. Create table Employee
2. Create table Department
3. CREATE VIEW RESEARCH_DPT
4. Display all the details of the created view

CREATE VIEW RESEARCH_DPT AS SELECT * FROM EMPLOYEE,DEPARTMENT WHERE


DNAME='Research' AND DNUMBER=DNO

SELECT * FROM RESEARCH_DPT


SELECT * FROM faculty WHERE college_code="idk" AND experience >=10;

SELECT * FROM faculty WHERE college_code="idk" AND qualification NOT IN


("mtech");

SELECT * FROM faculty WHERE college_code="idk" ORDER BY experience ASC;

SELECT COUNT(*) as faculty_count, college_name


FROM faculty,college
where faculty.college_code=college.college_code
GROUP BY college_name
HAVING COUNT(*) > 2;

select college_name,faculty_count
from fac_count
where faculty_count =
(select max(faculty_count) from fac_count) or faculty_count=(select
min(faculty_count)from fac_count);
CLASS 5

My SQL Functions
AIM
To perform SELECT operations along with SQL functions on a given table

Write SQL statements for the following requirements:

1. For a discount of 25.5% being offered on all FMCG item’s unit price,
display item code, existing unit price as “Old Price” and discounted price as
“New Price”. Round off the discounted price to two decimal values.
2. Retrieve the employee id, employee name of billing staff and the retail
outlet where they work. Perform a case insensitive search.
3. Retrieve the description of items which have more than 15 characters.
4. Display numeric part of supplier id.
5. Retrieve the maximum salary, minimum salary, total salary and average
salary of employees.
6. Retrieve the total number of items available in warehouse.
7. Retrieve the total number of orders made and the number of orders for
which payment has been done.
8. Retrieve the total number of different item types available.
CREATE TABLE item( itemcode VARCHAR(6) PRIMARY KEY, itemtype
VARCHAR(30), description VARCHAR(100) NOT NULL, price INT(10), reorderlevel
INT(6), quantityonhand INT(6), category VARCHAR(1) );

CREATE TABLE employee( empid INT(10) PRIMARY KEY, empname VARCHAR(40),


password VARCHAR(40), designation VARCHAR(20), emailid VARCHAR(30), contactno
INT(10), worksin VARCHAR(6) REFERENCES retailoutlet(retailoutletid), salary
INT(10) );

CREATE TABLE supplier( supplierid VARCHAR(6) PRIMARY KEY, suppliername


VARCHAR(30), suppliercontactno varchar(15), supplieremailid VARCHAR(30) );
CREATE TABLE orderstatus ( orderid VARCHAR(6) PRIMARY KEY,
quotationid VARCHAR(6) REFERENCES quotation(quotationid), qtyordered
INT(10) CHECK(qtyordered > 0), orderdate DATE, status VARCHAR(20)
CHECK(status in ('Ordered','Partial Delivery','Delivered')), paymentdate DATE,
amountpaid INT(10), paymentmode VARCHAR(20) CHECK(paymentmode in
('Cash','Cheque')) );

CREATE TABLE retailoutlet( retailoutletid VARCHAR(6) PRIMARY


KEY, retailoutletlocation VARCHAR(30) NOT
NULL, retailoutletmanagerid INT);

ALTER TABLE retailoutlet ADD FOREIGN KEY(retailoutletmanagerid)


REFERENCES employee (empid);
CLASS 6

DCL commands
Grant and revoke permissions
CREATE USER 'SOBHA'@'localhost' IDENTIFIED BY '1234’;
GRANT ALL PRIVILEGES ON mydb.* TO 'SOBHA'@'localhost’;
SHOW GRANTS FOR 'SOBHA'@'localhost’;
REVOKE INSERT ON mydb.* FROM 'SOBHA'@'localhost’;

Login to New User

sudo mysql -u SOBHA –p


CREATE DATABASE mydb;
USE mydb;
CREATE TABLE staff(no int);
INSERT INTO staff values(12);
CLASS 7

TCL commands
START TRANSACTION
COMMIT
ROLLBACK
SAVEPOINT
create database bank;
use bank;
CREATE TABLE IF NOT EXISTS employees (id INT AUTO_INCREMENT
PRIMARY KEY, name VARCHAR(100) NOT NULL,position VARCHAR(100),salary
DECIMAL(10, 2));
INSERT INTO employees (name, position, salary) VALUES ('Alice Johnson',
'Engineer', 75000.00);
INSERT INTO employees (name, position, salary) VALUES ('Bob Smith',
'Manager', 85000.00);
SELECT * FROM employees;

START TRANSACTION;
UPDATE employees SET salary = 80000.00 WHERE name = 'Alice Johnson’;
SELECT * FROM employees;
ROLLBACK;
SELECT * FROM employees;
START TRANSACTION;
UPDATE employees SET salary = 80000.00 WHERE name = 'Alice Johnson’;
SELECT * FROM employees;
COMMIT;
ROLLBACK;
SELECT * FROM employees;

START TRANSACTION;
savepoint a;
INSERT INTO employees (name, position, salary) VALUES ('Carol White',
'Analyst', 72000.00);
SELECT * FROM employees;
ROLLBACK to savepoint a;
SELECT * FROM employees;
CLASS 7

Trigger
CREATE DATABASE SHOP;
USE SHOP;

CREATE TABLE employees (


-> id INT AUTO_INCREMENT PRIMARY KEY,
-> name VARCHAR(100),
-> position VARCHAR(100),
-> salary DECIMAL(10, 2),
-> last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP
-> );

mysql> DELIMITER //
mysql> CREATE TRIGGER update_last_updated
-> BEFORE UPDATE ON employees
-> FOR EACH ROW
-> BEGIN
-> SET NEW.last_updated = CURRENT_TIMESTAMP;
-> END//
mysql> DELIMITER ;
SHOW TRIGGERS;
INSERT INTO employees (name, position, salary) VALUES ('Alice Johnson',
'Engineer', 75000.00);
SELECT * FROM employees;
UPDATE employees SET salary = 80000.00 WHERE name = 'Alice Johnson';
SELECT * FROM employees;
CLASS 8

SET OPERATIONS AND JOINS


CLASS 8

SET OPERATIONS AND JOINS


AIM: Implementation of set operations and join queries

The SQL Set operation 3. Create a table named ‘t2’ namely


is used to combine the columns rollno, present, absent,
two or more SQL percentage
SELECT statements.
4. Insert 5 rows into t1
Types of Set Operation
1. Union 5. Insert 5 rows into t2
2. Union All
3. Intersect 6. Find distinct roll no from the table t1
4. Minus
and t2 [union]
QUESTIONS
7. Find distinct roll no from the table t1
Write SQL statements for the following
and t2 [union all]
requirements:
8. Perform inner join operation
1. Create a database College
9. Perform left join operation
2. Create a table named ‘t1’ namely
columns rollno, firstname, lastname, 10. Perform right join operation

birthdate 11. Perform cross join operation

12. Perform intersection

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