0% found this document useful (0 votes)
13 views78 pages

DBMS Lab SCMS

The document contains a series of exercises aimed at understanding various SQL commands including DDL, DML, and constraints. It covers creating databases and tables, inserting, updating, and deleting records, as well as applying constraints like primary keys and foreign keys. Additionally, it discusses creating indexes and using SELECT queries with conditions.

Uploaded by

alfiyaashraf1114
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)
13 views78 pages

DBMS Lab SCMS

The document contains a series of exercises aimed at understanding various SQL commands including DDL, DML, and constraints. It covers creating databases and tables, inserting, updating, and deleting records, as well as applying constraints like primary keys and foreign keys. Additionally, it discusses creating indexes and using SELECT queries with conditions.

Uploaded by

alfiyaashraf1114
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/ 78

................................. ...........................

EXERCISE 1
Aim : To understand about DDL Commands
1. Create a database called “SUPERMARKET”

Query : CREATE DATABASE SUPERMARKET

2. Create a table ‘Product’ with the following fields in the above database.
Col Name DataType Width
PtdId Integer 11
PdtCode Char 3
Name Varchar 20
Quantity Integer 11
Price Decimal (7,2)

Query : CREATE TABLE PRODUCT(PDTID INT(11),PDTCODE


CHAR(3),NAME VARCHAR(20),QUANTITY INT,PRICE DECIMAL(7,2));

3. Check whether Product table has been created.

Query : SHOW TABLES;


................................. ...........................

4. Describe the fields of the Product table.

Query : DESC PRODUCT;

5. Insert multiple rows.

Query : INSERT INTO PRODUCT VALUES(101,”PEN”,”LEXI”,10,5),


(102,”PCL”,”NATARAJ”,20,3),(103,”SHP”,”DOVE
SHAMPOO”,1,110),(104,”CDR”,”DOVE HAIRFALL PRVTN”,1,150);

6. Insert “Null” value into the PdtId field

Query : INSERT INTO PRODUCT VALUES(NULL,”NP”,”DAZLER


NAILPOLISH”,1,55);

7. Insert values into the selected columns

Query : INSERT INTO PRODUCT(PDTID,NAME,PRICE)


VALUES(106,”FEVISTICK”,20);
................................. ...........................

8. Select all the details from the product table.


Query : SELECT * FROM PRODUCT;

9. Remove last row.

Query : DELETE FROM PRODUCT WHERE PDTID=106;

10. Select first two columns of the table.

Query : SELECT PDTID,PDTCODE FROM PRODUCT;

11. Select name and price of the product where price is less than 10

Query : SELECT NAME,PRICE FROM PRODUCT WHERE PRICE<10;


................................. ...........................

12. Select name and quantity of those product whose quantity is greater than or
equal to 10

Query :SELECT NAME,QUANTITY FROM PRODUCT WHERE


QUANTITY>=10;

13. Select name and price of product where product code is Pen

Query : SELECT NAME,PRICE FROM PRODUCT WHERE


PDTCODE=”PEN”;
................................. ...........................

Exercise 2
Aim : To understand about ALTER, UPDATE & RENAME Commands

1. Create the following table from the following description of the CDS table
Field Type Null Key Default Extra
CdId Int(3) Pk Null auto_increment
Artist Varchar(20) yes Null
Title Varchar(20) Yes Null
Year Int(4) Yes Null
Label Varchar(20) Yes Null
Bought date Yes Null

Query : CREATE TABLE CDS(CDID INT(3) PRIMARY KEY


AUTO_INCREMENT,ARTIST VARCHAR(20),TITLE
VARCHAR(20),YEAR INT(4),LABEL VARCHAR(20),BOUGHT DATE);

2. Insert the following values into the CDS Table


CdId Artist Title Year Label Bought
1 Jamiroquai a funk odyssey 2001 Sony 2001-09-
sogo2 01
2 Jamiroquai a funk odyssey 2001 Sony 2001-09-
sogo2 01

Query : INSERT INTO CDS VALUES(1,”JAMIROQUAI”,”A FUN


ODYSSEY”,2001,”SONY SOGO2”,”2001-09-01”), (2,”JAMIROQUAI”,”A
FUN ODYSSEY”,2001,”SONY SOGO2”,”2001-09-01”);

3. Change the second rows title into “Wrong Title”


Query : UPDATE CDS SET TITLE=”WRONG TITLE” WHERE CDID=2;
................................. ...........................

4. Create a table called Company


Field Type Null Key Default Extra
ComId Int Not null Null
Name Varchar Yes Null
Address Varchar Yes Null
Phone Int Yes 9999999999

Query :CREATE TABLE COMPANY(COMID INT(10) NOT NULL, NAME


VARCHAR(20),ADDRESS VARCHAR(20), PHONE INT DEFAULT
99999999);

5. Make the ComId as Primary Key

Query : ALTER TABLE COMPANY ADD PRIMARY KEY(COMID);

6. Add a new attribute called “fax” as integer type

Query : ALTER TABLE COMPANY ADD FAX INT(10);


................................. ...........................

7. Drop the newly added column called “fax”

Query : ALTER TABLE COMPANY DROP FAX;

8. Write a SQL statement to add a columns Country_ID(varchar) as the first


column of the table.
Query : ALTER TABLE COMPANY ADD Country_ID varchar(6) FIRST;

9. Write a SQL statement to add a column state after Address column to the table.

Query : ALTER TABLE COMPANY ADD state varchar(20) AFTER


Address;
................................. ...........................

10. Write a SQL statement to change the name of the column state to
state_province, keeping the data type and size same.

Query : ALTER TABLE COMPANY CHANGE state State_Province


varchar(20);

11. Drop the primary key

Query : ALTER TABLE COMPANY DROP PRIMARY KEY;


................................. ...........................

12. Change the data type of the column ComId to Char

Query: ALTER TABLE COMPANY MODIFY COMID CHAR;

13. Change the table name Company into Cmpny.

Query : RENAME TABLE COMPANY TO CMPNY;


................................. ...........................

14. Create a table Employee(empid,fname,lname,email,phone,desgn,salary

Query : CREATE TABLE employee(empid varchar(6) primary key, fname


varchar(20),lname varchar(20), email varchar(30), phone int,desgn
varchar(20),salary decimal(7,2));

15. Insert 3 rows

Query : INSERT INTO employee VALUES("e101","Vinitha","T


S","[email protected]",999999999,"Manager",65000.00),
("e102","Babitha","S","[email protected]",999997589,"Assistant
Manager",50000.00),("e103","Steve","Thomas","[email protected]",99
9998524,"HR",60000.00);

16. Update the email column as NOT AVAILABLE.

Query : UPDATE employee SET email='not available';


................................. ...........................

17. Update the values of email as [email protected]. (Hint: Use CONCAT )


Query : UPDATE employee SET email=CONCAT(fname,”@gmail.com”);
................................. ...........................

Exercise 3
Aim : To understand about foreign key constraint

1.Create a table “SPECIES” with the following fields: ID Integer Primary Key,
Name Varchar 10.

Query : CREATE TABLE SPECIES(ID INT PRIMARY KEY,NAME


VARCHAR(20));

2. Insert some values into the species.

Query : INSERT INTO SPECIES VALUES(1,”ANIMAL”), (2,”BIRDS”),


(3,”INSECTS”);

3. Create anothet table “ZOO” with the fields: SerialNo Integer PK, F_Id
Integer FK, Name Varchar 23.

Query : CREATE TABLE ZOO(SNO INT PRIMARY KEY,FID INT,NAME


VARCHAR(20), FOREIGN KEY(FID) REFERENCES SPECIES(ID));
................................. ...........................

4. Insert some values into the ZOO.

Query : INSERT INTO ZOO VALUES(1,1,”MONKEY”),


(2,2,”PIGEON”),(3,3,”SPIDER”),(4,1,”WHITE TIGER”),(5,1,”LION”),
(6,2,”PEACOCK”);
................................. ...........................

Exercise 4
Aim : FK Constarints defined with a DELETE Cascade.

1. Create a table EmployeeMaster with the fields –EmpId as its PK, EmpName,
EmpDesgn, ManagerId.

Query : CREATE TABLE EMPLOYEE_MASTER(EMPID INT PRIMARY


KEY,EMPNAME VARCHAR(20), EMPDESGN VARCHAR(20),
MANAGERID INT);

2. Create a table TransMaster with its FK as its TransEmployee with ON


DELETE CASCADE option. The FK references EmpId, which is the PK
Column in the EmployeeMaster Table.

Query : CREATE TABLE TRANSMASTER(TRANSID


VARCHAR(3),CUSTID VARCHAR(3), TRANSEMP INT,TRANSDATE
DATE,AMT DECIMAL(7,2), FOREIGN KEY(TRANSEMP) REFERENCES
EMPLOYEE_MASTER(EMPID) ON DELETE CASCADE);

3. Insert some records on both the tables.

Query : INSERT INTO EMPLOYEE_MASTER VALUES


(101,”MIDHUN”,”ASS.MNGR”,1),(102,”RAHUL”,”TEAM
LEADER”,1),(103,”ASMI”,”DEVELOPER”,1),
(104,”NEENA”,”ANALYST”,1) ,(105,”GAYATHRI”,”TESTING
ANALYST”,1);
................................. ...........................

INSERT INTO TRANSMASTER VALUES(“T01”,”C01”,101,”2023-05-


22”,50000.00), (“T02”,”CO2”,101,”2023-06-10”,75000.00),
(“T03”,”CO3”,101,”2023-02-14”,60000.00), (“T04”,”CO4”,101,”2023-07-
15”,65000.00), (“T05”,”CO5”,101,”2023-10-20”,55000.00);

4. View the data in both the tables


Query : SELECT * FROM EMPLOYEE_MASTER;

SELECT * FROM TRANSMASTER;

5. Delete the records in the table TransMaster with Custid as ‘C01’(c zero one)

Query : DELETE FROM TRANSMASTER WHERE CUSTID = “C01”;


................................. ...........................

6. Delete records from EmpMaster with EmpId 105

Query : DELETE FROM EmployeeMaster WHERE EmpID=105;

7. Display the instances in both the tables.

Query : SELECT * FROM EMPLOYEE_MASTER;


SELECT * FROM TRANSMASTER;
................................. ...........................

EXERCISE 4
Aim : Check, Unique, Default and NotNull constraints
Note : CHECK constraint will not working on Mysql 5.5.
1. To set a unique constraint at the column level for the name field in the
“CategoryMaster” table: Category_id varchar,name varchar

Query : CREATE TABLE CategoryMaster(Category_id varchar(6),name


varchar(25) UNIQUE);

2. To set a unique constraint at the table level for the EmployeeMaster table :
EmpId varchar, name varchar,design varchar,mangrId varchar. Name is unique

Query : CREATE TABLE EmployeeMaster(EmpId varchar(6), name


varchar(25),design varchar(25),mangrId varchar(6),UNIQUE(name));

3. (To set a default value for the column PaymentTerms in the CompanyMaster
table : CompnyId varchar,name varchar,address varchar,contactPerson
varchar,PaymentTerms varchar default value is 100% advanced payment.

Query : CREATE TABLE CompanyMaster(CompnyId varchar(6),name


varchar(25) ,address varchar(40),contactPerson varchar(25),PaymentTerms
varchar(25) default “100% advanced payment”);

4. To set a CHECK Constarint on the Pid column and NotNull constraint for the
fields Pid and Lastname of the Person Table. The check constraint specifies
that the column Pid must only include integer greater than 0.

Query : CREATE TABLE Person(Pid int NOT NULL


CHECK(Pid>0),Lastname varchar(25) NOT NULL,Firstname
varchar(25),address varchar(30));
................................. ...........................

EXERCISE 5
Aim : Creating an Index for a table
Note: Index is used to reduce the execution time and maximize the processing
speed.
Here since we are dealing with very small table,the execution time wont show
much changes even before and after the index creation.

1. Create a table on Candidate and ClientAddress and insert few rows.


Query : CREATE TABLE CANDIDATE(CANDID INT PRIMARY
KEY,CANDNAME VARCHAR(20));

CREATE TABLE CLIENTADDRESS(CLID INT,CLINTNAME


VARCHAR(20), CLIENTDISEASE VARCHAR(20),CLIENTAGE
INT,CLIENTADDRESS VARCHAR(50),CLIENTDRID INT);

INSERT INTO CANDIDATE VALUES


(101,”DINESH”),(102,”GEETHA”),(103,”NEETHU”),
(104,”SREERAM”),(105,”BHARATH”);

INSERT INTO CLIENTADDRESS


VALUES(201,”DILEEP”,”DIABETIC”,45,”KKKKKKKK”,101),
(202,”GEETHU”,”THYROID”,35,”GGGGGGGG”,102),
(203,”SREEHARI”,”FEVER”,5,”OOOOOOOO”,103),
(204,”PARVATHY”,”PCOD”,38,”PPPPPPPPP”,102),
(205,”GEETH”,”PRESSURE”,40,”LLLLLLLLL”,105);

2. Display the CandidateName of the Candidate.


Query : SELECT CANDNAME FROM CANDIDATE;
................................. ...........................

3. Create a simple index on the cand_id column of the Candidate table.


Query: CREATE INDEX candidateIDX on CANDIDATE(CANDID);

4. Check whether there is an index bound to the column cand_id

Query: SHOW INDEX from CANDIDATE;

5. Display the CandidateName of the Candidate.

Query : SELECT CANDNAME FROM CANDIDATE;


................................. ...........................

6. Drop the index of cand_id

Syntax : ALTER TABLE CANDIDATE DROP INDEX candidateIDX;

7. Display the ClientId,ClientName of the ClientAddress.

Query : SELECT CLID,CLINTNAME FROM CLIENTADDRESS;

8. Create a composite index

Syntax : CREATE INDEX idx1 on CLIENTADDRESS(CLID,CLINTNAME);

9. Check whether there is an index bound or not

Syntax : SHOW INDEX from CLIENTADDRESS;


................................. ...........................

10. Display the ClientId,ClientName of the ClientAddress


Query : SELECT CLID,CLINTNAME FROM CLIENTADDRESS;

11. Drop the index of ClientAddress

Syntax : ALTER TABLE CLIENTADDRESS DROP INDEX idx1;

12. Create a unique index ClientAddress

Syntax : CREATE UNIQUE INDEX idx2 on CLIENTADDRESS (CLID);


................................. ...........................

EXERCISE 6
Aim : Familiarizing SELECT query,LIKE operator,NOT LIKE
1. Create a table empdetails :eid varchar pk,ename varchar,edesgn varchar,esal
int, yearofJoining int
Query : CREATE TABLE EMPDETAILS(EID VARCHAR(5) PRIMARY
KEY, ENAME VARCHAR(20), EDESGN VARCHAR(20), ESAL INT, YOJ
INT);

2. Insert 5 values(Edesgn should have


AssistantManager,Manager,Salesman,Supervisor, Cashier, then salary should
be 20000,22000,27000,45000,70000.
Query : INSERT INTO EMPDETAILS VALUES
('E01','Tim','Manager','70000','2018'), ('E02','Jim','Assistant
Manager','45000','2020'), ('E03','Tom','Supervisor','27000','2021'),
('E04','Travis','Salesman','22000','2023'), ('E05','John','Cashier','20000','2017');
3. Select all data
Query : SELECT * FROM EMPDETAILS;

4. Select all rows but specified column say ename

Query : SELECT ENAME FROM EMPDETAILS;


................................. ...........................

5. Select all columns but specified row sat edesgn is ‘manager’

Query : SELECT * FROM EMPDETAILS WHERE EDESGN='manager';

6. Select specified column and rows like ename and edesgn where salary less than
25000.

Query : SELECT ENAME,EDESGN FROM EMPDETAILS WHERE ESAL <


25000;

Select non duplicating rows(unique rows of edesgn.)

Query : SELECT DISTINCT EDESGN FROM EMPDETAILS;


................................. ...........................

7. Get the edesgn of all the employees who are not ‘Salesman’(symbol is <>)

Query : SELECT EDESGN FROM EMPDETAILS WHERE EDESGN <>


'salesman';

8. Get the details of the employee whose edesgn starts with S.(hint s%)

Query : SELECT * FROM EMPDETAILS WHERE EDESGN LIKE 'S%';

9. Get the details of the employee whose name’s 3rd letter is ‘a’.(hint __a%)

Query : SELECT * FROM EMPDETAILS WHERE ENAME LIKE '__a%';

10. Get the names of employee whose name has a letter ‘a’(hint %a%)

Query : SELECT * FROM EMPDETAILS WHERE ENAME LIKE '%a%';

11. Get the names of employee whose name does not contain a letter ‘a’(hint NOT
LIKE ‘%a%’)

Query : SELECT * FROM EMPDETAILS WHERE ENAME NOT LIKE


'%a%';
................................. ...........................

12. Get the names of employee whose name has first letter as either ‘a’ or “p” or
“t”(hint ‘[apt]%’ or use logical operators)

Query : SELECT * FROM EMPDETAILS WHERE ENAME LIKE ‘a%’ OR


ENAME LIKE ‘p%’ OR ENAME LIKE ‘t%’;

13. Get the employee names where their joining year us 2000,2015,2018 (use IN
operator).

Query : SELECT ENAME FROM EMPDETAILS WHERE YOJ


IN(2000,2015,2018);
................................. ...........................

14. Get the employee names whose salary in between 25000 and 50000

Query : SELECT ENAME FROM EMPDETAILS WHERE ESAL BETWEEN


25000 AND 50000;

15. Get the names of employee whose joining year is after 2010 or eid is EMP001
or EMP005. (use IN operator).

Query : SELECT ENAME FROM EMPDETAILS WHERE YOJ>2020 OR


EID IN( 'E02','E01');
................................. ...........................

16. Get the names of employee whose joining year is after 2017 and eid is E02 or
E01(use IN operator).

Query : SELECT ENAME FROM EMPDETAILS WHERE YOJ>2017 AND


EID IN( 'E02','E01');

17. Sort the table in the ascending order of joining year.

Query : SELECT * FROM EMPDETAILS ORDER BY YOJ;

18. Sort the ename and edesgn in the descending order of joining year.

Query : SELECT ENAME,EDESGN FROM EMPDETAILS ORDER BY YOJ


DESC;
................................. ...........................

EXERCISE 7
Aim :Creation of table from another table
1. Create a table PRODUCT with the fields pid,pname,cost and insert 5 row values
into table
Query : CREATE TABLE PRODUCT(PID INT,PNAME
VARCHAR(20),COST DECIMAL(7,2));

INSERT INTO PRODUCT VALUES(101,”IPHONE”,60000.00),


(102,”IWATCH”,5000.00),(103,”APPLE LAPTOP”,95000.00),(104,”ASUS
LAPTOP”,65000.00),(105,”HP LAPTOP”,60000.00);

2. Create a table PdtMaster from Product table and insert some values into new
table

Query: CREATE TABLE PDTMASTER AS SELECT PID AS PDTID,


PNAME AS PDTNAME, COST AS PDTCOST FROM PRODUCT;

3. Describe PdtMaster

Query : DESC PDTMASTER;


................................. ...........................

4. Insert values from PRODUCT

Query: INSERT INTO PdtMaster SELECT Pid,Pname,Cost FROM PRODUCT


LIMIT 2,2;

5. Display values of two tables

Query 1 : SELECT * FROM PRODUCT;


Query 2 : SELECT * FROM PDTMASTER;
................................. ...........................

EXERCISE 8
Aim :Performing Calculations
1. Select all columns of PdtMaster where PdtCost is increased by 10% as
rename the column name with an alias title “Increase in Pdt Cost” and then
do another calculation on the same column say PdtCose*1.10 as “NewCost”

Query : SELECT PDTID,PDTNAME,PDTCOST*0.10 “INCREASE IN


PDT COST”, PDTCOST*1.10 “NEWCOST” FROM PDTMASTER;
................................. ...........................

EXERCISE 9
Aim : Familiarizing SET Operators
1. Create a table called Author with the following fields : AuthorId, AuthorName,
AuthorState,AuthorCountry,AuthorContact

Query : CREATE TABLE AUTHOR(AUTHORID VARCHAR(10),


AUTHORNAME VARCHAR(25), AUTHORSTATE VARCHAR(25),
AUTHORCOUNTRY VARCHAR(25), AUTHORCONTACT
VARCHAR(20));

2. Create another table called Publisher with the following fields : PublisherId,
PublisherName,PublisherState,PublisherCountry,PublisherContact.

Query : CREATE TABLE PUBLISHER(PUBLISHERID VARCHAR(10),


PUBLISHERNAME VARCHAR(25), PUBLISHERSTATE VARCHAR(25),
PUBLISHERCOUNTRY VARCHAR(25), PUBLISHERCONTACT INT(20));

3. Insert 5 rows into each table

Query : INSERT INTO AUTHOR VALUES


('A01','TOM','KERALA','INDIA','1234567'),('A02','JERRY','NEW
YORK','USA','1234567'),('A03','JIM','DELHI','INDIA','34567'),('A04','JIMMY
','DUBAI','UAE','4567323'),('A05','TIMMY','MUNICH','GERMANY','567123'
);

Query : INSERT INTO PUBLISHER(PUBLISHERID, PUBLISHERNAME,


PUBLISHERSTATE, PUBLISHERCOUNTRY, PUBLISHERCONTACT)
VALUES ('P01','PKP PUBLISHER
','KERALA','INDIA','1234567'),('P02','LSME','NEW
YORK','USA','1234567'),('P03','NEWBOOK','DELHI','INDIA','34567'),('P04','
JRST’,'DUBAI','UAE','4567323'),('P05','HUMANRIGHTS','MUNICH','GERM
ANY','567123');
................................. ...........................

4. Get the details of all authors and publisher who are from India.

Query: SELECT AUTHORNAME, AUTHORSTATE, AUTHORCOUNTRY


FROM AUTHOR WHERE AUTHORCOUNTRY ='INDIA' UNION SELECT
PUBLISHERNAME, PUBLISHERSTATE, PUBLISHERCOUNTRY FROM
PUBLISHER WHERE PUBLISHERCOUNTRY='INDIA';
................................. ...........................

EXERCISE 10
Aim : Familiarizing Aggregate functions.
1. CREATE TABLE Publishers with the fields : PubID char (4) NOT NULL
,PubName varchar (40), city varchar (20), PubAmount decimal,country varchar
(30) DEFAULT ‘Canada’,BasicPay Decimal, HRA Decimal,Tax Decimal,TA
Decimal.

Query : CREATE TABLE Publishers(PubID char (4) NOT NULL ,PubName


varchar (40), city varchar (20), PubAmount decimal,country varchar (30)
DEFAULT 'Canada',BasicPay Decimal, HRA Decimal,Tax Decimal,TA
Decimal);

2. Insert Values(min 5 rows)


Query: insert into publishers (pubID, PubName,
city,PubAmount,country,BasicPay, HRA, Tax,TA) VALUES
('p01','Tim','Kochi','12000','india','56788.78','8768.98','65660','56738.47'),
('p02','jim','newyork','22000','usa','26788.98','4768.88','55660','66738.47'),('p03'
,'john','Kochi','32000','india','26788.79','9768.98','15660','26738.67'),('p04','To
m','Kochi','82000','india','96788.78','6768.78','35660','36738.77');

3. Select average of PubAmount under the heading “Average Publication Charge”

Query : select AVG(PubAmount) AS "Average Publication Charge" from


publishers;

4. Select count of publishers under the title “No of Publishers”

Query : select count(*) as " No of Publishers " from publishers;


................................. ...........................

5. Select the count of all publishers whose country is India.

Query : select count(*) as " No of Indian Publishers " from publishers where
country='india';

6. Select highest amount of publisher(hint : MAX)


Query : select MAX(PubAmount)from publishers;

7. Select lowest amount of publisher(hint : MIN)


Query : select MIN(PubAmount)from publishers;

8. Calculate the total amount of publication.(hint : SUM(columnname))


Query : select SUM(PubAmount)from publishers;
................................. ...........................

9. Calculate the total pay of publisher under the column name Salary(hint :
SUM(basic+ta+hra-tax)

Query : select SUM(BasicPay + TA + HRA - TAX) AS salary from publishers;


................................. ...........................

10. Get the publisherId,average of basic,max of basic,min of basic from the table.

Query : select PubID,AVG(BasicPay),MAX(BasicPay),MIN(BasicPay) FROM


publishers;
................................. ...........................

EXERCISE 11
Aim : Familiarizing Numeric Functions
1. ADD:

Query : SELECT 3+2 AS “ADD”;

2. Subtract :

Query : SELECT 5-3 AS “SUBTRACT”;

3. Product :

Query : SELECT 5*3 AS “MULTIPLICATION”;


................................. ...........................

4. Division :
Query : SELECT 10/2 AS “DIVISION”;

5. Division by zero is impossible ,But SQL produces Null result :


Query 1 : SELECT 10/(2-2) AS “NULL DIVISION OUTPUT”;

Query 2 : SELECT 5 DIV 2, -5 DIV 2, 5 DIV -2, -5 DIV -2;

6. ABSOLUTE :
Query 1 : SELECT ABS(2);
................................. ...........................

Query 2 : SELECT ABS(-32);

7. Ceiling (Rounding function)


Query 1 : SELECT CEILING(1.23);

Query 2 : SELECT CEILING(-1.23);

8. Floor(Rounding Function)
Query : SELECT FLOOR(1.23), FLOOR(-1.23);

9. MOD :
Query 1 : SELECT MOD(234, 10);
................................. ...........................

Query 2 : SELECT 253 % 7;

10. Power :
Query : SELECT POW(2,2);

11. Round :
Query : SELECT ROUND(1.298, 1), ROUND(1.58) , ROUND(1.298, 0);

12. SIGN :
Query : SELECT SIGN(-32), SIGN(0), SIGN(234);

13. SQRT :
Query : SELECT SQRT(4);
................................. ...........................

14. Truncate :
Query : SELECT TRUNCATE(1.223,1);
................................. ...........................

EXERCISE 12
Aim : Familiarizing String Functions
1. ASCII :
Query : SELECT ascii('A'), ascii('a’);

2. Character Length/Length of a string :


Query : SELECT CHARACTER_LENGTH('Hello!'),
CHARACTER_LENGTH (“Hi! My name is Praseetha M.S.”);

3. CREATE a TABLE called Faculty_Info with the fields


Faculty_ID INT NOT NULL PRIMARY KEY,
Faculty_First_Name VARCHAR (100),
Faculty_Last_Name VARCHAR (100),
Faculty_Dept_Id INT NOT NULL,
Faculty_Address Varchar(120),
Faculty_City Varchar (80),
Faculty_Salary INT

Query : CREATE TABLE Faculty_Info(Faculty_ID INT NOT NULL


PRIMARY KEY,Faculty_First_Name VARCHAR (100), Faculty_Last_Name
VARCHAR (100), Faculty_Dept_Id INT NOT NULL, Faculty_Address
Varchar(120), Faculty_City Varchar (80), Faculty_Salary INT);
................................. ...........................

4. Insert values (5 rows)


Query : Insert into Faculty_Info(Faculty_ID,Faculty_First_Name,
Faculty_Last_Name,
Faculty_Dept_Id,Faculty_address,Faculty_City,Faculty_Salary) VALUES
(101,'Tom','Abcd','201','India
hgvdhn','Kochi','12000'),(102,'jim','efgh','202','Kochi
asdfs','Kochi','22000'),(103,'Tommy','hdgfhh','203','USA
Brooklyn','NY','32000'),(104,'Jerry','zsasds','204','LONDON
dfgdfg','England','62000'),(105,'Arun','bndkj',205,'India hgvdhn','DL','72000');

5. Display the values


Query : select * from Faculty_Info;

6. ASCII code of a column –


Query : SELECT ASCII(Faculty_First_Name) as ASCII_FName,
Faculty_Dept_Id FROM Faculty_Info ;
................................. ...........................

7. Character Length/Length of a string


8.
Query : SELECT CHAR_LENGTH(Faculty_Address) as Lenth_Address
FROM Faculty_Info ;

9. Concat :

Query 1 : SELECT CONCAT(Faculty_First_Name, Faculty_Last_Name ) as


FullName FROM Faculty_Info;

Query 2 : Concat : SELECT CONCAT('SCMS', ' is', ' an', ' institution ', ' who
runs as a team.');

Query 3: SELECT Faculty_First_Name, Faculty_Last_Name,


CONCAT(Faculty_First_Name, Faculty_Last_Name) AS Full_Name FROM
Faculty_Info;
................................. ...........................

10. Convert into Small and Capital Letters Letters :


Query : SELECT LOWER(Faculty_Address) AS Address,
UPPER(Faculty_Last_Name) AS Initial FROM Faculty_Info;

11. Extract from Left :


Query : SELECT LEFT(Faculty_Address, 5) FROM Faculty_Info;
................................. ...........................

12. Extract from Right :


Query : SELECT RIGHT(Faculty_Address, 5) FROM Faculty_Info;
................................. ...........................

EXERCISE 13
AIM : Familiarizing Inner join,Left Outer Join,Right Outer Join
1. Create different tables say
SchemeMaster(Sid,Descrptn)
PdtMaster(PdtId,PdtName,CatId, Sid)
EmpMaster(EmpId,EmpName,Desgn)
ProdtMaster(Pid,Pname,Cost)
TransMaster(Tid,EmpId,Pid)

Query : Create table SchemeMaster (Sid int(15) primary key,Descrptn


varchar(30));

Create table PdtMaster(PdtId int(15) primary key,PdtName varchar(30),CatId


varchar(15), sid int(15), foreign key PdtMaster(sid) references
SchemeMaster(Sid));

Create table EmpMaster(EmpId int(15) primary key,EmpName varchar(30)


,Desgn varchar(30));

Create table ProdtMaster(Pid int(15) primary key,Pname varchar(30),Cost


int(20));

Create table TransMaster(Tid int(15) primary key,EmpId int(15),Pid


int(15),foreign key TransMaster(Pid) references ProdtMaster(Pid));
................................. ...........................

2. Insert 5 rows on each table.


Query : insert into SchemeMaster(Sid,Descrptn) values
(101,'Scheme1'),(102,'Scheme2'),(103,'Scheme3'),(104,'Scheme4'),(105,'Schem
e5');

insert into PdtMaster(Pdtid,PdtName,CatID,Sid) values


(201,'Pdt1','Ct1',101),(202,'Pdt2','Ct2',102),(203,'Pdt3','Ct3',103),(204,'Pdt4','Ct
4',104),(205,'Pdt5','Ct5',105);

insert into EmpMaster(Empid,EmpName,Desgn) values


(301,'Emp1','Tester'),(302,'Emp2','Manager'),(303,'Emp3','CEO'),(304,'Emp4','
Sales'),(305,'Emp5','Account');

insert into ProdtMaster(Pid,Pname,Cost) values


(401,'P1',10000),(402,'P2',15000),(403,'P3',20000),(404,'P4',5000),(405,'P5',30
000);

insert into TransMaster(Tid,Empid,Pid) values


(501,301,401),(502,302,402),(503,303,403),(504,304,404),(505,305,405);
................................. ...........................

3. Perform the following


a) Inner Join
Query : SELECT A.PdtId,A.PdtName,B.Descrptn FROM PdtMaster A
INNER JOIN SchemeMaster B ON A.Sid = B.Sid WHERE CatId='ct2';

b) LeftOuter Join
Query : SELECT A.EmpId,A.EmpName , B.Tid FROM EmpMaster A
LEFT JOIN TransMaster B ON A.EmpId=B.EmpId;

c) Right Outer Join


Query : SELECT A.Pid,A.Pname,A.Cost,B.Tid,B.Pid FROM ProdtMaster
A RIGHT JOIN TransMaster B ON A.Pid=B.Pid;
................................. ...........................

EXERCISE 14
AIM : Familiarizing View Concept
1. Create a view( A temporary Table) names Products which will refer
columns from PdtMaster(Previously created table on Exercise 13)

Query : CREATE VIEW Products AS SELECT Pid “ProdNo”, Pname


“ProdName”,Cost “ProdCast” FROM ProdtMaster;

2. Display the values in Products


Query : select * from Products;

3. Destroy the view


Query : DROP VIEW Products;
................................. ...........................

EXERCISE 15
Aim : Familiarizing Groupby and Having Clause

1. Create a table named CHILD(cid,relationship,childname,parentname)

Query : create table child(cid varchar(15), relationship varchar(25), childname


varchar(25), parentname varchar(25));

2. Insert 5 rows

Query : insert into child(cid,relationship,childname,parentname) values


('c01','son','Tim','Manu'), ('c01','daughter','Jincy','Manu'),
('c02','son','John','Sonu'), ('c02','daughter','Amal','Sonu'),
('c03','son','Vedar','Anu');

3. Display the values

Query : select * from child;

4. Display the total no of children, and their parent’s names from the table and
group it by Cid.

Query : select count(cid) as 'Total No of Children',parentname from child


group by cid;
................................. ...........................

5. Display cid,parentname and total no of children from the table by grouping it


by Cid having the count of cid is greater than 1.

Query : select cid,parentname, count(cid) as 'total no of children' from child


group by cid having count(cid )> 1;
................................. ...........................

EXERCISE 16
Aim : Familiarizing Date conversion functions
Usage of date_format function

1. Convert a datetime value into week,month and year


Query : SELECT DATE_FORMAT("2017-06-15 22:23:00", "%W %m %y");

2. Convert a datetime into hours minutes and seconds


Query: SELECT date_format("2017-06-15 22:23:00", "%H %i %S");

3. Convert a datetime into day month year weekday time day of the year
Query : SELECT date_format("2017-06-15 22:23:00","%D %M %y,%a %r::
%j");
................................. ...........................

Format Description
%a Abbreviated weekday name (Sun to Sat)
%b Abbreviated month name (Jan to Dec)
%c Numeric month name (0 to 12)
%D Day of the month as a numeric value, followed by suffix (1st, 2nd, 3rd...)
%d Day of the month as a numeric value (01 to 31)
%e Day of the month as a numeric value (0 to 31)
%f Microseconds (000000 to 999999)
%H Hour (00 to 23)
%h Hour (00 to 12)
%I Hour (00 to 12)
%i Minutes (00 to 59)
%j Day of the year (001 to 366)
%k Hour (0 to 23)
%l Hour (1 to 12)
%M Month name in full (January to December)
%m Month name as a numeric value (00 to 12)
%p AM or PM
%r Time in 12 hour AM or PM format (hh:mm:ss AM/PM)
%S Seconds (00 to 59)
%s Seconds (00 to 59)
%T Time in 24 hour format (hh:mm:ss)
%U Week where Sunday is the first day of the week (00 to 53)
%u Week where Monday is the first day of the week (00 to 53)
%V Week where Sunday is the first day of the week (01 to 53). Used with
%X
%v Week where Monday is the first day of the week (01 to 53). Used with
%x
%W Weekday name in full (Sunday to Saturday)
%w Day of the week where Sunday=0 and Saturday=6
%X Year for the week where Sunday is the first day of the week. Used with
%V
%x Year for the week where Monday is the first day of the week. Used with
%v
%Y Year as a numeric, 4-digit value
%y Year as a numeric, 2-digit value
................................. ...........................

EXERCISE 17
Aim : Familiarizing SubQuery
1. Create a table called “Cand” ( cid pk,cname,csal,cexprnc integer)

Query : create table cand(cid varchar(10) primary key, cname varchar(25), csal
varchar(25), cexprnc int(20));

2. Insert 5 rows

Query : insert into cand(cid,cname,csal,cexprnc) values ('C01', 'Amal','10000',2),


('C02', 'Varun','15000',1), ('C03', 'Tim','25000',5), ('C04', 'Jimmy','36000',5),
('C05', 'Sreejith','40000',4);

3. Create table called Candidate(id,year,qlfn, where id foreign key of cid)

Query : create table candidate(id varchar(10) , qlfn varchar(25),year int ,


foreign key candidate(id) references cand(cid));

4. Insert values 5 rows

Query : insert into candidate(id,qlfn,year) values ('C01','Degree',2001),


('C02','10th',2002), ('C01','PG',2011), ('C03','PHD',2015), ('C03','Degree',2012),
('C04','Pre-Degree',2008);
................................. ...........................

SINGLE ROW RETURN

5. Select the data from cand where cand.cid = id from candidate if the year =2001
Query : SELECT * FROM CAND WHERE CAND.CID=(SELECT ID FROM
CANDIDATE WHERE YEAR=2001);

RETURN MULTIPLE ROW

SELECT * FROM CANDIDATE,CAND WHERE


CAND.CID=CANDIDATE.ID AND CANDIDATE.ID IN(SELECT ID
FROM CANDIDATE WHERE CSAL>'20000');
................................. ...........................

EXERCISE 18
Familiarizing TCL Commands
6. Select all the details from cand table.
Query : select * from cand;

7. Save the commands


Query : commit;

8. Select the details of cand where cand experience is more than 3 years.
Query: select * from cand where cexprnc > 3;

9. Undo the command.


Query : rollback;
................................. ...........................

MONGODB
................................. ...........................

1. Create a database yournameDB in MongoDB.

QUERY:

use yournameDB

OUTPUT:

2. Create another database called “urnameMCADB” in MongoDB

QUERY:

USE urnameMCADB

OUTPUT:

3. Drop yournameDB database.

QUERY:

db.dropDatabase()

OUTPUT:
................................. ...........................

4. Create a collection called Friends and Family

QUERY:

db.createCollection(“Friends”)
db.createCollection(“Family")

OUTPUT:

5. Check the available collections into your database urnameMCADB

QUERY:

show collections

OUTPUT

6. Drop the collection with the name Friends.

QUERY:

db.Friends.drop()

OUTPUT:
................................. ...........................

7. Insert the following documents into Family.

QUERY:

db.Family.insertMany([{Relationship:"Father",Address:"Housename",by:"Fathername",Siblings:
["Father'sistername","Father's Brothersname"]},{Relationship:"Mother",Address:"Mothers
house name",by:"Mother's Name",Siblings:["Mother's sistername","Mother's
brothername"],comments: [{status:"married",date:new Date(2023,11,10,2,25),refered_by:"4
Friends"}]}])

OUTPUT:
................................. ...........................

8. Insert the following documents into empdetails

QUERY:

db.EmpDetails.insertMany([{First_Name: "radhika",Last_Name: "sharma",Age:


"26",TeamMembers:['aaaa','bbbb','ccc'],e_mail: "[email protected]",phone:
"9000012345"},{First_Name: "Rachel",Last_Name: "Christopher",Age: "27",TeamMembers:
['dddd','eeee','fff'],e_mail: "[email protected]",phone: "9000054321"},
{First_Name: "Fathima",Last_Name: "Sheik",Age: "24",TeamMembers:['gggg','hhh','iii'],e_mail:
"[email protected]",phone: “9000054321"}])

OUTPUT:
................................. ...........................

9. Insert a document into the collection “dummycol

QUERY:

db.dummycol.insertMany([{title: "MongoDB Overview",description: "MongoDB is no SQL


database",by: "Karl",tags: ["mongodb","database","NoSQL"],likes: 100},{title: "NoSQL
Database",description: "NoSQL database dosen't have tables",by: "Karl",likes: 20,comments:
[{user: "user1",message: "My first comment",dateCreated: new Date(2013,11,10,2,35),like: 0}]}])

OUTPUT:
................................. ...........................

10. To display the documents from family in a formatted way by using pretty () method

QUERY:

db.Family.find().pretty()

OUTPUT:
................................. ...........................

11. Display only one document from Family

QUERY:

db.Family.findOne()

OUTPUT:

12. To show all the tutorials written by ‘ Karl’ and whose title is 'MongoDB Overview'.

QUERY:

db.dummycol.find({$and: [{"by":"Karl"},{"title": "MongoDB Overview”}]}).pretty()

OUTPUT:
................................. ...........................

13. To show all the tutorials written by 'Karl' or whose title is 'MongoDB Overview'.

QUERY:

db.dummycol.find({$or: [{"by":"Karl"},{"title": "MongoDB Overview”}]}).pretty()

OUTPUT:

14. Display the documents that have likes greater than 10 and whose
title is either'MongoDB Overview' or by is 'Karl’.

QUERY:

db.dummycol.find({"likes":{$gt:10},$or:[{"title":"MongoDB Overview”},{"by":"Karl"}]}).pretty()
................................. ...........................

OUTPUT:

15. Retrieve the document(s) from empdetails whose first name is not "Radhika" and
last name isnot "Christopher".

QUERY:

db.EmpDetails.find({$and:[{“First_Name":{$ne:"radhika"}},{"Last_Name":
{$ne:"Christopher"}}]}).pretty()

OUTPUT:
................................. ...........................

16. Retrieve the document(s) from empdetails whose age is not greater than 25

QUERY:

db.EmpDetails.find({“age":{$not:{$gt:"25"}}}).pretty()

OUTPUT:
................................. ...........................

17. Retrieve the document(s) from empdetails whose age is in the list {24,25,26}

QUERY:

db.EmpDetails.find({“Age":{$in:["24","25","26"]}}).pretty()

OUTPUT:

18. Set the new title 'New MongoDB Tutorial' of the documents whose title is
'MongoDBOverview'.

QUERY:

db.dummycol.update({"title":"MongoDB Overview"},{$set:{"title":"NewMongodb Tutorial”}},


{multi:true})

OUTPUT:
................................. ...........................

19. Updates the age and email values of the document with name 'Radhika'.

QUERY:

db.EmpDetails.update({“First_Name”:"Radhika"},{$set
{“age":"29","e_mail":"[email protected]"}},{multi:true})

OUTPUT:

20. Updates the age as 100, whose age is not greater than 25.

QUERY:

db.EmpDetails.update({“age":{$lt:"25"}},{$set:{"age":"100"}})

OUTPUT:

21. Remove all the documents whose title is 'MongoDB Overview'.

QUERY:

db.EmpDetails.remove({"title":"MongoDB Overview”})

OUTPUT:
................................. ...........................

22. Retrieve student id from all the documents.

QUERY:

db.Student.insert([{"student_name":"Tim","student_id":"1001","student_age":"23"},
{"student_name":"Tom","student_id":"1002","student_age":"24"},
{"student_name":"Jerry","student_id":"1003",

“student_age”:"25"}])db.Student.find({},{_id:0,"student_id":1})

OUTPUT:
................................. ...........................

23. List of all the students, having the id > 1002.

QUERY:

db.Student.find({"student_id":{$gt:"1002"}}).pretty()

OUTPUT:

24. List only one students, having the id > 1002.

QUERY:

db.Student.find({"student_id":{$gt:"1002"}}).limit(1).pretty()

OUTPUT:
................................. ...........................

25.List the second record of the students, having the id > 1002.

QUERY:

db.Student.find({ "student_id": { $gt: "1001" } }).limit(1).pretty();

OUTPUT:
................................. ...........................

26. To display the students_id of all documents in descending order

QUERY:

db.Student.find().sort({“student_id":-1}).pretty()

OUTPUT:
................................. ...........................

27. To display the student_id field of all the students in ascending order.

QUERY:

db.Student.find({},{_id:0,"student_id":1}).sort({"student_id":1})

OUTPUT:

28. Sort the documents based on student_id and display the


student_ageand student_name fields.

QUERY:

db.Student.find({},{_id:0,”student_name":1,"student_age":1}).sort({"student_id":1})

OUTPUT:

29. To create the index on student_name field in ascending order.

QUERY:

db.Student.createIndex({“student_name":1})

OUTPUT:
................................. ...........................

30. To find the indexes of studentdata collection.

QUERY:

db.Student.getIndexes()

OUTPUT:

31. Drop the index that we have created on student_name


field in thecollection studentdata.

QUERY:

db.Student.dropIndex({“student_name":1})

OUTPUT:

32. To create backup of database and to restore backup data.

QUERY:

mongodump
mongorestore
................................. ...........................

OUTPUT:

You might also like