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

Lecture 8 SQL

SQL is a database language used for managing and retrieving data in relational databases, with commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Transaction Control Language (TCL), and Data Control Language (DCL). Key commands include CREATE, ALTER, DROP for DDL; SELECT, INSERT, UPDATE, DELETE for DML; and operators like AND, OR, NOT for filtering data. The document provides syntax and examples for various SQL commands and their applications in database management.

Uploaded by

tinasherufudza18
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture 8 SQL

SQL is a database language used for managing and retrieving data in relational databases, with commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Transaction Control Language (TCL), and Data Control Language (DCL). Key commands include CREATE, ALTER, DROP for DDL; SELECT, INSERT, UPDATE, DELETE for DML; and operators like AND, OR, NOT for filtering data. The document provides syntax and examples for various SQL commands and their applications in database management.

Uploaded by

tinasherufudza18
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 61

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

CREATE TABLE table_name


(column_name1 datatype (size),
column_name2 datatype(size),
... column_nameN datatype(size)

);

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)

DESC means in descending order or ASC in


Ascending order
03/08/25
ALTER
• The SQL ALTER TABLE command is used to
modify the definition (structure) of a table by
modifying the definition of its columns. The
ALTER command is used to perform the
following functions.
• 1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints

03/08/25
Adding a column
Syntax:
ALTER TABLE table_name ADD
column_name datatype;

Example: To add a column "experience" to the


employee table
ALTER TABLE employee ADD experience
int(3);
03/08/25
Removing a column
Syntax:
ALTER TABLE table_name DROP column_name;

Example: To drop the column "location" from


the employee table
ALTER TABLE employee DROP location;

03/08/25
Modifying a column
Syntax:
ALTER TABLE table_name MODIFY
column_name datatype;

Example: To modify the column salary in the


employee table
ALTER TABLE employee MODIFY salary
number(15,2);
03/08/25
RENAME
• The SQL RENAME command is used to change
the name of the table or a database object.
• If you change the object's name any reference
to the old name will be affected.
• You have to manually change the old name to
the new name in every reference.

03/08/25
Syntax:
RENAME old_table_name To
new_table_name;

Example: To change the name of the table


employee to my_employee

RENAME employee TO my_employee;

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];

SELECT * FROM table-name


* Means all – all columns of the table

03/08/25
Example
id first_name last_name age subject sport

100 Mary Moyo 10 Science Cricket

101 Tom Dube 12 Maths Football

102 Stephen Dongo 09 Science Cricket

103 Lucas Shoko 18 Maths Badminton

104 Ashwin Masuku 15 Economics Chess

03/08/25
• Using the table in the previous slide:
– SELECT first_name FROM
student_details;

– SELECT first_name, last_name FROM


student_details;

– SELECT * 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

<>, != is not equal to

< less than

> greater than

>= greater than or equal to

<= less than or 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

For the row to be selected at least one of the


OR
conditions must be true.

For a row to be selected all the specified conditions


AND
must be true.

For a row to be selected the specified condition must


NOT
be false.

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

Syntax of WHERE clause with Select statement:

SELECT column_list FROM table-name


WHERE condition;

•column or expression - Is the column of a table or a


expression
•comparison-operator - operators like = < > etc.
•value - Any user value or a column name for
comparison
03/08/25
Example
Find the name of a student with id 100.
SELECT first_name, last_name FROM
student_details
WHERE id = 100;

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

% A substitute for zero or more characters

_ A substitute for a single character

[charlist] Sets and ranges of characters to match

[^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'

SELECT first_name, last_name


FROM student_details
WHERE first_name LIKE 'S%';

03/08/25
Example
• to display all the names with 'a' as the second
character:

SELECT first_name, last_name


FROM student_details
WHERE first_name LIKE '_a%';

03/08/25
What will these output?
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE ‘%es%';

SELECT first_name, last_name


FROM student_details
WHERE first_name LIKE ‘B_z_l’;

03/08/25
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE ‘[abc]%'

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];

Example: To insert a row into the employee table


from a temporary table, the sql insert query would
be like,
INSERT INTO employee (id, name, dept, age,
salary location) SELECT emp_id, emp_name,
dept, age, salary, location
FROM temp_employee;
03/08/25
SQL UPDATE
• The UPDATE Statement is used to modify the
existing rows in a table.
Syntax for SQL UPDATE Command is:
UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[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;

Example 2:To change the salaries of all the employees,


the query would be,
UPDATE employee
SET salary = salary + (salary * 0.2);
03/08/25
SQL DELETE
• The DELETE Statement is used to delete
rows from a table.
Syntax:
DELETE FROM table_name [WHERE
condition];
• The WHERE clause in the delete command is
optional and it identifies the rows in the
column that gets deleted.
• If the WHERE clause is not included, all the
rows in the table are deleted.
03/08/25
Example
• To delete an employee with id 100 from the
employee table, the sql delete query is as
follows:
DELETE FROM employee WHERE id = 100;
• To delete all the rows from the employee
table, the query:
DELETE FROM employee;

03/08/25

You might also like