Structured Query Language
(SQL)
Structured Query Languages (SQL)
SQL (Structured Query Language) is a language to operate
databases;
it includes Database Creation, Database Deletion, Fetching Data
Rows, Modifying & Deleting Data rows, etc.
SQL stands for Structured Query Language which is a
computer language for storing, manipulating and retrieving data
stored in a relational database.
SQL was developed in the 1970s by IBM Computer Scientists
and became a standard of the American National Standards
Institute (ANSI) in 1986, and the International Organization for
2
Standardization (ISO) in 1987.
Why Structured Query Languages (SQL) ?
SQL is widely popular because it offers the following advantages −
• Allows users to access data in the relational database management
systems.
• Allows users to describe the data.
• Allows users to define the data in a database and manipulate that data.
• Allows to embed within other languages using SQL modules, libraries &
pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in a database.
• Allows users to set permissions on tables, procedures and views. 3
SQL Language (DDL, DML, TCL and DCL)
1. DDL – Data Definition Language
DDL actually consists of the SQL commands that can be used to
define the database schema.
It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in
the database.
DDL is a set of SQL commands used to create, modify, and
delete database structures but not data.
4
SQL Language (DDL, DML, TCL and DCL)
List of DDL commands:
• CREATE: This command is used to create the database or its
objects (like table, index, function, views, store procedure, and
triggers).
• DROP: This command is used to delete objects from the
database.
• ALTER: This is used to alter the structure of the database.
• TRUNCATE: This is used to remove all records from a table,
including all spaces allocated for the records are removed.
• RENAME: This is used to rename an object existing in the
database. 5
SQL Language (DDL, DML, TCL and DCL)
DML - Data Manipulation Language
It is used to retrieve, store, modify, delete, insert and update
data in database.
The SQL commands that deal with the manipulation of data
present in the database belong to DML or Data Manipulation
Language and this includes most of the SQL statements.
It is the component of the SQL statement that controls access
6
to data and to the database.
SQL Language (DDL, DML, TCL and DCL)
List of DML commands:
▪ INSERT: It is used to insert data into a table.
▪ UPDATE: It is used to update existing data within a table.
▪ DELETE: It is used to delete records from a database table.
▪ SELECT - extracts data from a database table
7
SQL Language (DDL, DML, TCL and DCL)
DCL – Data Control Language
DCL includes commands such as GRANT and REVOKE which
mainly deal with the rights, permissions, and other controls of
the database system.
List of DCL commands:
GRANT: This command gives users access privileges to the
database.
REVOKE: This command withdraws the user’s access
privileges given by using the GRANT command. 8
SQL Language (DDL, DML, TCL and DCL)
TCL – Transaction Control Language
It is used to manage different transactions occurring within a
database.
BEGIN: Opens a Transaction.
COMMIT: Commits a Transaction.
ROLLBACK: Rollbacks a transaction in case of any error
occurs.
SAVEPOINT: Sets a save point within a transaction. 9
SQL Data Types
An SQL data type refers to the type of data which can be stored
in a column of a database table. For example integer data,
character data, monetary data, date and time data, binary
strings, and so on.
While creating a database table in a database, we need to
specify following two attributes to define a table column:
• Name of the column
• Data type of the column 10
SQL Data Types cont’d…
SQL data types can be broadly divided into the following
categories.
1. Numeric data types such as: INT, TINYINT, BIGINT, FLOAT,
REAL, etc.
2. Date and Time data types such as: DATE, TIME, DATETIME,
etc.
3. Character and String data types such as: CHAR, VARCHAR,
TEXT, etc.
4. Unicode character string data types such as: NCHAR,
NVARCHAR, NTEXT, etc.
5. Binary data types such as: BINARY, VARBINARY, etc.
6. Miscellaneous data types - CLOB, BLOB, XML, CURSOR, 11
TABLE, etc.
SQL Constraint
SQL - Constraint
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data
action, the action is aborted.
Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints apply to
13
the whole table.
SQL - Constraint
❑ Constraints are the rules that we can apply on the type of data in a
table. That is, we can specify the limit on the type of data that can
be stored in a particular column in a table using constraints.
❑ The following constraints are commonly used in SQL:
o NOT NULL - Ensures that a column cannot have a NULL value
o UNIQUE - Ensures that all values in a column are different
14
SQL – Constraint Cont’d....
o PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
o FOREIGN KEY - Prevents actions that would destroy links between
tables
o CHECK - Ensures that the values in a column satisfies a specific
condition
o DEFAULT - Sets a default value for a column if no value is specified
o CREATE INDEX - Used to create and retrieve data from the database
very quickly. 15
SQL – NOT NULL Constraint
o NOT NULL - If we specify a field in a table to be NOT NULL. Then
the field will never accept null value. That is, you will be not
allowed to insert a new row in the table without specifying any
value to this field.
o For example, the below query creates a table Student with the
fields ID and NAME as NOT NULL. That is, we are bound to specify
values for these two fields every time we wish to insert a new
row.
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20) 16
);
SQL – UNIQUE Constraint
o UNIQUE - This constraint helps to uniquely identify each row in the
table. i.e. for a particular column, all the rows should have
unique values. We can have more than one UNIQUE columns in
a table.
o For example, the below query creates a table Student where the
field ID is specified as UNIQUE. i.e, no two students can have the
same ID.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10) ,
ADDRESS varchar(20) 17
);
SQL – PRIMAREY KEY Constraint
o PRIMARY KEY - is a field which uniquely identifies each row in the
table. If a field in a table as primary key, then the field will not be able
to contain NULL values as well as all the rows should have unique
values for this field. So, in other words we can say that this is
combination of NOT NULL and UNIQUE constraints.
o A table can have only one field as primary key. Below query will create
a table named Student and specifies the field ID as primary key.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10) ,
ADDRESS varchar(20),
primary key(ID) 18
);
SQL – FOREIGN KEY Constraint
o FOREIGN KEY - is a field in a table which uniquely identifies each
row of a another table. That is, this field points to primary key of
another table. This usually creates a kind of link between the
tables.
o Consider the two tables as shown below:
Orders Customers
ORDER_N C_ID NAME ADDRESS
O_ID C_ID
O 1 RAMESH DELHI
1 2253 3 2 SURESH NOIDA
2 3325 3 3 DHARMESH GURGAON
3 4521 2 19
4 8532 1
SQL – FOREIGN KEY Constraint Cont’d....
o As we can see clearly that the field C_ID in Orders table is the
primary key in Customers table, i.e. it uniquely identifies each row
in the Customers table. Therefore, it is a Foreign Key in Orders
table.
Syntax:
CREATE TABLE Orders
(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int, PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
); 20
SQL - CHECK Constraint
o The CHECK Constraint enables a condition to check the value being
entered into a record. If the condition evaluates to false, the record
violates the constraint and isn't entered the table.
CREATE TABLE table_name (
column1 datatype(size),
column datatype(size) constraint constraintName CHECK
Check(columnName condition value), …,
column datatype (size)
); 21
SQL - CHECK Constraint Cont’d….
Example 1
For example, the following program creates a new table called CUSTOMERS and
adds five columns. Here, we add a CHECK with AGE column, so that you cannot
have any CUSTOMER who is below 18 years.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
22
PRIMARY KEY (ID) );
SQL - CHECK Constraint Cont’d….
Following is the syntax to specify the check constraint on column.
Syntax
REATE TABLE table_name (
column1 datatype(size),
column datatype(size) constraint constraintName CHECK Check(columnName
condition value), …,
column datatype (size)
23
);
SQL - CHECK Constraint Cont’d….
Example
create table customer
(
CID varchar(15) primary key,
CName varchar(15) not null,
Age int constraint C1 check(Age>=18),
Salary decimal(5,2)
); 24
SQL - CHECK Constraint Cont’d….
To drop a CHECK constraint, use the following SQL syntax.
ALTER TABLE Table_Name DROP CONSTRAINT Constraint_Name;
Example
ALTER TABLE CUSTOMER
DROP CONSTRAINT c1;
25
SQL - Default Constraint
The DEFAULT constraint provides a default value to a column when the
INSERT INTO statement does not provide a specific value.
Example
For example, the following SQL creates a new table called CUSTOMERS
and adds five columns. Here, the SALARY column is set to 5000.00 by
default, so in case the INSERT INTO statement does not provide a value
for this column, then by default this column would be set to 5000.00. 26
SQL - Default Constraint Cont’d….
create table customer
(
CID varchar(15) primary key,
CName varchar(15) not null,
Address varchar(16) Default 'Hawassa',
Age int constraint c1 check(Age>=18),
Salary decimal(18,5) Default 5000.00
27
);
Basic DDL Commands in SQL
CREATE: to define new tables (to define relation schemas)
DROP: to delete table definitions (to delete relation schemas)
ALTER: to change the definitions of existing tables (to change relation
schema)
28
DDL-Creating a Database
The SQL CREATE DATABASE statement is used to create a new
SQL database.
To initialize a new database:
Syntax:
CREATE DATABASE DatabaseName;
Example:
create DATABASE DB; 29
DDL- Drop a Database
The SQL DROP DATABASE statement is used to drop an existing
database in SQL schema.
Syntax:
Drop DATABASE DatabaseName;
Example:
Drop DATABASE DB;
30
DDL- Use a Database
When you have multiple databases in your SQL schema before
starting your operation, you need to select the database where all
the operations will be performed.
The SQL USE DATABASE statement is used to select any existing
database in the SQL schema.
Syntax:
use DatabaseName;
Example:
31
use DB;
DDL- Show a Database
This statement returns the output containing the
names of the databases, their IDs, and the dates
on which they were created. It should be noted that
this command will display all databases that are
system and user-defined databases both.
Syntax:
Select * from sys.databases; 32
DDL-Creating a Table
Syntax o Example
create table student
CREATE TABLE table_name (
SID varchar(23),
(Column_name datatype[(size)], Fname varchar(17),
Mname varchar(15),
Column_name datatype[(size)] Lname varchar(14),
D_Birth date,
) Age int,
Grade float
33
);
DDL-Drop table
o The DROP TABLE command is used to delete/drop the targeted table
permanently. Therefore, once a table is dropped using the DROP TABLE
command, it cannot be retrieved.
o The basic syntax of the DROP TABLE command will be as follows:
o DROP TABLE tblname;
o DROP TABLE Student
34
DDL-Alter table
o ALTER TABLE statement is used to add, modify, or drop/delete columns
in a table. ALTER TABLE statement is also used to rename a table.
1. Add column in table
Syntax
o ALTER TABLE table_name ADD new_column_name column_definition;
o table_name
o The name of the table to modify.
o new_column_name
o The name of the new column to add to the table.
o column_definition 35
o The datatype of the column.
DDL-Alter table
2. Modify column in table
Syntax
ALTER TABLE table_name ALTER COLUMN column_name TYPE
column_definition;
3.Drop column in table
Syntax
36
ALTER TABLE table_name DROP COLUMN column_name;
DDL-Truncate table
Remove all records from a table, including all spaces allocated for
the records are removed.
Syntax:
TRUNCATE TABLE Table_Name;
37
DDL-Rename table
SQL Server provides a standard stored procedure called SP_RENAME
for renaming the user-created object in the current database. The
user-created object can be a table or column.
Syntax:
EXEC sp_rename 'old_table_name', 'new_table_name’
Example:
EXEC sp_rename ’st', ’stud’ 38
Exercise
Write the SQL queries using Data Definition Language (DDL)
statements:
1.Create database mydatabase.
2.Write a SQL statement to create a simple table student including columns
Stu_ID, Fname, Mname, Lname, DateOfBirth, age and Grade.
3.Write a SQL statement to rename the table student to new_tudent.
4.Write a SQL statement to add a column Phone_No to the table locations.
39
5.Write a SQL statement to drop the column grade from the table locations.
SQL Data Manipulation Language (DML)
▪ SQL (Structured Query Language) 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:
•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
SQL The SELECT Statement
• The SELECT statement is used to select data from a table. The
tabular result is stored in a result table (called the result-set).
Syntax
SELECT column_name(s)
FROM table_name
Example:
select * from student;
Using the WHERE Clause
The WHERE clause is used to specify a selection criterion.
The WHERE Clause
To 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
Example
select * from New_student where Grade =3.95;
select SID, D_Birth,Grade from New_student where Fname ='Meron';
Using the WHERE Clause
❑ With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
❑ Note: In some versions of SQL the <> operator may be written as !=
Using Quotes
• Note that we have used single quotes around the conditional values
in the examples.
• SQL uses single quotes around text values (most database systems
will also accept double quotes). Numeric values should not be
enclosed in quotes.
For text values:
This is correct:
select * from New_student where Fname ='Meron';
This is wrong:
select * from New_student where Fname ='Meron';
The LIKE Condition
The LIKE condition is used to specify a search for a pattern in a
column.
Syntax
SELECT column FROM table
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 Students with first names
that start with an ‘a':
select * from student where Fname like 'a%’;
• The following SQL statement will return students with first names
that end with an 'a':
select * from student where Fname like '%a';
The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into a
table.
Syntax
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
Insert a New Row
Example 1:
insert into stud values ('IS/00/14','Abel','Tamirat','Yonas',27,3.56);
Example 2:
insert into stud values
('IS/007/14','A','B','C',27,3.00),
('IS/008/14/','AA','BB','CC',25,4.00),
('IS/009/14','D','E','F',22,3.99);
Example 3:
insert into stud (SID,Fname,Mname,Lname,AGE,Grade)
values ('IS/005/14','Abebe','Sofi','Yishak',27,3.56);
The 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
Update one Column in a Row
Example
update Stud set Grade = 3.80
where Fname = 'Abel';
Update several Columns in a Row
Syntax
UPDATE table_name,
SET column_name1 = new_value, column_name2 = new_value, …
column_namen = new_value
WHERE column_name = some_value
Example:
update Student set Grade = 4.00, Age = 30 where SID = 'CS/122/15';
The Delete Statement
The DELETE statement is used to delete rows in a table.
Syntax
DELETE FROM table_name
WHERE column_name = some_value
example:
delete from Stud where SID='IS/007/14';
Delete All Rows
• It is possible to delete all rows in a table without
deleting the table. This means that the table structure,
attributes, and indexes will be intact:
DELETE FROM table_name
Or
DELETE * FROM table_name
Example: delete from Student;
SQL Selection and Projection Operation
Projection
▪ The projection consists of selecting the name of the column(s) of
the table(s) you wish to be displayed in the response. If you wish to
display all columns, "*" must be used. Column names are inserted next
to the SELECT clause.
▪ Select column1, column2, column… from table_name;
SQL Selection and Projection Operation
Selection
▪ The operation of selection involves selecting rows (tuples) of one (or
several) table(s) which meet certain conditions. Conditions are
specified after the WHERE clause.
• Select * from table_name where condition;
SQL Aggregate Functions
▪ SQL aggregation function is used to perform the calculations on
multiple rows of a single column of a table. It returns a single value.
▪ It is also used to summarize the data.
▪ Types of SQL Aggregation Function
SQL Aggregate Functions-COUNT FUNCTION
▪ COUNT function is used to Count the number of rows in a database
table. It can work on both numeric and non-numeric data types.
▪ COUNT function uses the COUNT(*) that returns the count of all
the rows in a specified table. COUNT(*) considers duplicate and Null.
Syntax:
• COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
• SELECT COUNT(column_name)
FROM table_name
WHERE condition;
SQL Aggregate Functions-SUM() FUNCTION
▪ The SUM() function returns the total sum of a numeric column.
▪ Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
SQL Aggregate Functions-AVG() FUNCTION
The AVG() function returns the average value of a numeric column.
▪ Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SQL Aggregate Functions-MIN() and MAX() FUNCTION
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
▪ Syntax:
• SELECT MIN(column_name)
FROM table_name
WHERE condition;
• SELECT MAX(column_name)
FROM table_name
WHERE condition;
SQL - Group By Clause
o The SQL GROUP BY clause groups rows of data with the same values in the
specified columns. This clause is most commonly used with SQL aggregate functions
to compute statistics (such as a count of certain values, sum, average, and the
minimum/maximum value in a set) for a group of rows.
o It is used to arrange similar data into groups. The GROUP BY clause follows the
WHERE clause comes before the ORDER BY clause.
SQL - Group By Clause
o Syntax:
SELECT column1, column 2… FROM table_name WHERE [condition] GROUP
BY column1, column2 ORDER BY column1, column2;
o Example:
o If we want to know the total salary of each Employe, then GROUP BY is used as
follows:
• SELECT FName, Sum(salary) FROM EMP GROUP BY FName;
• SELECT FName, count(salary) FROM EMP GROUP BY FName;
SQL - Order By Clause
o SQL Order By is used to sort the data in ascending or descending order.
It sorts the data in ascending order by default. To sort the data in
descending order we use the DESC keyword.
o Syntax:
• SELECT column1, column2…. FROM table_name ORDER BY column1
ASC/DESC, column2 ASC/DESC;
o Example:
• select Fname, Lname, Salary from Emp Order by Salary ASC;
• select Fname, Lname, Salary from Emp Order by Salary DESC;
THE END!!