0% found this document useful (0 votes)
32 views

SQL Practical Guide - 1: Mohamed Ghasia ICT 114 Dec 2012/13

This document provides guidance on using SQL to perform practical tasks like creating databases and tables, inserting, updating, and retrieving data. It outlines how to create a database and table, insert data, alter tables by adding or dropping columns, update and delete data, retrieve data using conditions, order results, and apply aggregate functions. The document contains examples of SQL statements to accomplish each task using the student database and table as examples.

Uploaded by

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

SQL Practical Guide - 1: Mohamed Ghasia ICT 114 Dec 2012/13

This document provides guidance on using SQL to perform practical tasks like creating databases and tables, inserting, updating, and retrieving data. It outlines how to create a database and table, insert data, alter tables by adding or dropping columns, update and delete data, retrieve data using conditions, order results, and apply aggregate functions. The document contains examples of SQL statements to accomplish each task using the student database and table as examples.

Uploaded by

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

SQL PRACTICAL GUIDE -1

Mohamed Ghasia
ICT 114
Dec 2012/13
Objectives

• MU12&*dict2008

• WAMP
• -WINDOWS
• -APACHE
• -MYSQL
• -PHP
Outcomes
• Students should be able to do the following:-
– Create database
– Create database table
– Insert data into a database table
– Update data into a database table
– Update database table
– Retrieve data from table (s)
– Join tables [equal join, left joins, right joins]
– Drop database /tables
– Apply group functions
– Use operators [ AND , OR, IN, =, <>,like, >,<, IS NULL, NOT IN, NOT
BETWEEN
– Use aliases
– Show tables/databases
– Describe tables
– Order by and group by
– Sub queries
Creating database
1. Log into MYSQL
2. List the available databases :
MYSQL>show databases;
3. Create database called training:
MYSQL> create database training;
4. List the available databases :
MYSQL>show databases;
5. The database should be created at this stage and
listed together with other databases.
6. To use training database among the list:
MYSQL> use training;
Creating Basic Tables
To create a basic table with no constraints:-
Create table student (
stID char(30) primary key,
Fname char(30),
Surname char(30),
Sex char(6),
Town char(30),
Email char(30),
CellNO char(30)
);
Creating Tables
To create a basic table with constraints:-
Create table student (
stID char(30) primary key,
Fname char(30) not null,
Surname char(30) not null,
Sex char(6) not null,
Town char(30) not null default ‘Mzumbe’,
Email char(30) unique,
CellNO char(30) unique
);
Describing and listing tables
• To show list of tables:
MYSQL>show tables;
To show student table schema:
MYSQL> describe student; or
MYSQL> desc student;
To show content of a table student:
MYSQL> select * from student;
Inserting data into table
• Inserting through headings:-

MYSQL> Insert into student (


stid,email,cellno,sex,town,fname,surname,DoB)
values (“mu001”,”[email protected]
”,”0713121212”,”
Male”,”Morogoro”,”Majuto”,”Chonde”,”1990/12/
25”);
NOTE:
Order of columns should match the insert data.
All attributes except for those declared as number or integers
should be enclosed in quotation marks.
It is appropriate when you want to skip some attributes
Inserting data into table
• Inserting without headings:
MYSQL> Insert into student values (“mu001”,
”Majuto”,”Chonde”,” Male”, ”Morogoro”,
[email protected]”,
”0713121212”,” 1990/12/ 25”);

NOTE:
Arrangement of values should correspond
to the same in the table.
these examples are based on created tables;
match your table well
Altering Tables
• The ALTER TABLE statement is used to add, delete, or
modify columns in an existing table.
• SQL ALTER TABLE Syntax
• To add a column in a table, use the following syntax:
MYSQL>ALTER TABLE table_name ADD column_name
datatype constraints;
• To delete a column in a table:
MYSQL>ALTER TABLE table_name DROP COLUMN
column_name;
• To change the data type or constraint in a table:
MYSQL>ALTER TABLE table_name ALTER COLUMN
column_name datatype constraint;
Altering Tables
Inserting columns, changing data types, dropping
columns, adding constraints
• Adding new column(s) in a student table:
MYSQL> ALTER TABLE STUDENT add (DoB date not null,
Marital char(10));
• Droping column(s) from student table:
MYSQL>ALTER TABLE STUDENT drop DoB,cellno;
• Changing data types or constraints:-
MYSQL>alter table student modify marital
char(20) not null;
Altering Tables
• Inserting foreign key
MYSQL> ALTER TABLE student
ADD FOREIGN KEY (csid)
REFERENCES course(csid);
MYSQL> ALTER TABLE Sudent
ADD CONSTRAINT fk_student
FOREIGN KEY (CSID)
REFERENCES Course(csid);
NOTE: -parent table such as course should exist first
• referenced attribute should be declared within same domain
in both tables. Ie data type and size in both tables should be
same
• If there are data inside child table, error might appear if they
violate integrity rules
Updating table content
• Updating a column with same value to all
records:- example setting student town to kilosa.
MYSQL> update student SET town=“kilosa”;
• Updating specific records: example, set town for
students with ID 1234/t.08,12356/t.08 to songea.
MYSQL> update student SET town=“songea” WHERE stid
IN (“1234/t.08”, “12356/t.08”);

NOTE:
Observe WHERE clause to specify update criteria.
Without it, all records will be updated with new entry
Deleting table content
• Delete everything from student table:
MYSQL> delete from student;
• Delete only students from tanga and
sumbawanga:
MYSQL> delete from student where town=“tanga”
and town=“sumbawanga”;
NOTE:
Observe the use of WHERE to specify what to
delete?
Dropping table(s)/database/views
• To delete a database:-
MYSQL> DROP DATABASE database_name;
• To delete a table:-
MYSQL> DROP TABLE table_name;
• To delete all data inside student table:
MYSQL> TRUNCATE student;
NOTE: these commands are sensitive, use them
with care!! It will not warn u
Retrieving Data from table(s)
• Basic data retrieval (from single table)
• Retrieving all attributes and all rows:-
• MYSL>select * from tablename;
- Select*from student;
• Retrieving some attributes only:-
MYQL>select fname,surname,sex,town from
student;
• Retieving certain records such as female
students:-
– Select * from student WHERE sex=“female”;
Retrieving Data from table(s)
– Retieving female students from ICTM :-
MYSQL>Select * from student where csid=“ictm” AND
sex=“female”;
– Retrieving students born between 1990 and 1995
MYSQL>select * from student WHERE dob BETWEEN
“1990” AND “1995”;
– Retrieving students born after 1992
MYSQL>select * from student WHERE dob>”1992”;
Retrieving Data from table(s)
• Basic data retrieval ( IN, IS NULL, =, NOT IN)
• Retrieve students from southern Tanzania
MYSQL>select * from student where town IN
(“mtwara”,”lindi”,”mikindani”,”songea”,”masasi”,”liwale”,”tun
duru”,”nachingwea”,”newala””ruvuma”);
• Retrieve female students not coming from southern zone
MYSQL>select * from student where town NOT IN
(“mtwara”,”lindi”,”mikindani”,”songea”,”masasi”,”liwale”,”tun
duru”,”nachingwea”,”newala””ruvuma”) and SEX=“female”;
• Retrieve list of students whom have not indicated date they
were born:-
MYQL>select * from student WHERE dob IS NULL;
Retrieving Data from table(s)
• The BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The
values can be numbers, text, or dates.
• SQL BETWEEN/not between Syntax
MYSQL> SELECT column_name(s)
FROM table_name WHERE column_name BETWEEN value1
AND value2;

MYSQL> SELECT column_name(s)


FROM table_name WHERE column_name NOT BETWEEN value1
AND value2;
– Retrieving students born between 1990 and 1995
MYSQL>select * from student WHERE dob
BETWEEN “1990” AND “1995”;
Retrieving Data from table(s)
• Example: LIST STUDENTS BORN BTN 1985 AND 1990
MYSQL> SELECT * FROM STUDENT
WHERE dOb BETWEEN “1985/01/01” AND “1990/06/31”;
• List students with surname between Dadi and
Mohamed
MYSQL> Select * from Student
where surname between “dadi” and “mohamed”;
• List students registered not between 17th to 30th
october 2011
MYSQL>select * from student
where rdate not between “2011/10/17” and
“2011/10/30”;
Retrieving Data from table(s)
The LIKE Operator
The LIKE operator is used to search for a specified
pattern in a column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Example: list student whose town starts with M
MYSQL>select * from student where town LIKE
“M%”;
MYSQL>select * from student where town LIKE
“%A”; ? What is the result of this query?
MYSQL>select * from student where town LIKE
“%ang%”; ? What is the result of this query?
Order by Clause
• It is used with select statement to sort the resulting
dataset either in ascend or descending. User needs to
specify attribute to be used for sorting:-
• The following dataset will be sorted based on boom
amount descending:-
MYSQL> select * from student order by boom desc;
• The following dataset will be sorted based on courseid
descending:-
MYSQL>select * from student order by csid asce;
NOTE:
Order by clause is applied at the end of SQL statement as
referred in the syntax
USING Group Function
• Count, sum, average, max, min
Count  used for counting items in a list (range)
Sum used for doing summation of numerical
data in a given list (range)
Average  returns average of the numerical
values in a range excluding null
Maximum  returns maximum numerical value
in a given range excluding null
Maximum  returns minimum numerical value
in a given range excluding null
m
USING Group Function & Aliases
• Compute the sum and average boom for each
course
MYSQL>select csid, sum(boom),avg(boom) from
student GROUP BY csid;
MYSQL>SELECT CSID KOZI,SUM(BOOM) “JUMLA YA
BOOM”,AVG(BOOM) “WASTANI ” FROM STUDENT
GROUP BY csid;
• Compute the sum and average boom of female
student in each course
MYSQL>SELECT CSID KOZI,sex,SUM(BOOM) “JUMLA
YA BOOM”,AVG(BOOM) “WASTANI ” FROM
STUDENT where sex=“female” GROUP BY csid,sex;
USING Group Function & Aliases
• Count number of student in each course
MYSQL>SELECT CSID KOZI,COUNT(STID) IDADI FROM
STUDENT GROUP BY CSID;
• Count number of student in each class from eastern zone
MYSQL>SELECT CSID KOZI,COUNT(STID) IDADI FROM
STUDENT WHERE TOWN IN(“DAR ES
SALAAM”,”MOROGORO”,”PWANI”) GROUP BY CSID;
• Count number of female student in each class from
eastern zone
MYSQL>SELECT CSID KOZI,COUNT(STID) IDADI FROM
STUDENT WHERE sex=“male” AND TOWN IN(“DAR ES
SALAAM”,”MOROGORO”,”PWANI”) GROUP BY CSID;
USING Group Function & Aliases
• List the minimum and maximum student boom
in each course
MYSQL>SELECT CSID KOZI,MIN(BOOM) “MKOPO
WA CHINI”,max(boom) “mkopo wa juu” FROM
STUDENT group by csid;
• List average boom and number of student in a
course
Mysql>select avg(boom), count(stid), Csid From
Student group by Csid;
Sub query
• List student who receives boom that is less than
average:
• Query 1: what is the average boom?  MYSQL>select
avg(boom) from student;
• Query 2: Students whose boom is less than average
 MYSQL>select * from student where
boom<(query1);

Answer:

MYSQL>select * from student where boom<(select


avg(boom) from student);
Sub query
• List students who receives minimum boom
– Query 1: what is a minimum boom  MYSQL>select
min(boom) from student;
– Query 2: list students who receive minimum boom 
MYSQL>select * from student where boom=(query1);

Answer:

MYSQL> select * from student where


boom=(select min(boom) from student);
Sub query
• List students who receives maximum boom
– Query 1: what is a maximum boom 
MYSQL>select max(boom) from student;
– Query 2: list students who receive maximum
boom  MYSQL>select * from student where
boom=(query1);

Answer:

MYSQL> select * from student where


boom=(select max(boom) from student);
JOIN
• Left Join - syntax
– Select
table1.columna,table1.columnb,table1.column..z,
table2.columna,table2.columnb.table2.column..z
from table1 LEFT JOIN table2 ON
table1.columnc=table2.columnc;
• List owners with their respective taxi
MYSQL>select
owner.oid,owner.fname,owner.surname,
taxi.taxid,taxi.regno,taxi.make from owner
left join taxi ON owner.oid=taxi.oid;
JOIN
• List students with their respective room and
hostel:-
– MYSQL>select
student.stid,student.fname,student.surname,room.ro
omid,hostel.hname from student left join room,hostel
on student.rooid=room.roomid AND
room.hoid=hostel.hoid;
JOIN
• In order to retrieve data that are based in
more that one table, the tables must be joined
first
• Right Join - syntax
– Select
table1.columna,table1.columnb,table1.column..z,
table2.columna,table2.columnb.table2.column..z
from table1 LEFT JOIN table2 ON
table1.columnc=table2.columnc;
JOIN
• Display parents with their respective student
– MYSQL>select
pare.fname,parent.surname,student.stid,student.f
name,student.csname from parent right join
student ON student.parid=parent.parid;
• List course with their respective students
– MYSQL>select
course.csid,course.csname,student.stid,student.fn
ame,student.surname FROM course right join
student IN course.csid=student.csid;
JOIN
• Equal Join- syntax
• Select
table1.columna,table1.columnb,table1.column..z,
table2.columna,table2.columnb.table2.column..z
from table1, table2 WHERE
table1.columnc=table2.columnc;
• List owners with their respective taxi
MYSQL>select
owner.oid,owner.fname,owner.surname,
taxi.taxid,taxi.regno,taxi.make from owner,
taxi WHERE owner.oid=taxi.oid;
JOIN
• Equal Join- syntax
• List students with their respective course and faculty
MYSQL>SELECT
student.stid,student.fnsme,student.surname,s
tudent.sex,course.csname,faculty.fcname
FROM student,course,faculty
WHERE student.csid=course.csid AND
course.fcid=faculty.fcid;
WORKING WITH VIEWS
• CREATING VIEWS syntax:-
CREATE VIEW viewname AS SELECT column(s)
from table(s) where condition order by column;

Example :
• List students from ICTB, ICTM, and ITS
MYSQL>CREATE VIEW ICT_STUDENTS AS
SELECT * FROM STUDENT WHERE CSID IN
(“ICTB”,”ICTM”,”ITS”);
WORKING WITH VIEWS
• list of students who do not receive boom
MYSQL>CREATE VIEW students_with_no_boom as SELECT
* FROM STUDENT WHERE BOOM IS NULL;

• List Nyirenda students with their respective rooms


MYSQL>CREATE VIEW nyirenda_students AS SELECT STID,
FNAME, SURNAME, SEX, CSID, ROOMID, HSNAME FROM
STUDENT,ROOM,HOSTEL WHERE HSNAME= “NYIRENDA”
AND STUDENT.ROOMID=ROOM.ROOMID AND
ROOM.HSID=HOSTEL.HSID;
WORKING WITH VIEWS
• List male students from fst
MYSQL>CREATE VIEW FST_STUDENT AS SELECT
STID,FNAME,SURNAME,SEX,CSNAME,FCNAME
FROM STUDENT,COURSE,FACULTY
WHERE STUDENT.CSID=COURSE.CSID AND
COURSE.FCID=FACULTY.FCID AND FCID=“FST” AND SEX=“MALE”;
• list female student from fol
MYSQL>CREATE VIEW FST_STUDENT AS SELECT
STID,FNAME,SURNAME,SEX,CSNAME,FCNAME
FROM STUDENT,COURSE,FACULTY
WHERE STUDENT.CSID=COURSE.CSID AND
COURSE.FCID=FACULTY.FCID AND FCID=“FOL” AND SEX=“FEMALE”;
WORKING WITH VIEWS
• list eastern zone students with their respective course name and faculty name
MYSQL>CREATE VIEW EASTERN_STUDENT AS SELECT
STID,FNAME,SURNAME,SEX,CSNAME,FCNAME
FROM STUDENT,COURSE,FACULTY
WHERE STUDENT.CSID=COURSE.CSID AND
COURSE.FCID=FACULTY.FCID AND TOWN IN (“DAR ES
SALAAM”,”PWANI”,”MOROGORO”);
• list students their boom, tax is 0.05 boom, and net pay
MYSQL>CREATE VIEW STUDENTS_WITH_NETBOOM AS SELECT
STID, FNAME, SURNAME, SEX, CSID, BOOM, 0.05*BOOM
TAX,BOOM-(0.05*BOOM) NET
FROM STUDENT ;
WORKING WITH VIEWS
• Views can be described same way relations are described:-
MYSQL>describe viewname;
Example:
MYSQL>describe students_with_netboom;

MYSQL>desc EASTERN_STUDENT;
• Views can be queried same way relations do:-
example:
• To display views’ content
MYSQL>select * from students_with_netboom;
• To display female students_with_netboom
MYSQL>select * from student_with_netboom where
sex=“female”;
WORKING WITH VIEWS
• Adding content into views; depends on the type of view created.
Some views allows data entry, some do not allow data entry
-END-

You might also like