0% found this document useful (0 votes)
46 views22 pages

SQL Lab Assign

The document provides instructions on how to use SQL to interact with relational databases. It discusses SQL commands like CREATE, SELECT, INSERT, UPDATE, DELETE, and DROP for defining, manipulating, and querying database tables. It also covers SQL syntax for selecting, filtering, ordering, grouping data and creating tables with data types, primary keys, and constraints. Examples are given for creating tables, inserting data, and viewing table schemas.

Uploaded by

naveen suman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
46 views22 pages

SQL Lab Assign

The document provides instructions on how to use SQL to interact with relational databases. It discusses SQL commands like CREATE, SELECT, INSERT, UPDATE, DELETE, and DROP for defining, manipulating, and querying database tables. It also covers SQL syntax for selecting, filtering, ordering, grouping data and creating tables with data types, primary keys, and constraints. Examples are given for creating tables, inserting data, and viewing table schemas.

Uploaded by

naveen suman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

LAB MANUAL FOR DBMS LAB

1. Understand basics of SQL programming:


What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data
stored in relational database. SQL is the standard language for Relation Database System.

Why SQL?
Allows users to access data in relational database management systems.

Allows users to describe the data.

Allows users to define the data in database and manipulate that data.

Allows to embed within other languages using SQL modules, libraries & pre-compilers.

Allows users to create and drop databases and tables.

SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE,
DELETE and DROP. These commands can be classified into groups based on their nature:
DDL -Data Definition Language:
Command Description
CREATE Creates a new table, a view of a
table, or other object in database

ALTER Modifies an existing database object,


such as a table.

DROP Deletes an entire table, a view of a


table or other object in the database

DML -Data Manipulation Language:


Command Description

INSERT Creates a record


UPDATE Modifies records
DELETE Deletes records

DCL -Data Control Language:


Command Description
GRANT Gives a privilege to
user

REVOKE Takes back privileges


granted from user

DQL -Data Query Language:


Command Description
SELECT Retrieves certain records
from one or more tables
2. SQL Syntax:
SQL is followed by unique set of rules and guidelines called Syntax.
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE,
DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a
semicolon (;).
SQL is case insensitive, which means SELECT and select have same meaning in SQL
statements, but MySQL makes difference in table names.
SQL SELECT Statement:
SELECT column1, column2....columnN
FROM table_name;

SQL DISTINCT Clause:


SELECT DISTINCT column1, column2....columnN
FROM table_name;

SQL WHERE Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;

SQL AND/OR Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;

SQL IN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);

SQL BETWEEN Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;

SQL LIKE Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SQL ORDER BY Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};

SQL GROUP BY Clause:


SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;

SQL CREATE TABLE Statement:


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

SQL DROP TABLE Statement:


DROP TABLE table_name;

SQL ALTER TABLE Statement:

ALTER TABLE table_name {ADD|DROP|MODIFY} column_name


{data_ype};

SQL ALTER TABLE Statement (Rename):


ALTER TABLE table_name RENAME TO new_table_name;

SQL INSERT INTO Statement:


INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);

SQL UPDATE Statement:


UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
SQL DELETE Statement:
DELETE FROM table_name
WHERE {CONDITION};

SQL CREATE DATABASE Statement:


CREATE DATABASE database_name;
SQL DROP DATABASE Statement:

SQL DROP DATABASE Statement:


DROP DATABASE database_name;
ASSIGNMENT 2
SQL Data Types:
SQL data type is an attribute that specifies type of data of any object. Each column, variable
and expression has related data type in SQL.
We would use these data types while creating your tables. You would choose a particular
data type for a table column based on your requirement.
SQL Server offers six categories of data types for your use:
1. Exact Numeric Data Types
2. Approximate Numeric Data Types
3. Date and Time Data Types
4. Character Strings Data Types
5. Unicode Character Strings Data Types
6. Binary Data Types
7. Misc Data Types

SQL Operators:
An operator is a reserved word or a character used primarily in an SQL
statement's WHERE clause to perform operation(s), such as comparisons
and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as
conjunctions for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions

SQL CREATE Database:


SQL CREATE DATABASE statement is used to create new SQL database:
Syntax:
CREATE DATABASE DatabaseName;

Always database name should be unique within the RDBMS


Example:
If you want to create new database <testDB>, then CREATE DATABASE
statement would be as follows:
SQL> CREATE DATABASE testDB;
Once a database is created, you can check it in the list of databases as
follows:
SQL> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+--------------------+
7 rows in set (0.00 sec)

DROP or DELETE Database:


SQL DROP DATABASE statement is used to drop an existing database in
SQL schema.
Syntax:
Basic syntax of DROP DATABASE statement is as follows:
DROP DATABASE DatabaseName;
Example:
To delete an existing database <testDB>, then DROP DATABASE statement
would be as follows:
SQL> DROP DATABASE testDB;

SQL SELECT Database:


When you have multiple databases in your SQL Schema, then before starting
your operation, you would need to select a database where all the operations
would be performed.
The SQL USE statement is used to select any existing database in SQL
schema:
Syntax:
Basic syntax of USE statement is as follows:
USE DatabaseName;
Now, if you want to work with AMR database, then you can execute the
following SQL command and start working with AMR database:
SQL> USE AMR;
SQL CREATE Table:
Creating a basic table involves naming the table and defining its columns and each
column's data type.
The SQL CREATE TABLE statement is used to create a new table.
Syntax:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows
the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data
type it is.

Create Table Using another Table:


A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
The new table has the same column definitions. All columns or specific columns can be
selected.
When you create a new table using existing table, new table would be populated using
existing values in the old table.

Syntax:
The basic syntax for creating a table from another table is as follows:

CREATE TABLE NEW_TABLE_NAME AS


SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]

Here, column1, column2...are the fields of existing table and same would be used to create
fields of new table.

Example:
Following is an example, which would create a table SALARY using CUSTOMERS table
and having fields customer ID and customer SALARY:
SQL> CREATE TABLE SALARY AS
SELECT ID, SALARY
FROM CUSTOMERS;

This would create new table SALARY


Example:
Following is an example, which creates a CUSTOMERS table with ID as
primary key and NOT NULL are the constraints showing that these fileds can
not be NULL while creating records in this table:

SQL> CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

We can verify if table has been created successfully by looking at the


message displayed by the SQL server, otherwise we can use DESC
command as follows:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+

5 rows in set (0.00 sec)

Now, we have CUSTOMERS table available in your database which we can


use to store required information related to customers.

ASSIGNMENT 3

SQL INSERT Query


Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which you want to insert data.
We may not need to specify the column(s) name in the SQL query if we are adding values for all the columns of the table.
But make sure the order of the values is in the same order as the columns in the table. The SQL INSERT INTO syntax
would be as follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example:
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );

All the above statements would produce the following records in CUSTOMERS table:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

SQL SELECT Query


S QL SELECT Statement is used to fetch the data from a database table which returns data in the form of result table.

These result tables are called result-sets.

Syntax:
The basic syntax of SELECT statement is as follows:
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available
in the field, then you can use the following syntax:
SELECT * FROM table_name;

Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;

This would produce the following result:


+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

If you want to fetch all the fields of CUSTOMERS table, then use the following query:
SQL> SELECT * FROM CUSTOMERS;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Some simple SQL QUERIES

DDL QUERIES:
Q1. Write a query to create a table employee with empno, ename, designation, andsalary.
SQL>CREATE TABLE EMP (EMPNO NUMBER (4),
ENAME VARCHAR2 (10),
DESIGNATIN VARCHAR2 (10),
SALARY NUMBER (8,2));
Table created.
Q2. Write a query for create a from an existing table with all the fields.
SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
Table created.
SQL> DESC EMP1
Name Null? Type
----------------------------------------- -------- ------------------
EMPNO NUMBER (4)
ENAME VARCHAR2 (10)
DESIGNATIN VARCHAR2 (10)
SALARY NUMBER (8,2)
Q3. Write a Query to Alter the column EMPNO NUMBER(4) TO EMPNO NUMBER(6).
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6);
Table altered.
Q4. Write a query to add a new column in to employee.
SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);
Table altered.
Q5. Write a query to drop a column from an existing table employee.
SQL> ALTER TABLE EMP DROP COLUMN DOJ;
Table altered.
Q6. Write a query to drop an existing table employee.
SQL> DROP table employee;
Table deleted.
DML QUERIES:
Q1. Write a query to insert the records in to employee.
SQL>INSERT INTO EMP VALUES(103,'Saurabh','ASST_PROF',25000);
1 row created.
Q2. Write a query to display the records from employee.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
103 SAURABH ASST_PROF 25000
Q3. Write a query to insert the records in to employee using substitution
method.
SQL> INSERT INTO EMP
VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY');
Enter value for empno: 102
Enter value for ename: DHAJVEER
Enter value for designatin: ASST_PROF
Enter value for salary: 35000
old 1: INSERT INTO EMP
VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')
new 1: INSERT INTO EMP
VALUES(102,'DHAJVEER','ASST_PROF','35000')
1 row created.
SQL> /
Enter value for empno: 101
Enter value for ename: ABHILASHA
Enter value for designatin: ASST_PROF
Enter value for salary: 40000
old 1: INSERT INTO EMP
VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')
new 1: INSERT INTO EMP
VALUES(101,'ABHILASHA','ASST_PROF','40000')
1 row created.
Q4. Write a query to update the records from employee.
SQL> UPDATE EMP SET SALARY=45000 WHERE EMPNO=101;
1 row updated.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 ABHILASHA ASST_PROF 45000
102 DHAJVEER ASST_PROF 35000
103 SAURABH ASST_PROF 30000

Outcome:
Assignment 6
To understand the basic commands of DML and DDL and their use in database.

AIM: Write SQL queries using logical operations and operators.


Theory:
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations. These Operators are used to specify
conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Operators used to negate conditions

Pre-Requisite Data:
CUSTO NAME AGE ADDRE SALAR
MER SS Y
TABLE
ID
1 Akshay 25 Delhi 30000
2 Manish 27 Mumbai 35000
3 Kushagr 26 Kolkata 30000
a
4 Mukesh 31 Hyderab 32000
ad
5 Himans 29 Chennai 40000
hu
6 Neeraj 30 Noida 36000
7 Nishant 32 Delhi 30000

Q2. Write a query to find the salary of a person where age is <= 26 or salary > =33000 from customer
table.
SQL>SELECT * FROM CUSTOMERS WHERE AGE <= 26 or SALARY > =33000;

Output: NAME AGE ADDRE SALAR


ID SS Y
1 Akshay 25 Delhi 30000
2 Manish 27 Mumbai 35000
3 Kushagr 26 Kolkata 30000
a
5 Himans 29 Chennai 40000
hu
6 Neeraj 30 Noida 36000

5 rows selected.
Q3.Write a query to find the name of customer whose name is like “Ku%”.
SQL>SELECT * FROM CUSTOMERS WHERE NAME LIKE 'Ku%';
Output: NAME AGE ADDRE SALAR
ID SS Y
3 Kushagr 26 Kolkata 30000
a
1 row selected.

Q4. Write a query to find the customer details using “IN” and “Between” operator where age can
be 25 or 27.
SQL>SELECT * FROM CUSTOMERS WHERE AGE IN ( 25, 27 );
SQL>SELECT * FROM CUSTOMERS WHERE AGE BETWEEN 25 AND 27;
Output:
ID NAME AGE ADDRE SALAR
SS Y
1 Akshay 25 Delhi 30000
3 Kushagra 26 Kolkata 30000

2 rows selected.

CASE STUDY:
1. CREATION OF BANK DATABASE SYSTEM using mysql
The bank database schema has a combination of multiple tables,
where we will creating database
schema tables which is more helpful to design a bank database.
Bank database is a collection of multiple tables like customer,
branch, account, trandetails, loan.
Now we will be writing tables to create bank database schema:
First, create the database "bank"
mysql> CREATE DATABASE bank;
Then use the database bank to creating tables inside it.
mysql> USE bank;

Creating table customer


CREATE TABLE customer
(
custid VARCHAR(6),
fname VARCHAR(30),
mname VARCHAR(30),
ltname VARCHAR(30),
city VARCHAR(15),
mobileno VARCHAR(10),
occupation VARCHAR(10),
dob DATE,
CONSTRAINT customer_custid_pk PRIMARY KEY(custid)
);

Creating table account


CREATE TABLE account
(
acnumber VARCHAR(6),
custid VARCHAR(6),
bid VARCHAR(6),
opening_balance INT(7),
aod DATE);

Creating table trandetails

CREATE TABLE trandetails ( tnumber VARCHAR(6), acnumber VARCHAR(6),


dot DATE, medium_of_transaction VARCHAR(20), transaction_type
VARCHAR(20), transaction_amount INT(7), CONSTRAINT
trandetails_tnumber_pk PRIMARY KEY(tnumber), CONSTRAINT
trandetails_acnumber_fk FOREIGN KEY(acnumber) REFERENCES
account(acnumber) );

Creating table loan

CREATE TABLE loan ( custid VARCHAR(6), bid VARCHAR(6), loan_amount


INT(7), CONSTRAINT loan_customer_custid_bid_pk PRIMARY
KEY(custid,bid), CONSTRAINT loan_custid_fk FOREIGN KEY(custid)
REFERENCES customer(custid), CONSTRAINT loan_bid_fk FOREIGN KEY(bid)
REFERENCES branch(bid));

All the tables are created now we will be inserting database records into these tables:
Insert records into the customer table:

Record :
INSERT INTO customer VALUES('C00001','Ramesh','Chandra','Sharma','Delhi','9543198345','Service','1976-12-06');
INSERT INTO customer VALUES('C00002','Avinash','Sunder','Minha','Delhi','9876532109','Service','1974-
10-16');
INSERT INTO customer
VALUES('C00003','Rahul',null,'Rastogi','Delhi','9765178901','Student
','1981-09-26');INSERT INTO customer
VALUES('C00004','Parul',null,'Gandhi','Delhi','9876532109','Housewif
e','1976-11-03');INSERT INTO customer
VALUES('C00005','Naveen','Chandra','Aedekar','Mumbai','8976523190','
Service','1976-09-19');INSERT INTO customer
VALUES('C00006','Chitresh',null,'Barwe','Mumbai','7651298321','Stude
nt','1992-11-06');INSERT INTO customer
VALUES('C00007','Amit','Kumar','Borkar','Mumbai','9875189761','Stude
nt','1981-09-06');INSERT INTO customer
VALUES('C00008','Nisha',null,'Damle','Mumbai','7954198761','Service'
,'1975-12-03');INSERT INTO customer
VALUES('C00009','Abhishek',null,'Dutta','Kolkata','9856198761','Serv
ice','1973-05-22');INSERT INTO customer
VALUES('C00010','Shankar',null,'Nair','Chennai','8765489076','Servic
e','1976-07-12');

Now inserting records into the branch table:


INSERT INTO branch VALUES('B00001','Asaf ali road','Delhi');
INSERT INTO branch VALUES('B00002','New delhi main branch','Delhi');
INSERT INTO branch VALUES('B00003','Delhi cantt','Delhi');

Now inserting records into the account table:


INSERT INTO account VALUES('A00001','C00001','B00001',1000,'2012-12-
15','Saving','Active');INSERT INTO account
VALUES('A00002','C00002','B00001',1000,'2012-06-
12','Saving','Active');INSERT INTO account
VALUES('A00003','C00003','B00002',1000,'2012-05-
17','Saving','Active');INSERT INTO account
VALUES('A00004','C00002','B00005',1000,'2013-01-
27','Saving','Active');INSERT INTO account
VALUES('A00005','C00006','B00006',1000,'2012-12-
17','Saving','Active');INSERT INTO account
VALUES('A00006','C00007','B00007',1000,'2010-08-
12','Saving','Suspended');INSERT INTO account
VALUES('A00007','C00007','B00001',1000,'2012-10-
02','Saving','Active');INSERT INTO account
VALUES('A00008','C00001','B00003',1000,'2009-11-
09','Saving','Terminated');INSERT INTO account
VALUES('A00009','C00003','B00007',1000,'2008-11-
30','Saving','Terminated');INSERT INTO account
VALUES('A00010','C00004','B00002',1000,'2013-03-
01','Saving','Active');

Now inserting records into the trandetails table:


INSERT INTO trandetails VALUES('T00001','A00001','2013-01-
01','Cheque','Deposit',2000);INSERT INTO trandetails
VALUES('T00002','A00001','2013-02-
01','Cash','Withdrawal',1000);INSERT INTO trandetails
VALUES('T00003','A00002','2013-01-01','Cash','Deposit',2000);INSERT
INTO trandetails VALUES('T00004','A00002','2013-02-
01','Cash','Deposit',3000);INSERT INTO trandetails
VALUES('T00005','A00007','2013-01-11','Cash','Deposit',7000);INSERT
INTO trandetails VALUES('T00006','A00007','2013-01-
13','Cash','Deposit',9000);INSERT INTO trandetails
VALUES('T00007','A00001','2013-03-13','Cash','Deposit',4000);INSERT
INTO trandetails VALUES('T00008','A00001','2013-03-
14','Cheque','Deposit',3000);INSERT INTO trandetails
VALUES('T00009','A00001','2013-03-
21','Cash','Withdrawal',9000);INSERT INTO trandetails
VALUES('T00010','A00001','2013-03-
22','Cash','Withdrawal',2000);INSERT INTO trandetails
VALUES('T00011','A00002','2013-03-
25','Cash','Withdrawal',7000);INSERT INTO trandetails
VALUES('T00012','A00007','2013-03-26','Cash','Withdrawal',2000);

Now inserting records into the trandetails table:


INSERT INTO loan VALUES('C00001','B00001',100000);INSERT INTO loan
VALUES('C00002','B00002',200000);INSERT INTO loan
VALUES('C00009','B00008',400000);INSERT INTO loan
VALUES('C00010','B00009',500000);INSERT INTO loan
VALUES('C00001','B00003',600000);INSERT INTO loan
VALUES('C00002','B00001',600000);

Performs querying on this:


All tables with records are created, now we will performqueries on
these tables:
Problem#1:Write a query to display the customer number, firstname,
customer’s date of birth. Display in sorted order of date of birth
year and within that sort by firstname.

Solution: SELECT custid, fname, mname,dob FROM customer ORDER BY


EXTRACT(year FROM dob), fname ASC;
Problem#2: Write a query to display the customer’s number, first
name, and middle name. The customer’s who don’t have a middle name,
for them display the last name. Give the alias name as Cust_Name.

Solution: SELECT custid, fname, IF(mname IS NOT NULL, mname, ltname)


AS Cust_Name FROM customer;

Problem # 3: Write a query to display the number of customer’s from


Delhi. Give the count an alias name of Cust_Count.

Solution: SELECT (SELECT COUNT(city) FROM customer;

Problem # 4: Write a query to display the customer number, customer


firstname,account number for the customer’s whose accounts were
created after 15th of any month.
Solution:SELECT account.custid, customer.fname, account.acnumberFROM
account, customerWHERE account.custid = customer.custidAND day(aod)
> 15;

Problem # 6:Write a query to display the female customers firstname,


city and account number who are not into business, service or
studies.
Solution:SELECT DISTINCT customer.fname, customer.city,
account.acnumberFROM account, customerWHERE account.custid =
customer.custidAND NOT(occupation=”business” or occupation=”service”
or occupation=”student”);
Problem # 7:Write a query to display city name and count of branches
in that city. Give the count of branches an alias name of
Count_Branch.
Solution:SELECT bcity, count(*)AS Count_Branch FROM branchGroup By
bcity;

Problem # 8:Write a query to display account id, customer’s


firstname, customer’s lastname for the customer’s whose account is
Active.
Solution:SELECT account.acnumber, customer.fname, customer.ltname
FROM account, customer WHERE account.custid = customer.custid AND
astatus = “Active”;

Problem # 9:Write a query to display the customer’s number,


customer’s firstname, branch id and loan amount for people who have
taken loans.
Solution:SELECT customer.custid, customer.fname, branch.bid,
loan.loan_amountFROM ((loanINNER JOIN customer ON
loan.custid=customer.custid)INNER JOIN branch ON
loan.bid=branch.bid);

Lab Activity 1: Create a table STUDENT with under mentioned


structure by using SQL
Statement:
StdID Number Primary Key
StdName Character (30) NOT NULL
Sex Character(6) Male or Female
Percentage Number
SClass Number
Sec Character
Stream Character(10) Science or Commerce
DOB Date Date of Birth
Step 1: Open MySQL, Open Database and create table as:
CREATE TABLE Student (
StdID INT(4) PRIMARY KEY, StdName VARCHAR(30) NOT NULL,
Sex VARCHAR(1), Percentage DECIMAL(5,2), SClass INT ,
Sec VARCHAR(1), Stream VARCHAR(10), DOB DATE );
Step 2: Press Enter key to complete create table:
Step 3: Insert records into STUDENT table.
INSERT INTO Student VALUES (1001, ‘AKSHRA
AGARWAL,'FEMALE',70,11,’A’, ‘10/11/1996’);
Step 4: As you press enter key after typing above statement, 1
record will be stored into STUDENT table.
Step5: Similarly like step 3, enter other records of the following
table
Lab Activity 2: Open school database, then select student table and
use following SQL statements.
TYPE THE STATEMENT, PRESS ENTER AND NOTE THE OUTPUT
1 To display all the records form STUDENT table.
SELECT * FROM student ;
2. To display ony name and date of birth from the table STUDENT.
SELECT StdName, DOB FROM student ;
3. To display all students record where percentage is greater of
equal to 80 FROM student table.
SELECT * FROM student WHERE percentage >= 80;
4. To display student name, stream and percentage where percentage
of student is more than 80
SELECT StdName, Stream, Percentage WHERE percentage > 80;
5. To display all records of science students whose percentage is
more than 75 form student table.
SELECT * FORM student WHERE stream = ‘Science’ AND percentage > 75;

Lab Activity 3: Open school database, then select student table and
use following SQL statements.
TYPE THE STATEMENT, PRESS ENTER AND NOTE THE OUTPUT
1. To display the STUDENT table structure.
DESCRIBE Student;
2. To add a column (FIELD) in the STUDENT table, for example
TeacherID as VARCHAR(20);
ALTER TABLE Student ADD TeacherID VARCHAR(20);
3. Type the statement
DESC Student;
Press enter key, now note the difference in table structure.
4. Type the statement and press enter key, note the new field that
you have added as TeacherID
SELECT * FROM student;
3.To modify the TeacherID data type form character to integer
ALTER TABLE Student MODIFY TeacherID INTEGER ;
DESC Student;
SELECT * FROM student;

Lab Activity 4
1. To Drop (Delete) a field form a table. For e.g you want to delete TeacherID field.
ALTER TABLE Student DROP TeacherID;
2. To subtract 5 form all students percentage and display name and percentage.
SELECT name, percentage - 5 FROM Student;
3. Using column alise for example we want to display StdName as Student Name and DOB
as Date of Birth
then the statement will be.
SELECT StdName AS "Student Name",
DOB As “Date of Birth” FROM Student;
4. Display the name of all students whose stream is not Science
SELECT StdName FROM student
WHERE Stream <> ‘Science’;
5. Display all name and percentage where percentage is between 60 and 80
SELECT StdName, percentage FROM student WHERE percentage >=60 AND
percentage<=80 ;

Lab Activity 5:
1. To change a student name from SWATI MISHRA to SWATI VERMA whose
StdID is 1014 and also change
percentage 86.
UPDATE Student SET StdName = ‘SWATI VERMA’, percentage = 86
WHERE StdId = 1014;
2. To delete the records form student table where StdId is 1016.
DELETE FROM Student WHERE StdID = 1016;
3. Type the following SQL statement and note the output.
SELECT * FROM Student WHERE StdName LIKE 'G_' ;
SELECT * FROM Student WHERE StdName='G';
SELECT * FROM Student WHERE StdName LIKE 'G%' ;
SELECT * WHERE Student WHERE StdName='%G%' ;
4. Display all the streams in student table.
SELECT DISTINCT Stream FROM Student;
5. Note the output of the following statement.
SELECT StdName, Sex, Stream FROM Student WHERE percentage BETWEEN 70
AND 80;
67

You might also like