Download as pdf
Download as pdf
You are on page 1of 28
Bangladesh University of Business & Technology Lab Report: 03 Course Title:Database System Course Code: CSE-207 Submitted By Submitted To Name: Omar Farque Name: Ahmed Shafkat ID: 22234103118 Lecturer intake:50 Department of CSE BUBT Section:3 Department of CSE Date:08-05-2024 Signature of the instructor Date:10-01-2024 We have learned following topic in the lab: Sure, here's a modified version of the list: 1. Data types: Understanding different data types used in databases, such as VARCHAR, INT, DATE, etc. 2. Creating a database: Learning how to create a new database using SQL commands like CREATE DATABASE. 3. Dropping a database: Understanding how to delete an existing database using SQL commands like DROP DATABASE. 4. Creating a table: Learning how to create a new table within a database using SQL commands like CREATE TABLE. 5. Dropping a table: Understanding how to delete an existing table within a database using SQL commands like DROP TABLE. 6. Adding a primary key to a table: Learning how to define a primary key for a table's column(s) to uniquely identify each row using SQL commands like ALTER TABLE. 7. Altering a table (Adding a primary key, Adding a column, Dropping a column): Understanding how to modify the structure of an existing table using SQL commands like ALTER TABLE, including adding or removing a primary key, adding new columns, and dropping existing columns. SQL What is Database? Database is a collection of interrelated data. What is DBMS? DBMS (Database Management System) is software used to create, manage, and organize databases. What is RDBMS? © RDBMS (Relational Database Management System) - is a DBMS based on the concept of tables (also called relations). * Data is organized into tables (also known as relations) with rows (records) and columns (attributes). « Eg-MySAL, PostgreSQL, Oracle etc. What is SQL? ‘SQL is Structured Query Language - used to store, manipulate and retrieve data from RDBMS. (itis not a database, it is a language used to interact with database) We use SQL for CRUD Operations : CREATE - To create databases, tables, insert tuples in tables etc READ - To read data present in the database. © UPDATE - Modify already inserted data, © DELETE - Delete database, table or specific data pointtuple/row or multiple rows. “Note - SQL keywords are NOT case sensitive. Eg: select is the same as SELECT in SQL. SQL vis MySQL ‘SQL is a language used to perform CRUD operations in Relational DB, while MySQL is a RDBMS that uses SQL. Database ‘SQL Data Types In SQL, data types define the kind of data that can be stored in a column or ve To See all data types of MYSQL, visit : htts://dev. mysql. com/doc/refman/8.O/en/data-types, him! Here are the frequently used SQL data types: DATATYPE DESCRIPTION USAGE CHAR string(0-255), can store characters of fixed length CHAR(50) VARCHAR string(0-255), can store characters up to given length | VARCHAR(50) BLOB string(0-65535), can store binary large object BLOB(1000) INT integer -2, 147,483,648 to 2,147,483,647 ) INT TINYINT integer(-128 to 127) TINYINT BIGINT integer( -9,223,372,036,854,775,808 to BIGINT 9,223,372,036,854,775,807 ) BIT can store x-bit values. x can range from 1 to 64 BIT) FLOAT Decimal number - with precision to 23 digits FLOAT DOUBLE Decimal number - with 24 to 53 digits DOUBLE BOOLEAN Boolean values 0 or 1 BOOLEAN DATE date in format of YYYY-MM-DD ranging from DATE 1000-01-01 to 9999-12-31 TIME HH:MM:SS TIME YEAR year in 4 digits format ranging from 1901 to 2155 YEAR *Note - CHAR is for fixed length & VARCHAR is for variable length strings. Generally, VARCHAR is better as it only occupies necessary memory & works more efficiently. We can also use UNSIGNED with datatypes when we only have positive values to add Eg - UNSIGNED INT 1. DQL (Data Query Language) : Used to retrieve data from databases. (SELEC. 2. DDL (Data Definition Language) : Used to create, alter, and delete database objects like tables, indexes, etc. (CREATE, DROP, ALTER, RENAME, TRUNCATE) 3. DML (Data Manipulation Language): Used to modify the database. (INSERT, UPDATE, DELETE) 4. DCL (Data Contro! Language): Used to grant & revoke permissions. (GRANT, REVOKE) 5. TCL (Transaction Control Language): Used to manage transactions. (COMMIT, ROLLBACK, START TRANSACTIONS, SAVEPOINT) 1. Data Definition Language (DDL) Data Definition Language (DDL) is a subset of SQL (Structured Query Language) responsible for defining and managing the structure of databases and their objects. DDL commands enable you to create, modify, and delete database objects like tables, indexes, constraints, and more. Key DDL Commands are: © CREATE TABLE: © Used to create a new table in the database. © Specifies the table name, column names, data types, constraints, and more. © Example: CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50), salary DECIMAL(10, 2)); © ALTER TABLE: © Used to modify the structure of an existing table. © You can add, modify, or drop columns, constraints, and more. © Example: ALTER TABLE employees ADD COLUMN email VARCHAR(100); © DROP TABLE: © Used to delete an existing table along with its data and structure. © Example: DROP TABLE employees; 1. How to create Database? CREATE DATABASE lab_1_S0_3; 2. How to create Database? CREATE TABLE student ( ID INT, Name VARCHAR(200), Email VARCHAR(215), GPA FLOAT, ‘Address VARCHAR(205) i 3. How to Drop a Table ; DROP Table_name ; For Example DROP Table student ; 4. How to add primary key to the table? CREATE TABLE student ( ID INT PRIMARY KEY, Name VARCHAR(200), Email VARCHAR(215), CGPA FLOAT, Address VARCHAR(205) 5.How to alter table & when it use? If we forget to set primary key while creating the table ,we can use alter table to set primary key; For example: First of all we Drop the column, LKE- ALTER TABLE student DROP COLUMN ID; Now we adds anew ID column as the primary key : ALTER TABLE student ADD COLUMN ID INT AUTO_INCREMENT PRIMARY KEY; If we want to add extra column to an existing table we can use alter table to add column? Yes ! we can use the ALTER TABLE statement to add a new column to an e) ing table, Like ALTER TABLE table name ADD column_name column_definition; For Example: ALTER TABLE student ADD age INT; Press CtrleEnter to eecute query >EWEATE DATABASE Tab 1.50.3; DEREATE TABLE student ( ID INT, lone VARCHAR(2#9), Eat VARCHAR(2I5), COPA FLORT, Address VARCHAR( 205) 5 >SELECT * FROM “student” >OnOP TABLE student CREATE TASLE student ( 1D INT PRIMARY KEY, Mane VARGWAR(200), Email VARCHAR(215), CGPA FLOAT, Address VARCHER(205) ); SELECT © FROM “student a ALTER TABLE student O80 COLL 105 ‘ALTER TABLE student ADD COLL ID INT AUTO_IICREMENT PRIFARY KEYS DALTER TABLE student 400 age IT; >SELECT * FRON student; 1.Create Database: CREATE DATABASE lab_3_50_3; 2. Create table: CREATE TABLE customer( ID int, Name varchar(215), Address varchar(200), Phone varchar(205), Email varchar(235), Country varchar(245), PRIMARY KEY(ID) 3. Alter table to add unique key! ALTER TABLE customer ADD CONSTRAINT unique_email UNIQUE (Email); 4.Insert Information Into the table; INSERT INTO customer (ID, Name, Address, Phone, Email, Country) VALUES (1, John Doe', '123 Main Street', '555-1234', john@example.com', 'USA'), (2, ‘Jane Smith’, '456 Elm Street, '555-5678", ‘jane@example.com’, ‘Canada'), (3, ‘Alice Johnson’, '789 Oak Street’, '555-9012’, ‘alice@example.com’, 'UK']; 5.Various types of operation: a. Print all information... Querie }: SELECT * FROM customer. b. Print Customer from outside Canada... Queries : SELECT * FROM customer WHERE Country <> 'Canada'; C. Print customer whose ID ID 789. Queries: SELECT * FROM customer WHERE ID = 789; Necessary Table for this lab: (Pangan npn ox ua ca Aen] = "BB testa is SOL ey Information table : (Pig i Sk ra PP de Rh] Cis inh stoel % ~) raion Sebi [om oT ene Ate on sm — (26 Cay © Done 1 Doe Dike See 553 KAM com USA (PE Steapy @ Dake 2 Ine nih AEE Ein LEE jeep Cas (758 HOw @ Dee 3 Aks nen TODOS SST Hee « LL Coma Weed yee Hexy Que get Sova | nambertems 25 ¥) mos [See ie santero Console. res eter to eatery DATE SE ab 383 DHEATE LE caste 10 it, ne cary Aes ecar( 2), tae ard >SELECT * ON stn ta car), Contry varcar( 2), PRT HED) ) >A I customer (1, Nes, Pie, Ea, Cry VES (L "hn oe’, “1 Pain Stet >SELECT * HO extn; S51, beam 6 tn tet. >SELECT * ON stone MERE Cty © Cal >SELECT * FO castne WERE 0 «75; Date :31 -01-2024 Lab4 We have learned following topic in the lab: 1Perform various query operations on an existing table.” Necessary queries for these Lab : First we create a database ‘Lab_4_50_3” Then create a table ‘product’. Query for Table: CREATE TABLE product ( ProductName varchar(50), Description varchar(50), Price decimal(10, 2), Available int, Madetn varchar(50) INSERT INTO product (ProductName, Description, Price, Available, Madein) VALUES (‘cap', 'Classic', 224.00, 100, 'BD'); INSERT INTO product (ProductName, Description, Price, Available, Madein) VALUES (‘pen’, 'Red', 14.80, 500, 'China’); INSERT INTO product (ProductName, Description, Price, Available, MadeIn) VALUES (‘soap’, 'Lux', 60.50, 300, 'UK'); INSERT INTO product (ProductName, Description, Price, Available, Made!In) VALUES (‘light', 'Led Light’, 181.56, 400, 'BD'); aa Gn Bm 8 on tet tpt Re ee | [cea ntact ia in aceite 9 a | vamemtseemamentniemny Ltn S11 * Mn “probes (Pig ie En SL Cle HP cat] Rak] C1 Stora | Nambia: 25 +| aro [Seite = Guse — Ztm1OhD cy fd ke a sop a0 amu jet lige SSD Ci Stonat | Nimbus 25 v| aro S ite (amt oberon | a)Find maximum price : Queries: SELECT MAX(Price) AS MaxPrice FROM product; b) Find second maximum price: Queries: sevect MAx(Price) AS SecondMaxPrice FROM product WHERE Price < (SELECT MAX(Price) FROM product); C)Find total of price column: Queries: SELECT SUM(Price) FROM product; D)Find minimum available product: Queries: SELECT MIN(Available), tem FROM ‘product’; E)Find average of available product: Queries: SELECT AVG(Available) FROM ‘product’; F)Print the Items whose value is less than average value: Queries: SELECT Item FROM ‘product’ WHERE Price <= (SELECT AVG(Price) FROM ‘product’); G)Print average value of each country: Queries: SELECT AVG(Price), Made_In FROM ‘product’ GROUP BY Made_In; H)Print the Item Which product has maximum amount of stock: Queries: SELECT Item, MAX(Price* Available) FROM ‘product’ WHERE (Price*Available)=(SELECT MAX(Price8Available) FROM ‘product’) i)Find the total number of row: Queries: SELECT COUNT(Item) FROM ‘product’; J)Find price between 60-160: Queries: SELECT Price FROM ‘product’ WHERE Price BETWEEN 60 AND 160; K)Increase each price by 10%: Queries: UPDATE product SET Price=Price*1.1 L)Again increase Chinese product price by 20% and print: Queries: UPDATE product SET Price=Price*1.2 WHERE Made_in='China’; SELECT Price FROM ‘product’ WHRE Made_in=’China’; M)Now print difference between light and soap price: Queries: (SELECT price FROM products WHERE product_name = 'light ') (SELECT price FROM products WHERE product_name = 'soap') AS price_difference; N)Calculate % of comparison: Queries: SELECT ((SELECT Price FROM products WHERE product_name = 'light') - (SELECT Price FROM products WHERE product_name = 'soap')) / (SELECT Price FROM products WHERE product_name = 'light') * 100 AS Price_difference_percentage; Seater eee wee Date:05-02-2024 rid ‘order_id * toe ao tw note Queries that we performed in today’s lab: 1.Print Full Name of every customers. Queries: SELECT CONCAT(first.name, * , last_name) AS Full_Name FROM Customers; 2.Country wise average age of customers Queries: SELECT AVG(age) AS Average Age, country FROM Customers GROUP BY country; 3.Customer id 4 which item? Queries: SELECT Items FROM Orders WHERE customer_id = 4; 4.Average Cart Value of a order. Queries: SELECT AVG(amount) AS Average Cart_Value FROM Orders; 5.Who spend maximum amount in the market in his/her lifetime? Queries: SELECT ccustomer_id, CONCAT(cfirst_name, ", clast_name) AS full_name, MAX(o.amount) AS max_amount_spent FROM Orders 0 JOIN Customers ¢ ON o.customer.id = c.customer.id GROUP BY c.customer_id, full name ORDER BY max_amount_spent DESC uMiT 1 {6.Print the pending item product list. Queries: SELECT item FROM OrdersiOIN Shippings ON Shippings shipping i (Orders order idWHERE Shippings status = Pending’; First of all we Create a Database :Lab_6_50_3 Then we create a Table : Table queries: CREATE TABLE customer ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(300), email VARCHAR(S50) ) CREATE TABLE orders ( o_id INT AUTO_INCREMENT PRIMARY KEY, cid INT, o_date DATE, o_cart TEXT, FOREIGN KEY (c_id) REFERENCES customer(c_id) he Bowe smcare fy Sob 5s bt | nt int ie Csi itn 08 He tatenrence (Rt ee ‘name pe Calan mie at na Cam ta sae Oew> sm to exe ‘AO_MOREMENT 7 Char @ Op We Penance) ate nial Ye HL O28 2 Oe Me © > esos wer) mt guna Ys NRL 2 a9» @ 00» Me 0 tem race) tant pal ve ete Yo 2 00 Me TL Cone wmsicms Bone yctage —@Dm —phinwy tine nts Spd Shesncalctes yams mont cone Gre Aropetinmncse @ eB Teiale Ppl pies Beall ct) (art (GS Activate Windows Stee sen roe cererren se ace SS ie i res ese Sr mcxcuent Sone bene Zee bene me pre mie ocean ta moe 1.Natural Join two tables: SELECT * FROM customer NATURAL JOIN orders; 2.Left Join: SELECT * FROM customer LEFT JOIN orders ON customer.c_id = orders.c_id; 3.Right Join: SELECT * FROM customer RIGHT JOIN orders ON customer.c_id = orders.c_id; 4.Full Join SELECT * FROM customer FULL JOIN orders ON customer.c_id = orders.c. 5.Print order details of Dhaka's customer SELECT * FROM customer JOIN orders ON customer.c_id = orders.c_id WHERE customer.c_address LIKE ‘%Dhaka%'; 6.Total sell of each district SELECT SUBSTRING _INDEX(c_address, ‘', 1) AS district, SUM(o_amount) AS total sell FROM customer JOIN orders ON customer.c_id = orders.c.id GROUP BY district; 7.Who buy products on 2 nd February 2024? SELECT ccname, 0.0_id, 0.0_date FROM customer ¢ JOIN orders 0 ON c.c.id = 0.¢ id WHERE 0.0_date = ‘2024-02-02; 8.Average sell of each date SELECT date, AVG(o_amount) AS average sell FROM orders GROUP BY 0 date; phpMyAdmin amvoge twee He Scare SOL Sach net 5 Fapert pt = Pee 4 Opto Tag 3 Te Se vcore ens nie (mr eoer e (I) RE rer Pe i See >= nee meu a ena =a oF See ce See o eta e areas a ve ar aa SaaS oS macs Some SRL RE ee = Serta ee ew 1S mest | T= ware Boma >t or ete tr et = wet Lab 7) In today’s lab, task was to design a database according to the given demo: Provided Demo: Completed Tas! fear cis env ect Ors) i “ “eratase_sopama_ Oe Lam toe ~e cine comin Mo min Year) ee Ty PraduecanagonD tt) one eemacsene eae | hanes Seca + PraduCaagon( it) r 2 deg: ere) ue va) Hoses ere vemsmmsie Mo) Jo 200 20m nampa 10:4) ion mt) pempeee0me) Bis a da eye en cues rts) {eres rar) ‘tye a) aes a) 1 eptne) sae) va Regent) came sea) 2 may ee) Consol DALTEN TILE “city sins” ABD PINAR KEY Eh" DCAEATE TABLE Castner. sims CustomrIO INT PRIMINY HEY, Contonertane warhar(259), Ades warehar299) CYID TMT, FOREN HEY (CYB) REFER. Dene TABLE Produc. ataory.inesion ProfectcatgeryiD IT PRIMARY KEY, Hae varchr(29),oesripionvarcar(38),unipeicewartar355)) DeMAIE TABLE Pred Qlneelon SroductO IMI PRIMARY KY, Padua varchar, ProMuetEsagery/ID IMT, FOREIGN HEY (roduc tagoy10) REFERENCES — RAE TABLE Sale ProductIO Sat, Grdroate Int BRIM HEY, CastonertO IAT, CapoyeerD nt Total Int, Guntiy im scoot mmer(2,2), FOREIGN — DERCATE TABLE tine Glnnsion Order Sk PRR HEY, OrerBte nts Yeor Inte Quarter Smt, Meth in FOREN KC (rdeoate REFEREES saes(orerDa- Some key points that we should keep in mind to create relational database: © Draw a demo database schema at first «Determine the Primary key and Foreign key which is a must * Start creating the table from Left-to-Right «Sometimes queries might not work as expected, so we should try in different ways Lab 99 In todays lab, we learned how to draw an ER diagram using online based tool draw.io: Lab work: ee oper coo = — - = Es Process to draw this ER diagram: At first we have to go to draw.io website Then we have to select a create new project and select the directory path to save the program © Then select ER diagram format and select necessary objects for drawing an er diagram

You might also like