FDB Lecture05

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Jawzjan University

Department of Computer Science

Fundamentals of
Database
Prepared by: Khudaydad MAHMOODI
Overview
 SQL (Structured Query Language)
 Database Languages
SQL
SQL (Structured Query Language) was developed in 1970’s in
an IBM laboratory “San Jose Research Laboratory” (now the
Amaden Research center). SQL is derived from the SEQUEL
(Structured English QUEry Language) one of the database
language popular during 1970’s. SQL established itself as the
standard relational database language. Two standard
organization (ANSI) and International standards organization
(ISO) currently promote SQL standards to industry.
SQL
SQL is a language used for storing and managing data in
RDBMS. SQL was the first commercial language introduced
for E.F Codd’s Relational model. Today almost all RDMBS
(MySQL, Oracle, Informix, Sybase, Ms Access, etc) uses SQL
as the standart database language. SQL is used to perform
all type of data operations in RDBMS.
Database Languages
SQL defines some data languages to manipulate data of RDBMS.
 DDL (Data Definition Language)
 DML (Data Manipulation Langauge)
 TCL (Transaction Control Language)
 DCL (Data Control Language)
 DQL (Data Query Langugae)
Database Languages
 DDL (Data Definition Language)
All DDL commands are auto-committed. That means it saves all the
changes permanently in the database. DDL statements are used to define
and manage the objects in the database.

Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table
DDL: CREATE
The CREATE statement is used to create a new database or table.

To create database:
CREATE DATABASE `DatabaseName`;

To create table:
CREATE TABLE `TableName` (
`ColumnName1` DataType [Constraint],
`ColumnName2` DataType [Constraint],
`ColumnName3` DataType [Constraint],
...
);
DDL: CREATE
Lets create a sample database and its tables.
CREATE DATABASE `enrollment`;

CREATE TABLE `student` (


`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`first_name` VARCHAR( 50 ) NOT NULL ,
`last_name` VARCHAR( 50 ) NOT NULL
);

CREATE TABLE `subject` (


`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 100 ) NOT NULL ,
`credit` TINYINT NOT NULL
);
DDL: CREATE
CREATE TABLE `enroll` (
`student_id` INT NOT NULL ,
`subject_id` INT NOT NULL ,
`create_date` DATETIME NOT NULL
);
If you try to create a table twice, you will probably get a warning like
"Table already exists.". To avoid this you can use "IF NOT EXISTS"
keyword:
CREATE TABLE IF NOT EXISTS `enroll` (
`student_id` INT NOT NULL ,
`subject_id` INT NOT NULL ,
`create_date` DATETIME NOT NULL
);
DDL: ALTER
The ALTER statement is used to add, delete, or modify columns in an
existing table or to add and drop various constraints on an existing.

To add new column to student table:


ALTER TABLE `student` ADD `date_of_birth` DATETIME
NOT NULL AFTER `last_name`;

To delete an existing column from student table:


ALTER TABLE `student` DROP `date_of_birth`;
To change one of the column name of student table:
ALTER TABLE `student` CHANGE `date_of_birth` `dob` DATETIME
NOT NULL;
DDL: TRUNCATE
The TRUNCATE statement is used to delete the data inside a table, but
not the table itself.

TRUNCATE TABLE `TableName`;

To delete all data from student table:


TRUNCATE TABLE `student`;
DDL: DROP
The DROP command is used to delete an entire database or table.

DROP DATABASE `DatabaseName`;


DROP TABLE `TableName`;

To delete entire "enrollment" database:


DROP DATABASE `enrollment`;

To delete a table in "enrollment" database:


DROP TABLE `student`;
DDL: RENAME
The RENAME command is used to change the name of a database or a
table. Sometimes, we choose non-meaningful name for the table. So it is
required to be changed.
RENAME DATABASE `OldName` TO `NewName`;
RENAME TABLE `OldName` TO `NewName`;

To change enrollment database name:


RENAME DATABASE `enrollment` TO `db_enrollment`;
To change student table name:
RENAME TABLE `student` TO `tbl_student`;
Database Languages
 DML (Data Manipulation Language)
DML is statements are used for managing data in database. DML
commands are not auto-committed. It means changes are not permanent
to database, they can be rolled back.

Command Description
insert to insert a new row
upadate to update existing row
delete to delete a row
merge merging two rows or two tables
DML: INSERT
The INSERT command is used to insert data into a table.

INSERT INTO `TableName` (`column1`, `column2`, ...)


VALUES ('value1', 'value2', ...);

Lets insert a record to subject table:


INSERT INTO `subject` (`id`, `title`, `credit`) VALUES (NULL,
'Fundamentals of Database', 4);

Or,
INSERT INTO `subject` VALUES (NULL, 'Fundamentals of
Database', 4);

INSERT INTO `subject` (`title`, `credit`) VALUES


('Fundamentals of Database', 4);
DML: INSERT
If a column is defined with default value, so we can insert data to that
column with its deafult value.
INSERT INTO `subject` (`id`, `title`, `credit`) VALUES (NULL,
'Fundamentals of Database', default);

Or,
INSERT INTO `subject` (`id`, `title`) VALUES (NULL,
'Fundamentals of Database');

We can also insert multiple records in a single query:


INSERT INTO `subject`
(`id`, `title`, `credit`)
VALUES
(NULL, 'Fundamentals of Database', 4),
(NULL, 'Data Structures', 4),
(NULL, 'Operating System-II', 3);
DML: UPDATE
UPDATE command is used to update a row of a table.

UPDATE `TableName` SET `column1`=value1, `column2`=value2, ...


WHERE condition;

Lets update data from subject table:


UPDATE `subject` SET `credit`=4;

UPDATE `subject` SET `credit`=4 WHERE `id`=1;

We can also update multiple columns in asingle query:


UPDATE `subject` SET title='C#', `credit`=4 WHERE `id`=3;
DML: DELETE
The DELETE command is used to delete data from a table. Delete
command can also be used with condition to delete a particular row.
DELETE FROM `TableName` WHERE condition;

To delete all records from subject table:


DELETE FROM `subject`;

To delete a particular row from subject table:


DELETE FROM `subject` WHERE `id`=2;
DML: MERGE
The MEREGE statement is used to to merge two rows or two tables. This
command combines INSERT, DELETE, and UPDATE operations into one
table.
SQL: SELECT
SELECT query is used to retrieve data from a table. It is the most used
SQL query. We can retrieve complete data from a table, or partial by
mentioning conditions using WHERE clause.
To retrieve some columns data from a table:
SELECT `column1`,`column2`,... FROM `TableName`;
To retrieve all records from student table:
SELECT * FROM `student`;

To retrieve some columns records from student table:


SELECT first_name,last_name FROM `student`;

To retrieve first and last name of student whose id is 3:


SELECT first_name,last_name FROM `student` WHERE `id`=3;
SQL: WHERE
 To limit the number of rows use the WHERE clause.
 The WHERE clause filters for rows that meet certain criteria.
 WHERE is followed by a condition that returns either true or false.
 WHERE is used with SELECT, UPDATE, and DELETE.

A WHERE clause with a SELECT, UPDATE and DELETE statements:


SELECT `ColumnNames` FROM `TableName` WHERE Condition;

UPDATE `TableName` SET `ColumnName`=Value WHERE Condition;

DELETE FROM `TableName` WHERE Condition;


SQL: WHERE
Examples:

SELECT * FROM `student` WHERE `first_name`='Ali';

UPDATE `student` SET `first_name`='Omar' WHERE `id`=2;

DELETE FROM `student` WHERE `first_name`='Ali';


SQL: LIKE
Like clause is used as condition in SQL query. Like clause compares data
with an expression using wildcard operators. It is used to find similar
data from the table.

Wildcard Operators
There are two wildcard operators that are used in like clause.
1. Percent sign (%) : represents zero, one or more than one character.
2. Underscore sign (_) : represents only one character.

SELECT ColumnNames FROM `TableName`


WHERE Condition LIKE Value;
SQL: LIKE
List all students with names that start with 'Abdul':
SELECT * FROM `student` WHERE `first_name` LIKE 'Abdul%';
List all students with names that ends with '%Farooq':
SELECT * FROM `student` WHERE `first_name` LIKE '%Farooq';
List all students with names that contains space between there names:
SELECT * FROM `student` WHERE `first_name` LIKE '% %';

List all students with names that contains 'b‘ as second character:
SELECT * FROM `student` WHERE `first_name` LIKE '_b%';
SQL: ORDER BY
Order by clause is used with Select statement for arranging retrieved
data in sorted order. The Order by clause by default sort data in
ascending order. To sort data in descending order DESC keyword is used
with Order by clause.

SELECT ColumnNames FROM `TableName`


WHERE Condition ORDER BY ColumnName;
SQL: ORDER BY
List all students by there first name in ascending order:
SELECT * FROM `student` ORDER BY `first_name` ASC;
List all students by there first name in descending order:
SELECT * FROM `student` ORDER BY `first_name` DESC;
List all students by there first name ascending order, and by there last
name descending order:
SELECT * FROM `student` ORDER BY `first_name` ASC,
`last_name` DESC;
SQL: Aggregate Functions
An aggregate function allows you to perform calculation on a set of
values to return a single scalar value. We often use aggregate functions
with the GROUP BY and HAVING clauses of the SELECT statement.

Name Description
MIN returns the smallest value in a given column
MAX returns the largest value in a given column
SUM returns the sum of the numeric values in a given column
AVG returns the average value of a given column
COUNT returns the total number of values in a given column
COUNT(*) returns the total number of rows in a table
Sample database table
Assume that we have table called employee as bellow.
SQL: MIN
SELECT MIN(`ColumnName`)
FROM `TableName`;

Find the lowest salary:


SELECT MIN(salary)
FROM employee;

Find the employees who has the lowest salary:


SELECT *
FROM employee
WHERE salary=(SELECT MIN(salary) FROM employee);
SQL: MAX
SELECT MAX(`ColumnName`)
FROM `TableName`;

Find the highest salary:


SELECT MAX(salary)
FROM employee;

Find the employees who has the highest salary:


SELECT *
FROM employee
WHERE salary=(SELECT MAX(salary) FROM employee);
SQL: AVG
SELECT AVG(`ColumnName`)
FROM `TableName`;

Find the average of salaries:


SELECT AVG(salary)
FROM employee;

Find the employees whose salaries are bellow average salary:


SELECT *
FROM employee
WHERE salary<(SELECT AVG(salary) FROM employee);
SQL: COUNT
SELECT COUNT(`ColumnName`)
FROM `TableName`;

Find the total number of employees:


SELECT COUNT(id)
FROM employee;

Find the number of employees whose last_name is not NULL:


SELECT COUNT(last_name)
FROM employee;
SQL: COUNT(*)
SELECT COUNT(*)
FROM `TableName`;

Find the total number of employees:


SELECT COUNT(*)
FROM employee;
SQL: Logical Operators
Logical operators are used to combine two or more conditions into a
compound condition.
SQL: Logical Operators
Name Description
AND Combines two expressions. The statement is true only
when both expressions are true. Ex:
WHERE (A=B) AND (C=D)
OR Combines two expressions. The statement is true when
either expression is true. Ex:
WHERE (A=B) OR (C=D)
NOT Reverses the value of an expression. It’s typically used in
conjunction with LIKE, BETWEEN clauses. Ex:
WHERE columnName NOT LIKE ‘ABC%‘
WHERE columnName NOT BETWEEN 90 AND 100
SQL: AND
The AND operator combines two expressions. The statement is true only
when both expressions are true.

AND
FALSE FALSE FALSE
FALSE TRUE FALSE
TRUE FALSE FALSE
TRUE TRUE TRUE
SQL: AND
SELECT *
FROM `TableName`
WHERE exp1 AND exp2 AND exp3 ... ;

Find the employees whose genders are male and ages are 20:
SELECT *
FROM employee
WHERE gender='m' AND age=20;

Find the female employees whose salaries are more than 10000:
SELECT *
FROM employee
WHERE gender='f' AND salary>10000;
SQL: OR
The OR operator combines two expressions. The statement is true when
either expression is true.

OR
FALSE FALSE FALSE
FALSE TRUE TRUE
TRUE FALSE TRUE
TRUE TRUE TRUE
SQL: OR
SELECT *
FROM `TableName`
WHERE exp1 OR exp2 OR exp3 ... ;

Find the employees whose ages are 20 or 25:


SELECT *
FROM employee
WHERE age=20 OR age=25;

Find the employees whose first names are start with 'a‘ or 's':
SELECT *
FROM employee
WHERE first_name LIKE 'a%' OR first_name LIKE 's%';
SQL: NOT
The NOT operator negates an expression. The statement is true when
expression is false or the statement is false when expression is true.

NOT
NOT FALSE TRUE
NOT TRUE FALSE
SQL: NOT
SELECT *
FROM `TableName`
WHERE NOT expression ... ;

Find the employees whose ages are not 20:


SELECT *
FROM employee
WHERE NOT age=20;

Find the employees whose genders are not male:


SELECT *
FROM employee
WHERE NOT gender='m';
SQL: LIKE
Checks to see whether an expression matches a specified pattern.
SQL: BETWEEN
Checks to see whether an expression is within a specified range.

You might also like