Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

FDB Lecture05

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

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: DISTINCT
In SQL, the DISTINCT keyword is used in the SELECT statement to retrieve
unique values from a database table. Any value that has a duplicate will
only show up once.

SELECT DISTINCT `column1`,`column2`,... FROM `TableName`;

To retrieve student first names uniquely:


SELECT DISTINCT first_name FROM `student`;

To retrieve student first names and last names uniquely:


SELECT DISTINCT first_name,last_name FROM `student`;
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: IN
The IN operator in SQL filters the result set based on a list of discrete
values. The list of discrete values can be simply be listed out or is
provided by a separate SELECT statement (this is called a subquery). The
IN operator is always used with the WHERE clause.

SELECT column1,column2,... FROM TableName


WHERE columnX IN (value1, value2, ...);

To retrieve all info of students whose ids are 2, 5 and 9:


SELECT * FROM student
WHERE id IN (2, 5, 9);

To retrieve all info of students whose cities are Jawzjan and Faryab:
SELECT * FROM student
WHERE city IN ('Jawzjan', 'Faryab');
SQL: BETWEEN
The BETWEEN operator is used when the filtering criteria is a continuous
range with a maximum value and a minimum value. It is always used in
the WHERE clause.

SELECT column1,column2,... FROM TableName


WHERE columnX BETWEEN minValue AND maxValue;

To retrieve all info of students whose ages are between 20 and 25:
SELECT * FROM student
WHERE age BETWEEN 20 AND 25;

To retrieve all info of students whose dates of birth are bertween:


SELECT first_name,last_name FROM student
WHERE dob BETWEEN '2015-01-01' AND '2019-12-31';
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: 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: Alias
Alias refers to the practice of using a different temporary name to a
database table or a column in a table.
The main advantage of using an alias is to help make the SQL statement
more concise and readable. In addition, the output of the SQL statement
can become more understandable with the use of an alias.

SELECT ColumnName1 "Column1Alias", ColumnName2 "Column2Alias", ...


FROM TableName "TableAlias";

SELECT CONCAT(e.first_name, " ", e.last_name) "full_name"


FROM employee e;
SQL: AS
The keyword AS is used to assign an alias to the column or a table. It is
inserted between the column name and the column alias or between the
table name and the table alias.

SELECT ColumnName1 AS "Column1Alias", ColumnName2 AS "Column2Alias", ...


FROM TableName AS "TableAlias";

SELECT CONCAT(e.first_name, " ", e.last_name) AS "full_name"


FROM employee AS e;
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) AS min_salary
FROM employee;

Find the lowest salary in Afghani:


SELECT first_name, MIN(salary/75) AS min_salary_af
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) AS max_salary
FROM employee;

Find the employees who has the highest salary:


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

Find the sum of employees salary:


SELECT SUM(salary) AS total_salary
FROM employee;

Find the employees whose salaries are bellow average salary:


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

Find the average of employees salary:


SELECT AVG(salary) AS 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) AS employee_count
FROM employee;

Find the number of employees whose last_name is not NULL:


SELECT COUNT(last_name) AS last_name_count
FROM employee;

Find the number of employee names uniquely:


SELECT COUNT(DISTINCT(first_name)) AS first_name_count
FROM employee;
SQL: COUNT(*)
SELECT COUNT(*)
FROM TableName;

Find the total number of employees:


SELECT COUNT(*) AS employee_count
FROM employee;
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 [ASC,DESC];
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: ORDER BY
In addition to column name, we may also use column position (based on
the SQL query) to indicate which column we want to apply the ORDER BY
clause. The first column is 1, second column is 2, and so on.
List all students by there first name in descending order:
SELECT * FROM student
ORDER BY 2 DESC;

List all students by there first name ascending order, and by there last
name descending order:
SELECT * FROM student
ORDER BY 2 ASC, 3 DESC;
SQL: ORDER BY
It is also possible to sort the result by an expression. For example, in the
following product table,

id unit_price quantity
1 10 9
2 15 4
3 25 3
4 20 6

SELECT id, unit_price * quantity AS revenue


FROM product
ORDER BY unit_price * quantity DESC;
SQL: GROUP BY
The GROUP BY clause is used to tell SQL what level of granularity the
aggregate function should be calculated in. The level of granularity is
represented by the columns in the SELECT statement that are not
aggregate functions.

SELECT ColumnNames, Function(ColumnName)


FROM TableName
GROUP BY ColumnNames;
SQL: GROUP BY
List the number of male and female students:
SELECT gender,COUNT(*) AS total_count
FROM student
GROUP BY gender;

List the sum of salaries according to gender:


SELECT gender,SUM(salary) AS total_salary
FROM student
GROUP BY gender;

List count of genders according to each city:


SELECT city,gender,COUNT(*) AS total_count
FROM student
GROUP BY city,gender;
SQL: HAVING
The HAVING clause is used to filter the result set based on the result of
an aggregate function. It is typically located near or at the end of the
SQL statement.
HAVING is often coupled with the presence of the GROUP BY clause,
although it is possible to have a HAVING clause without the GROUP BY
clause.

SELECT ColumnNames, Function(ColumnName)


FROM TableName
GROUP BY ColumnNames
HAVING condition;

You might also like