0% found this document useful (0 votes)
54 views15 pages

SQL Lab Manual Guide Materials

This document contains a SQL lab manual that covers: 1. An introduction to SQL, including what it is used for and common SQL statements. 2. Overviews of the main SQL languages: DDL for data definition, DML for data manipulation, and DQL for data queries. 3. Details on SQL data types and five labs covering topics like installing MySQL, creating databases and tables, inserting and modifying data, and advanced queries using subqueries.

Uploaded by

Birhanu Worku
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)
54 views15 pages

SQL Lab Manual Guide Materials

This document contains a SQL lab manual that covers: 1. An introduction to SQL, including what it is used for and common SQL statements. 2. Overviews of the main SQL languages: DDL for data definition, DML for data manipulation, and DQL for data queries. 3. Details on SQL data types and five labs covering topics like installing MySQL, creating databases and tables, inserting and modifying data, and advanced queries using subqueries.

Uploaded by

Birhanu Worku
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/ 15

SQL Lab Manual Database System-SWEG2108 AASTU2022

SQL Lab Manual Guide Materials (SWEG2108)

Lab 1: MySQL Installations and Connecting Database server


What is SQL Server?
 SQL Server is Server Side Processing RDBMs where as Access is Desktop based.
 The back-end component of most web application architecture.

SQL can be classified based on the following functionalities:


 Query data
 Updating, inserting, and deleting data
 Creating , modifying and deleting database objects
 Controlling access to database objects
 Providing data integrity and consistency

SQL statements can be divided into the following categories:


 DDL-used commands CREATE, ALTER, DROP
 DML-use commands INSERT, DELETE and UPDATE.
 DCL-use commands GRANT and REVOKE
 DQL-Use commands SELECT
 Administration Statements: use command SHOW, USE
 Transaction Control Statements (TCS): use commands COMMT, ROLLBACK,
SAVEPOINT and SET TRANSACTION.

1|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

SQL DATA TYPES : Data Types are a classification of a particular type of information. As like
other programming languages, the user should specify the data types for each field in the
database.

 SQL is very flexible language that enables you to accomplish all kinds of tasks. SQL
Statements (commands) – these commands are available in different relational DBMS
software such as MySQL, MSSQL, SQLlite, PostGreSQL, etc. In this lab, we select
MySQL as it is open source and most popular to develop web applications.
 Installation see My SQL Community Server download page

(https://dev.mysql.com/downloads/installer/)

 Connecting and disconnecting mySQL: basically, there two options two write SQL

commands. (1) Command line: run “mysql -u root -p” from command line and (1)

Using GUI tools like Workbench MySQL. We will use workbench MySQL in this

session.

 To see the available database: use the SHOW database command. e.g SHOW

DATABASES;

 To Select a database from the list, use the USE command. e.g. USE db_name;

2|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 2: Data Definition Language (DDL)

DDL: CREATE, ALTER, DROP commands


Creating Database
 CREATE database [Student database]
Dropping database
 DROP database [Student database]

Creating a table: Tables are building blocks of in any RDBMS.


 General Form:
 CREATE TABLE Base_Table_Name(
o Column_Name1 Data Type ,
o Column_Name2 Data Type ,
o Column_Name3 Data Type ,
o PK_Definition,
o FK_definition )
 Each column definition may include [NULL|NOT NULL| WITHDEFAUL|UNIQUE]
 PK_Definition can be in the form PRIMARY KEY(column_name).
 FK_Definition can be in the form FORIENGN KEY(column_name) REFERENCES
Table_name(Column_Name).
Example:
CREATE TABLE [dbo].[Student](
[SID] [smallint] NOT NULL,
[Name] [varchar](50) NULL,
[Sex] [nchar](10) NULL check(sex IN('Male' , 'Female')),
[CGpa] [real] default 0 not null check(CGpa<=4 and CGpa>=0) ,
[DoBith] [smalldatetime] NULL,
CONSTRAINT [PK_Student] PRIMARY KEY ([SID] ASC)

3|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

)Modifying a table: used to change the definition of existing table.


 General Form:
 ALTER TABLE base_table_name
o ADD Column_Name3 Data Type or DROP Column_Name3 Data Type
Example: To Add new AGE column in to table STUDENT
ALTER TABLE [dbo].[Student] ADD column [Age] [smallint] NULL
To delete a column from table STUDENT
ALTER TABLE [dbo].[Student] DROP column [Age]
To add CHECK constraint on a table column
ALTER TABLE [dbo].[Student] add Age smallint check(Age>17 and age<61)

To Add/Drop primary key constraint or Foreign Key constraint, we use ALTER statement
 ALTER TABLE base_table_name
o ADD/DROP CONSTRAINT constraint_name
o PRIMARY KEY(column_name)
 Example:
 ALTER TABLE base_table_name
o ADD/DROP CONSTRAINT constraint_name
o FORIENGN KEY(column_name) REFERENCES Table_name (Column Name).
 Example:
Deleting a table: used to delete an existing table.
 General Form:
o DROP TABLE base_table_name|database_name|view_name
 Example:

4|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 3: Data Manipulation Language (DML)


DML: change the state/content of the database.
 INSERT: used to insert new rows into a table.
 General Form:
o INSERT INTO table_name[column_name1, column_name2, column_name3)
o VALUES [literals, literals,literals)|[subquery]
Example: Inserting new row into student table
INSERT INTO Student(SID,name, cgpa,dobith, age)
VALUES (10,'Zemen',3.6,'12/7/1978',27)
 UPDATE: used to update existing row or rows of a table.
 General Form:
o UPDATE table_name
o SET column_name1=Literal/expression, column_name2=Literal/expression
o [WHERE condition]
Example: Change cgpa to 3.8 for student whose ID is 10.
UPDATE Student
SET CGPA=3.8
WHERE SID=10
 DELETE: used to delete existing row or rows from a table.
 General Form:
o DELETE
o FROM table_name
o [WHERE condition]
 Example: Delete a student record whose ID is 10.
DELETE
FROM Student
WHERE SID=10

5|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 4: Data Query Language (DQL)


 DQL-used to construct queries or subqueries
 Use commands SELECT
 General Form:
o SELECT[ALL|DISTINCT] scalar expression(s) FROM table(s)
o WHERE conditional expression
o GROUP BY column(s)
o HAVING conditional expression
o ORDER BY column(s)

 The SELECT-lists the items-list of column names, list of computed values and aggregate
functions (min, max, count, avg, etc) to be retrieved.
 The FROM clause specifies the table(s) from which information is retrieved.
 The WHERE clause tells to SQL to include only certain rows of data. It specifies search
criteria. The criteria may be combined by logical operators: OR, AND, IN, LIKE, NOT etc
 The GROUP BY clause specifies a summary query. It usually used with aggregate function.
E.g. GROUP BY PublisherName….will group result set based on publisher’s Name
 The HAVING clause tells SQL to include only certain groups produced by the GROUP BY
clause in the query result set. Having clause is the equivalent of where clause.
 The ORDER BY clause sorts or orders results based on the data in one or more columns in
ASC or DESC order.
Note: Select * …….selects data in all columns.
Note: Use DISTINCT to avoid duplicates of rows in the results.
EXAMPLE:
--Total number of students who in each course
select count(takes.sid) as [Number of Students],course.ctitle from student inner join takes on
Student.Sid=takes.sid
inner join course on course.cid=takes.cid
group by course.cid,ctitle--,course.ctitle

6|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

--Total number of students who take database system


select count(takes.sid) as [Number of Students],course.ctitle from student inner join takes on
Student.Sid=takes.sid
inner join course on course.cid=takes.cid
group by course.cid,ctitle--,course.ctitle
having course.ctitle='database system'
--List of courses which are not taken by student
select * from course
where CID NOT IN(select CID from takes)

7|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 5: Data Query Language (DQL)- Advanced

DQL: used to retrieve information using SUBQUERIES.


SubQueries are almost identical with ordinary SELECT statements Except with the following
differences:
 Subquery produces a single column of data as its result. So you can’t use SELECT *.
 ORDER BY clause cannot be specified. Because it is used internally. It is not displayed to
the user. So it doesn’t make any sense.
 A Subquery cannot be a UNION , only a single select statement is allowed.
 SQL OPERATORS: Operators are represented by a single character or reserved word.
 Two types of Operators: Binary and Unary operators
 Arithmetic operators: (+,-,*,/,)
 Comparison operators: (=,!=,<>,<,>,>=, IN, NOT IN, IS NULL, IS NULL, LIKE ‘%gir’,
ALL, SOME, ANY, EXISTS, BETWEEN x and y i.e. >=x and <=y
 NOT can be used with IN, LIKE, EXISTS, BETWEEN, NULL and with other conditional
expression as NEGATION.
 E.g: SELECT Title from Catalog where exists (Select * from OrderDetails where
OrderDetail.BookID=Catalog.BookID)
 The comparison operators work for numeric, character and datetime data types.
 ANY and ALL work for any value retrieved in inner query.
 =ANY, >ANY, <ANY, >=ANY, <=ANY are same is true for ALL.
 E.g: SELECT Title from Catalog WHERE Price >ALL(SELECT AVG(Price) from Catalog
Group By Category)
 ALL is evaluating every rows to be TRUE and ANY is at least one rows to be TRUE
 Logical Operators: AND, OR and NOT
 Set Operators: UNION(returns all distinct rows from both queries), UNION ALL,
INTERSECT, MINUS
 E.g: SELECT Title FROM Catalog INTERSECT Select Title from OrderDetails
 Used with IN[NOT IN] or <>, =, <,>=, ANY,ALL, EXISTS etc predicates in the where
clause. E.g. SELECT Title from catalog where price>(select avg(price) from catalog)

8|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

 Used with multiple rows comparison operators(IN,=ANY,>ANY,<=ALL, etc…) E.g: Get


the names of all authors who have more than two books in the catalog. SELECT name
from Author where Authors_ID IN(SELECT Authors_ID from catalog group by
authors_ID Having count(*)>2)
 Get list of courses which are taken by more than 2 student
o select ctitle from course
o where cid in (select cid
 from takes
 group by cid
 having count(*)>2)
 List of students who scored more than 2A's in the courses they registed
o select * from student
o where SID IN (select sid from takes
o group by sid,grade
o having count (*)>2 and grade='A')
 List of students who scored atleast 1F's in the courses they registed
o select * from student
o where SID IN (select sid from takes
o group by sid,grade
o having count (*)>0 and grade='F')
 List of female students who scored more than 1F's in the courses they registed
select * from student
where SID IN (select sid from takes
group by sid,grade
having count (*)>0 and grade='F') and sex='female'
 Nested SUBQUERIES are also allowed. Eg: Get the details of all the authors whose books
are being sold from the book club. Select * from Author where Authors_ID IN(select
Authors_ID from catalog where book_ID IN (Select Distinct book_ID from
orderDetials))

9|Page
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 6: Joins and Union

JOINS and UNIONS


Why we need JOINs ? Because one table may not give us the information we need.
What is a good Join? A join where the Join condition is based on a PK or a FK makes a good
join.

Types of JOIN:
[Natural] Join: returns all matching rows from both rows by making Cartesian product. Same as
inner join or join.
e.g SELECT Student.Name, Takes.grade, Course.CTitle
FROM Course ,Student, takes
where Course.CID = Takes.CID and Takes.SID = Student.SID
Self Join: Join a table with itself
E.g. Find out the titles that have the same price.
Select c1.title,c1.price from catalog c1, catalog c2 where c1.price=c2.price
E.g. Students having same cgpa.
select distinct s1.name+' And '+s2.name+' have same cgpa of ', s1.cgpa from student s1, student s2
where s1.cgpa=s2.cgpa and s1.name<>s2.name
[Inner]Join: returns matching rows from both tables.
Outer Join: returns both matching or/and non-matching rows from both tables.
Outer Join: Types: Left[outer],Right[outer] and Full[outer]
General Form for Inner/Outer Join:
 Table_reference[natural] outer_join_type
 JOIN table_reference
 [ON join_condition]
 [USING column_commalist]
 If Natural is used, ON or Using are not necessary.
 Left outer join-retains non matching rows from the left table in the result.

10 | P a g e
SQL Lab Manual Database System-SWEG2108 AASTU2022

E.g SELECT Student.Name, Student.Sex, Takes.grade, Course.CTitle


FROM Course left outer JOIN
Takes ON Course.CID = Takes.CID right outer JOIN
Student ON Takes.SID = Student.SID
INNER JOIN and IN –may be used to produce same result
Example: List all students who take database system course.
a)Using INNER JOIN
SELECT Student.*-- Course.CTitle
FROM Course INNER JOIN
Takes ON Course.CID = Takes.CID INNER JOIN
Student ON Takes.SID = Student.SID
WHERE (Course.CTitle = 'Database System')

b)Using IN
select * from student
where SID IN
(select SID from Takes
where CID IN(select cid from course
where ctitle='Database System' ))

11 | P a g e
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 7: Stored Procedures

Stored procedure on student database


--SelectStudent
CREATE PROCEDURE SelectStudents
AS
SELECT * FROM [Student]
GO
EXEC SelectStudents
/////////////////////////////////////////////////
--InsertStudent
CREATE PROCEDURE InsertStudent
(@SID smallint, @Name varchar(50), @sex char (15), @cgpa real,
@DateofBirth datetime, @Age smallint)
AS
INSERT INTO [student] ([SID], [Name], [SEX], [CGPA], [Dobith],[age]) VALUES (@SID,
@Name, @sex, @cgpa,@DateofBirth, @Age)
GO
EXEC InsertStudent 23, 'John','Male',4.0,'1/11/1980',20
--DeleteStudent
CREATE PROCEDURE DeleteStudent
@SID smallint
AS
DELETE FROM [Student] WHERE [SID] = @SID
GO
EXEC deleteStudent 23
--UpdateStudent
CREATE PROCEDURE UpdateStudent
(@Name char(20), @CGPA real,
@birthDate datetime, @SID int)

12 | P a g e
SQL Lab Manual Database System-SWEG2108 AASTU2022

AS
UPDATE [Student] SET [Name] = @Name,[cgpa] = @cgpa, [Dobith] = @birthDate WHERE
[SID] = @SID
GO
EXEC UpdateStudent 'ZEMEN',4.0,'8/30/1990',5

13 | P a g e
SQL Lab Manual Database System-SWEG2108 AASTU2022

Lab 8: Triggers
Triggers on Student database
Triggers is a kind of stored procedure that is executed automatically when an action is
performed on database objects
a)To inform the user when user inserts new rows
CREATE trigger [student_trigger] on [dbo].[Student]
after insert as
select 'one new row is inserted'Example:
Insert into student values(33,'Haimanot','Female',3.8,'12/3/1988 12:00:00 AM',27)
b)To prevent user from deleting data

CREATE TRIGGER [student_del] ON [dbo].[Student]


after delete
AS PRINT 'You must ask your DBA to drop or alter tables!'
ROLLBACK TRANSACTION
Example: delete student
where SID =34
c) dropping trigger
DROP TRIGGER [dbo].[student_trigger_Insert]

Lab 1: Exercise
create mini-student database for a data requirement specification:
“Student takes course.” Identify entities, attributes, relationships, PK, FK,
check constraints, defaults, null values,. Create tables using MS Access.
Populate sample data and formulate queries to retrieve data. Create it
using MYSQL.

14 | P a g e
SQL Lab Manual Database System-SWEG2108 AASTU2022

15 | P a g e

You might also like