Lecture 8 SQL
Lecture 8 SQL
Lecture 7
SQL
• SQL is a database computer language
designed for the retrieval and management of
data in relational databases.
• designed to organise and simplify the process
of getting information out of a database in a
usable form and to reorganise data within
databases.
03/08/25
SQL Commands
• SQL commands are instructions used to
communicate with the database to perform
specific tasks on the data.
• These tasks include searching for specific data,
creating databases and tables, adding data to
tables, modifying data, dropping tables,
setting permissions for users, e.t.c.
03/08/25
SQL Categories
• SQL commands are grouped into four major
categories depending on their functionality :
1.Data Definition Language (DDL) - These SQL
commands are used for creating, modifying, and
dropping the structure of database objects. The
commands are CREATE, ALTER, DROP, RENAME,
and TRUNCATE.
2.Data Manipulation Language (DML) - These SQL
commands are used for storing, retrieving,
modifying, and deleting data. These commands
are SELECT, INSERT, UPDATE, and DELETE.
03/08/25
3. Transaction Control Language (TCL) -
These SQL commands are used for
managing changes affecting the data.
These commands are COMMIT,
ROLLBACK, and SAVEPOINT.
4. Data Control Language (DCL) - These
SQL commands are used for providing
security to database objects. These
commands are GRANT and REVOKE.
03/08/25
Data Definition
Statements
03/08/25
CREATE
• CREATE DATABASE: Creates a new database
• CREATE TABLE: Creates a new database table
• CREATE INDEX: Creates a search key
03/08/25
CREATE DATABASE
Syntax:
CREATE DATABASE DatabaseName
Example:
CREATE DATABASE Nust
03/08/25
CREATE TABLE
• The CREATE TABLE Statement is used to
create tables to store data.
• Integrity Constraints like primary key, unique
key, foreign key can be defined for the
columns while creating the table.
03/08/25
CREATE TABLE SYNTAX
);
03/08/25
CREATE TABLE EXAMPLE
CREATE TABLE employee
( id int(5),
name varchar(20),
dept varchar(10),
age int(2),
salary double(10),
location varchar(10)
);
03/08/25
SQL Integrity Constraints
• Integrity Constraints are used to apply
business rules to the database tables.
• The constraints available in SQL are Foreign
Key, Not Null, Unique, Check.
• Constraints can be defined in two ways
1) The constraints can be specified
immediately after the column definition. This
is called column-level definition.
2) The constraints can be specified after all
the columns are defined. This is called table-
level definition.
03/08/25
CREATE TABLE EXAMPLE 2
CREATE TABLE Students(
Student# varchar(9) primary key not null,
Surname varchar(40) not null,
Firstname varchar(30) not null.
DateOfBirth Date(yyyymmdd) not null,
Gender enum(“Female”, “Male”) not null,
Age int(3) );
03/08/25
Explanation of example 2
• Varchar (size) holds a variable length string with a
maximum size and can contain letters, numbers
and special characters
• Int(size) holds integers only with a maximum
number of digits
• Decimal(size, d) holds numbers with fractions, d
is the digits after the comma
• Date(yyyymmdd) holds a date
• Enum() holds a list to choose from
03/08/25
CREATE INDEX
• Created on an existing table to locate rows more
quickly and efficiently.
Syntax:
CREATE INDEX Indexname
ON TABLENAME(columnname)
Example:
CREATE INDEX studentIndex
ON Students(Surname DESC)
03/08/25
Adding a column
Syntax:
ALTER TABLE table_name ADD
column_name datatype;
03/08/25
Modifying a column
Syntax:
ALTER TABLE table_name MODIFY
column_name datatype;
03/08/25
Syntax:
RENAME old_table_name To
new_table_name;
03/08/25
DROP
• The SQL DROP command is used to remove an
object from the database.
• If you drop a table, all the rows in the table is
deleted and the table structure is removed
from the database.
• Once a table is dropped we cannot get it back.
• When a table is dropped all the references to
the table will not be valid.
03/08/25
DROP
• DROP DATABASE: Deletes a database
• DROP TABLE: Deletes a database table
• DROP INDEX: Deletes a search key
03/08/25
Deleting a database
Syntax:
DROP Database_Name
Example:
DROP NUST
03/08/25
Deleting a Table
Syntax:
DROP TABLE Tablename
Example:
DROP TABLE Students
03/08/25
Deleting an Index
Syntax:
DROP INDEX Indexname
ON TABLENAME
Example:
DROP INDEX StudentIndex
ON Students
03/08/25
Data
Manipulation
Language
Statements
DML
03/08/25
DML Statements
– SELECT extracts data from a database table
– UPDATE Modifies data in a database table
– DELETE Removes data from a database table
– INSERT Adds new data into a database table
03/08/25
SELECT
• The most commonly used SQL command is
SELECT statement.
• It is used to query or retrieve data from a
table in the database.
• A query may retrieve information from
specified columns or from all of the columns
in the table.
03/08/25
Select Syntax
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
03/08/25
Example
id first_name last_name age subject sport
03/08/25
• Using the table in the previous slide:
– SELECT first_name FROM
student_details;
03/08/25
Using expressions in SQL SELECT
Statement
• If we want to display the first and last name of
an employee combined together, the SQL
Select Statement would be like :
SELECT first_name + ' ' + last_name FROM
employee;
03/08/25
SQL Operators
• There are two type of Operators, namely
Comparison Operators and Logical Operators.
• These operators are used mainly in the
WHERE clause and the HAVING clause to filter
the data to be selected.
03/08/25
Comparison Operators
• Comparison operators are used to compare
the column data with specific values in a
condition.
• Comparison Operators are also used along
with the SELECT statement to filter data based
on specific conditions.
03/08/25
Comparison Operators Description
= equal to
03/08/25
Logical Operators
• There are three Logical Operators namely,
AND, OR, and NOT.
• These operators compare two conditions at a
time to determine whether a row can be
selected for the output.
• When retrieving data using a SELECT
statement, you can use logical operators in
the WHERE clause, which allows you to
combine more than one condition.
03/08/25
Logical
Description
Operators
03/08/25
OR Example
• If you want to select rows that satisfy at least
one of the given conditions, you can use the
logical operator, OR.
For example: if you want to find the names of
students who are studying either Maths or
Science, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
WHERE subject = 'Maths' OR subject =
'Science'
03/08/25
AND Example
• If you want to select rows that must satisfy all
the given conditions, you can use the logical
operator, AND.
For Example: To find the names of the students
between the age 10 to 15 years, the query
would be like:
SELECT first_name, last_name, age
FROM student_details
WHERE age >= 10 AND age <= 15;
03/08/25
NOT Example
• If you want to find rows that do not satisfy a
condition, you can use the logical operator, NOT.
NOT results in the reverse of a condition. That is,
if a condition is satisfied, then the row is not
returned.
For example: If you want to find out the names of
the students who do not play football, the query
would be like:
SELECT first_name, last_name, games
FROM student_details
WHERE NOT games = 'Football'
03/08/25
WHERE Clause
• The WHERE Clause is used when you want to
retrieve specific information from a table
excluding other irrelevant data.
• The condition you provide in the WHERE
clause filters the rows retrieved from the table
and gives you only those rows which you
expected to see.
• The WHERE clause can be used along with
SELECT, DELETE, UPDATE statements.
03/08/25
Syntax of WHERE clause:
WHERE {column or expression}
comparison-operator value
03/08/25
Using expressions in the WHERE
Clause
• Lets consider the employee table. If you want
to display employee name, current salary, and
a 20% increase in the salary for only those
products where the percentage increase in
salary is greater than 30000, the SELECT
statement can be written as shown below
SELECT name, salary, salary*1.2 AS
new_salary FROM employee
WHERE salary*1.2 > 30000;
03/08/25
SQL LIKE
• The LIKE operator is used to list all rows in a
table whose column values match a specified
pattern.
• It is useful when you want to search rows to
match a specific pattern, or when you do not
know the entire value.
• For this wildcard characters are used.
03/08/25
Wildcards
• In SQL, wildcard characters are used with the
SQL LIKE operator.
• SQL wildcards are used to search for data
within a table.
Wildcard Description
[^charlist]
or Matches only a character NOT specified within the brackets
[!charlist]
03/08/25
Example
• For example: To select all the students whose
name begins with 'S'
03/08/25
Example
• to display all the names with 'a' as the second
character:
03/08/25
What will these output?
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE ‘%es%';
03/08/25
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE ‘[abc]%'
03/08/25
SQL BETWEEN ….AND
• The operator BETWEEN and AND, are used to
compare data for a range of values.
• to find the names of the students between
age 10 to 15 years we query:
SELECT first_name, last_name, age
FROM student_details
WHERE age BETWEEN 10 AND 15;
03/08/25
SQL GROUP BY
• The SQL GROUP BY Clause is used to retrieve
data grouped according to one or more
columns.
• For Example: If you want to know the total
amount of salary spent on each department,
the query would be:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;
03/08/25
SQL INSERT
• The INSERT Statement is used to add new
rows of data to a table.
• We can insert data to a table in two ways,
1) Inserting the data directly to a table.
2)Inserting the data through a select
statement
03/08/25
Inserting the data directly to a table.
Syntax:
INSERT INTO TABLE_NAME
[ (col1, col2, col3,...colN)]
VALUES (value1, value2, value3,...valueN);
Example:
INSERT INTO employee (id, name, dept,
salary location) VALUES (105, ‘James',
'Aeronautics', 33000);
03/08/25
• if you are adding value for all the columns of
the table you need not specify the column(s)
name in the sql query. But you need to make
sure the order of the values is in the same
order as the columns in the table.
• The sql insert query will be as follows
INSERT INTO TABLE_NAME
VALUES (value1, value2,
value3,...valueN);
Example:
INSERT INTO employee
VALUES (105, ‘James', 'Aeronautics', 27,
33000);
03/08/25
Inserting the data through a
select statement
Syntax:
INSERT INTO table_name
[(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM table_name [WHERE condition];
03/08/25
Example
• In the Update statement, WHERE clause identifies the
rows that get affected. If you do not include the
WHERE clause, column values for all the rows get
affected.
Example 1: To update the location of an employee, the
sql update query would be:
UPDATE employee
SET location ='Mbalabala'
WHERE id = 101;
03/08/25