Fundamental database
lab exercise
PREPARED BY
INSTRUCTOR: ASMAMAW M
Create database and table
For example if we need to create a database registrar we can write the sql
statement on the query editor as:
create database registrar; then click execute
To create a student table with 7 attributes (studid, first name, last name, age,
gender, department, address)
create table student ( studid int identity(1,1) primary key, firstname varchar(30)
, lastname varchar(30), age int, gender varchar(6), department varchar(50),
adress varchar(30));
Con’t
To create an employee table with 9 attributes( emp_id, first name, last name, age, gender,
position, salary, department, address)
create table employee (
empid int identity(1,1) primary key, firstname varchar(30) , lastname varchar(30), age int,
gender varchar(6), position varchar(30), salary int, department varchar(50), adress
varchar(30),
)
Inserting records
It is possible to write the INSERT INTO statement in two forms.
1. The first form doesn't specify the column names where the data will be inserted, only their
values: INSERT INTO table_name VALUES (value1, value2, value3,...)
2. The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2,...)
For example: if we need to insert a record of a student
1. Insert into student values( 'Abebe','Belay', 24 , 'Male','Computer', 'Woldia')
Whereas by using the 2nd form
2. Insert into student (firstname, lastname, age, gender, department, adress) values
('Henok','Awoke',27, 'Male','InformationTechnology','Dessie')
if we need to insert a data for specified columns we have to write like:
For example to insert the student firstname, lastname and department into student table we
have to write like:
insert into student(firstname,lastname,department) values ('Zerihun','Alebachew','Economics')
Update
Example: update the age, gender and address of student zerihun with age=25, gender=male,
address=kombolcha.
update student set age=25, gender='Male', adress='kombolcha' where firstname='zerihun'
Con’t
Example: delete a student record with InformationTechnology department
delete from student where department='InformationTechnology'
Delete All Rows
It is possible to delete all rows in a table without deleting the table
Delete from table_name
Note! Make sure to do this only when you really mean it! You cannot UNDO this
statement!
Review
SQL DML
SQL DDL
SELECT - extracts data from a database
CREATE DATABASE - creates a new database
UPDATE - updates data in a database
DELETE - deletes data from a database ALTER DATABASE - modifies a database
INSERT INTO - inserts new data into a CREATE TABLE - creates a new table
database ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
Sample data
Create the following tables named Person and Order inside database named Order_Details.
Persons P_id FirstName LastName Address city
1 john alex 547 gonder
2 kebed dave 124 bahirdar
3 abel worku 875 debark
O_id orderNo P_id
order 1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Various Select examples
The SQL SELECT DISTINCT Statement
The DISTINCT keyword can be used to return only distinct (different) values.
SELECT DISTINCT column_name(s) FROM table_name;
Additional notes about the where clause
For text values
SELECT * FROM Persons WHERE LastName=‘dave’; correct
SELECT * FROM Persons WHERE LastName=dave; wrong
For numeric values
SELECT * FROM Persons WHERE Year=1965; correct
SELECT * FROM Persons WHERE Year='1965’; wrong
Con’t
Operators Allowed in the WHERE Clause – =,,<=,>=,<>, BETWEEN, LIKE, IN, AND, OR
Examples
SELECT * FROM Persons WHERE FirstName=‘kebed’ AND LastName=‘dave’;
SELECT * FROM Persons where P_ID <= 2 OR P_ID >=2;
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
Con’t
Example 1: The following query selects all data from persons ordered by last
name in ascending order(default)
SELECT * FROM Persons ORDER BY LastName;
Example 2: to select data sorted in descending order
SELECT * FROM Persons ORDER BY firstName, LastName DESC;
Insert and Update
Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", “FirstName"
and the “LastName" columns:
INSERT INTO Persons (P_Id, FirstName, LastName) VALUES (5, 'Tjessem', 'Jakob');
Update the remaining column values
UPDATE Persons SET Address='Nissestien 67', City='Sandnes„ WHERE FirstName=‘abel' AND
LastName=‘worku’;
Delete the last row
DELETE FROM Persons WHERE FirstName='Tjessem' AND LastName='Jakob„;
Becareful while updating and deleting, if you don‟tuse the where condition all rows will be
updated or deleted.
Limit Clause, Like Operator
Returns the top 5 rows from Persons table;
SELECT * FROM Persons LIMIT 5;
The LIKE operator is used to search for a specified pattern in a column.
SELECT * FROM Persons WHERE City LIKE ‘s%’;
Selects the persons living in a city that starts with "s" from the persons table
SELECT * FROM Persons WHERE City LIKE ‘%s’;
Selects the persons living in a city that ends with “s” from the persons table;
Select the persons living in a city that contains the pattern "tav" from the Persons table
SELECT * FROM Persons WHERE City LIKE ‘%tav%’;
CHECK ALL THE ABOVE QUERY BY ADDING NOT BEFORE OPRETARES.
IN and BETWEEN Operators
select the persons with a last name alphabetically between "Hansen" and "Pettersen"
from Persons
SELECT * FROM Persons WHERE LastName BETWEEN ‘Hansen’ AND ‘Pettersen’;
display the persons outside the range
SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen’;
select the persons with a last name equal to "Hansen" or "Pettersen" from;
SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen');
SQL Alias
You can give a table or a column another name by using an alias.
This can be a good thing to do if you have very long or complex table names or column names.
An alias name could be anything, but usually it is short.
Example: Assume we have a table called "Persons" and another table called "Product_Orders". We will
give the table aliases of "p" and "po" respectively.
Now we want to list all the orders that "Ola Hansen" is responsible for.
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po WHERE
p.LastName='Hansen' AND p.FirstName=„Ola‟;
The same SELECT statement without aliases:
SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons,
Product_Orders WHERE Persons.LastName='Hansen' AND Persons.FirstName=„Ola‟;
Aggregate Functions
Commonly used Aggregate functions Some of the commonly used aggregate functions are:
SUM
COUNT
AVG
MIN
MA
Example: Consider the following Employee table:
EMPLOYEE (EMP_ID, NAME, DEPT_NAME, SALARY)
CON’T
CREATE TABLE EMPLOYE ( EMP_ID int,NAME VARCHAR(50), DEPT_NAME VARCHAR(50), SALARY int );
INSERT RECORED TO EMPLOYEE TABLE
insert into EMPLOYE Values(100, 'Abebe', 'Biology', 5500)
insert into EMPLOYE Values(110, 'Henok', 'Electrical', 6500)
insert into EMPLOYE Values(112, 'Zelalem', 'Computer', 6500)
insert into EMPLOYE Values(120, 'Birhane', 'InformationTechnology', 7500)
insert into EMPLOYE Values(124, 'Abrham', 'Biology', 8500)
Query 1: To find the sum of all salaries in the organization:
SELECT SUM(SALARY) AS Total_slary FROM EMPLOYE
CON’T
Query 2: To find the sum of the salaries grouped by dept
SELECT SUM(SALARY) AS Total_slary FROM EMPLOYE group by DEPT_NAME
If we take a look at the previous query the information won’t tell us what the sum for a particular
department is. So to include that information we add DEPT_NAME in the SELECT
SELECT DEPT_NAME, SUM(SALARY) AS Total_salary FROM EMPLOYE group by DEPT_NAME
Query 3: If we want to calculate the AVG of all the salaries in the organization the SQL would be
SELECT AVG(SALARY) AS Average_salary FROM EMPLOYE
We use count function how many records we have with the given table
select count(*) AS Total_record from Employe
MIN and MAX
Min is used to display a record which has minimum value.
Query 4: To find the minimum salary within a particular department
SELECT DEPT_NAME, Min(SALARY) AS Min_salary FROM EMPLOYE group by DEPT_NAME
Max is used to display a record which has maximum value.
Query 5: To find the maximum salary within a particular department
SELECT DEPT_NAME, Max(SALARY) AS Max_salary FROM EMPLOYE group by DEPT_NAME