Chapter Six
Introduction to SQL
Prepared by:
Misganaw Abeje
University of Gondar
College Of Informatics
Department of computer science
Misganaw.Abeje13@gmail.com
Outline
What is sql
SQL Data Manipulation Language (DML)
SQL Data Definition Language (DDL)
Aggregate function
BY: MA
What is SQL?
SQL stands for Structured Query Language
SQL allows you to access a database
SQL can execute queries against a database
SQL is easy to learn
SQL is an ANSI (American National Standards Institute)
standard computer language for accessing and
manipulating database systems. SQL statements are
used to insert, retrieve and update data in a database
and, delete records from a database.
SQL works with database programs like MS Access,
BY: MA DB2, Informix, MS SQL Server, Oracle, Sybase, etc.
Types of SQL language
DDL: Data definition language eg, create, Drop..
DML: Data Manipulation Language, select,
delete, update. Insert into…
DCL: Data Control Language eg, Grant, Revoke
TCL: Transaction Control Language: Commit,
ROLLEBACK
SQL Data Manipulation Language
(DML)
SQL is a syntax for executing queries. But the SQL
language also includes a syntax to update, insert, and
delete records.
These query and update commands together form the
Data Manipulation Language (DML) part of SQL are:
– SELECT - extracts data from a database table
– UPDATE - updates data in a database table
– DELETE - deletes data from a database table
– INSERT INTO - inserts new data into a database table
BY: MA
SQL Data Definition Language (DDL)
DDL part of SQL permits database tables to be created or deleted.
We can also define indexes (keys), specify links between tables, and
impose constraints between database tables.
The most important DDL statements in SQL are:
– CREATE TABLE - creates a new database table
– ALTER TABLE - alters (changes) a database table
– DROP TABLE - deletes a database table
– CREATE DATABASE - creates a new database
– ALTER DATABASE- alters (changes) a database
– DROP DATABASE - deletes a database
– CREATE INDEX - creates an index (search key)
– DROP INDEX - deletes an index
BY: MA
Steps to open SQL
start All programs
Microsoft SQL server 2008
SQL server management
studio connecnew query
BY: MA
Creating database & tables in
SQL
Create a Database:To create a database:
– CREATE DATABASE database_name
– Eg create database FirstDatabase
Create a Table: to create a Table:
– CREATE TABLE table_name(column_name1
data_type,column_name2 data_type,.......)
– Eg: create table student(st_id int, st_name,
varchar(20), age int, sex varchar(10), dept
varchar(20));
BY: MA
Data Type Description
integer(size) Hold integers only. The maximum number of digits are specified in
int(size) parenthesis.
smallint(size)
tinyint(size)
decimal(size,dv) Hold numbers with fractions. The maximum number of digits are specified
numeric(size,d) in "size". The maximum number of digits to the right of the decimal is
specified in "d".
char(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis.
varchar(size) Holds a variable length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis.
date(yyyymmdd) Holds a date
BY: MA
INSERT
The INSERT INTO statement is used to insert new rows into
a table.
Syntax:
– INSERT INTO table_nameVALUES (value1, value2,...)
– Eg: INSERT INTO student VALUES(123, ‘henok’, 24, ‘m’, ‘land') ;
You can also specify the columns for which you want to
insert data.
SyntaxINSERT INTO table_name (column1,
column2,...)VALUES (value1, value2,....)
– Eg: INSERT INTO student( st_id, st_name, age, sex, dept)
values(01,’aman’, 23, ‘f’,‘comp’);
BY: MA –
SQL INSERT INTO Example
We have the following “EMPLOYEE" table:
Now we want to insert a new row in the “EMPLOYEE" table.
We use the following SQL statement:
INSERT INTO EMPLOYEE VALUES(‘Yonas’,’Melaku’,19,’X’,’E\2652/03’)
The “EMPLOYEE" table will now look like this:
BY: MA
Select
The query select is used to retrieve the data from the table or
database:
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
– SELECT column_name(s) FROM table_name
or
– SELECT * FROM table_name: which is used for retrieve all record
of the table
Keep in Mind That...
SQL is not case sensitive
BY: MA
… An SQL SELECT Example
Now we want to select the content of the columns named “FName"
and “LName" from the above table .
We use the following SELECT statement:
SELECT Fname,LName FROM EMPLOYEE
The result-set will look like this:
Now we want to select all the columns from the “EMPLOYEE" table.
We use the following SELECT statement:
SELECT * FROM EMPLOYEE
Tip: The asterisk (*) is a quick way of selecting all columns!
BY: MA
SQL WHERE Clause
The WHERE clause is used to specify a selection
criterion.
The WHERE Clause is conditionally select data from a
table, a WHERE clause can be added to the SELECT
statement.
Syntax
– SELECT column FROM table WHERE column operator value
– Eg: SELECT st_id, st_name, sex, dept from student where
st_id=01
– SELECT st_name, dept from student where sex=‘m’
BY: MA
With the WHERE clause, the following operators can be used: we
have used single quotes around the conditional values for text
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BY: MA BETWEEN Between an inclusive range
This is correct:
– SELECT * FROM student WHERE st_name ='Tove'
This is wrong:
– SELECT * FROM student WHERE st_name= aman
This is correct:
– SELECT * FROM student WHERE age>20
This is wrong:
– SELECT * FROM student WHERE age>‘20’
BY: MA
LIKE Condition
The LIKE condition is used to specify a search for a
pattern in a column.
Syntax
– SELECT column FROM table name WHERE column LIKE pattern
A "%" sign can be used to define wildcards (missing
letters in the pattern) both before and after the pattern.
Using LIKE
The following SQL statement will return student with first
names that start with an ‘A':
– SELECT * FROM student WHERE st_name LIKE ‘A%‘
BY: MA – ‘%A’ for end with A letters
some examples of like wildcards
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at
least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends
BY: MA with "o"
SQL UPDATE Statement
The UPDATE statement is used to modify the data in a
table.
Syntax
– UPDATE table_name SET column_name = new_value WHERE
column_name = some_value
Eg: UPDATE student SET age= 25 WHERE st_id= 01
Update several Columns in a Row
We want to change the address and add the name of the
city:
– UPDATE student SET year= ‘3rd year', age= 23 WHERE dept=
‘comp'
BY: MA
SQL DELETE Statement
The DELETE statement is used to delete rows in a table.
Remove existing rows from table by using the DELETE
statement.
Specific rows are deleted when you specify the WHERE
clause.
– Syntax: DELETE [from] table_name [WHERE condition];
– Eg: DELETE FROM student WHERE st_name= ‘henok‘
All rows in the table are deleted if you omit the WHERE
clause. Without delete table structre.
– syntax: FROM table_name
– Example: DELETE FROM student
BY: MA
SQL AND & OR operators
AND and OR join two or more conditions in a
WHERE clause.
The AND operator displays a row if ALL
conditions listed are true. The OR operator
displays a row if ANY of the conditions listed
are true.
BY: MA
Example
Use AND to display each student with the first name equal to
"Tove", and the last name equal to "Svendson":
Student table
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes
BY: MA
SELECT * FROM student WHERE
FirstName='Tove'AND LastName='Svendson'
LastName FirstName Address City
Svendson Tove Borgvn 23 Sandnes
Example|: Use OR to display each student with the first name equal to
"Tove", or the last name equal to "Svendson":
SELECT * FROM studentWHERE firstname='Tove' OR
lastname='Svendson'
BY: MA
SQL Drop Table and Database
Delete a Table or Database
• To delete a table (the table structure, attributes, and indexes
will also be deleted):
• To delete a database:
Eg:
DROP TABLE table_name
DROP DATABASE database_name
BY: MA
ALTER command in SQL
It used to change/alter a table using the ALTER TABLE
statement.
You can use ALTER TABLE to perform tasks such as:
– Add, modify, or drop a column
– Add or drop a constraint
– Enable or disable a constraint
Adding a Column
Use ADD clause to add column
ALTER TABLE table_name ADD (column datatype [CONSTRAINT
constraint_def DEFAULT default_exp] );
Eg: ALTER TABLE Student ADD (last_name VARCHAR2(15));
BY: MA
…cont.
Example Person table:
LastName FirstName Address
Pettersen Kari Storgt 20
Example: To add a column named "City" in the "Person" table:
ALTER TABLE Person ADD City varchar(30)
Result:
LastName FirstName Address City
Pettersen Kari Storgt 20
BY: MA
con…:
Modifying a Column
– Change the size of a column
– Change the precision of a numeric column
– Change the data type of a column
– Change the default value of a column
– Affects only subsequent insertion to the table
Syntax:
ALTER TABLE table_name MODIFY (column new(data type) );
Eg: ALTER TABLE Student MODIFY (first_name VARCHAR2(15));
ALTER TABLE Student MODIFY (major CHAR(3) );
BY: MA
…cont.
Add a primary key constraint
ALTER TABLE Classes ADD CONSTRAINT cls_pk
PRIMARY KEY (dep,course);
ALTER TABLE student ADD CONSTRAINT st_pk
PRIMARY KEY (stId);
Add a foreign key constraint
ALTER TABLE personal_info ADD CONSTRAINT
personal_info_fkey FOREIGN KEY (employee_id)
REFERENCES employees (employee_id) ON DELETE
CASCADE;
BY: MA
….cont
Dropping a Column: Use DROP COLUMN clause to
drop columns you no longer need from the table
The column may or may not contain data. Only one
column can be dropped at a time
The table must have at least one column remaining in it
after it is altered.
Syntax:
ALTER TABLE table_name DROP COLUMN name;
Example:
ALTER TABLE student DROP COLUMN f_name;
BY: MA
…cont
Adding a CHECK Constraint
Example:
– ALTER TABLE Student ADD CONSTRAINT student_major
CHECK ( major IN („CSC‟,‟HIS‟,‟ECN‟,‟MUS‟,NUT‟));
– ALTER TABLE Student ADD CONSTRAINT student_credits
CHECK (current_credits > 0);
Dropping a Constraint
Syntax:
ALTER TABLE table_name DROP CONSTRAINT constraint;
Example:
BY: MA ALTER TABLE student DROP CONSTRAINT std_major;
SQL ORDER BY , ASCENDING
and DESCENDING
The ORDER BY keyword is used to sort the rows.
SELECT column name(s)FROM table name
ORDER BY column name(s)
When we want to order the values of the result in
ascending or descending order we use the following
syntax
SELECT column name(s)FROM table name
ORDER BY column DESC, column ASC
Note : DESC and ASC are key words for descending
and ascending respectively.
BY: MA
Example SQL ORDER BY
Orders table:
To display the companies in alphabetical order:
– SELECT Company, OrderNumber FROM Orders ORDER BY Company
Company OrderNumber
– result order table: ABC Shop 5678
Sega 3412
BY: MA W3Schools 6798
To display the companies in reverse alphabetical order:
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC
Company OrderNumber
W3Schools 6798
W3Schools 2312
Sega 3412
ABC Shop 5678
BY: MA
Questions
Create a database called finance that consists payroll table. The payroll table looks
like this, after you create the database and the table (2 pt) answer the following
questions.
A.Extract an employee salary lessthan than 2000 (2 pt)
B.Update the sex and dept of sara haile (sex is F and dept is PERSONNEL) (2 pt)
C.Extract the empid and dept whose empname starts with ‘A’ (2 pt)
BY: MA
D.Delete the second row from the table (2 pt)
Aggregate Function in SQL
SQL allows grouping of resulting rows in a query so that
aggregate functions can be applied to make analysis and
summary.
The aggregate functions supported by the SQL statement
are:
– Summation: SUM (<column_name>)
– Average: AVG (<column_name>)
– Minimum: MIN (<column_name>)
– Maximum: MAX (<column_name>)
– Count: COUNT (<column_name> | *)
BY: MA
MaX and MIN
The MIN() function returns the smallest value of the
selected column.
– SELECT MIN(column_name) FROM table_name WHERE condition;
The MAX() function returns the largest value of the
selected column.
– SELECT MAX(column_name) FROM table_name WHERE condition;
– Eg
– SELECT MIN(sallery) AS SmallestSallery FROM lecture;
– SELECT MAX(sallery) AS HighestSallery FROM lecture;
BY: MA
Count() ,AVG() & SUM()
The COUNT() function returns the number of rows that
matches a specified criterion. Syntax:
– SELECT COUNT(column_name) FROM table_name WHERE condition;
– SELECT COUNT(leId) FROM lecture WHERE dept=‘computer’;
The AVG() function returns the average value of a numeric
column. AVG() Syntax
– SELECT AVG(column_name) FROM table_name WHERE condition;
– SELECT AVG(sallery) FROM lecture ;
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
– SELECT SUM(column_name) FROM table_name WHERE condition;
– SELECT SUM(sallery) FROM lecture WHERE L_Rank=‘Lecturer’;
BY: MA
Exercise
Create database class schedule
Create table student
– Attributes (stid,stFname,Lname,brthdate, phoneno )
Create table course
– Attributes (cocode, coname, CRHR)
Create table room
Attributes (Roomno, Nochair, Buldingno)
Create table instructor.
– Attributes (InsId, InFname,Lname, age, phoneno, Department, salary )
Create the relational table scheddule
– Between course and instructor
BY: MA
– Between Course and student
Design such type schedule Database
BY: MA
Thank you
BY: MA