Sunteți pe pagina 1din 45

SQL

Dr. Md. Rakibul Hoque


University of Dhaka
SQL (Structured Query Language)
SQL is a widely used and special-purpose domain-specific
database language used in programming and designed for
managing data held in a relational database management
system (RDBMS), or for stream processing in a relational data
stream management system (RDSMS). SQL is the most
influential commercially marketed query language. SQL uses
a combination of relational-algebra and relational-calculus
construct.
This is not just query language; it can define the structure of
the data, modify data in the database and specify security
constraints.
Categories of SQL

The four main categories of SQL statements


are as follows:
1. DML (Data Manipulation Language)
2. DDL (Data Definition Language)
3. DCL (Data Control Language)
4. TCL (Transaction Control Language)
Categories of SQL

Data Definition Language (DDL) Specifies


content and structure of database and defines
each data element as it appear before that data
element is translated into the forms required by
applications.
DDL statements are used to define the database
structure or schema.
DDL is also used to alter/modify a database or
table structure and schema.
Categories of SQL

Data-Definition Language (DDL): A database


schema is specified by a set of definitions
expressed by a special language called a data-
definition language.
create table account (
account-number char(10),
balance integer)
Database Languages

As DDL creates schema of a table it


also updates a special set of tables
called data directory or data dictionary.
A data dictionary contains metadata
(data about data). A database system
consults the data dictionary before
reading or modifying actual data.
Database Languages
Data dictionary: A data dictionary is a file or a set of
files that contains a database's metadata. The data
dictionary contains records about other objects in the
database, such as data ownership, data relationships
to other objects, and other data. The data dictionary
is a crucial component of any relational database.
Stores definitions of data elements and data
characteristics i.e usage, physical representation,
authorization, and security.
Categories of SQL

CREATE -create a new Table, database, schema


ALTER - alters the structure of the database. Alter
existing table, column description
DROP - delete objects from the database
TRUNCATE - remove all records from a table,
including all spaces allocated for the records are
removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
Categories of SQL

Data Manipulation Language (DML): DML


statements affect records in a table. These are
basic operations we perform on data such as
selecting a few records from a table, inserting
new records, deleting unnecessary records,
and updating/ modifying existing records.
DML is a language that enables users to
access or manipulate data as organized by
appropriate data model.
Database Languages
Data manipulation includes:
i) The retrieval of information stored in the
database
ii) The insertion of new information into the
database
iii) The deletion of information from the database
iv) The modification of information stored in the
database
Categories of SQL

DML statements include the following:


SELECT select records from a table. Retrieve

data from the a database


INSERT insert data into a table

UPDATE update/Modify existing data within a

table
DELETE delete existing records from a table

MERGE - UPSERT operation (insert or update)


Categories of SQL

DCL (Data Control Language): A data


control language (DCL) is a syntax similar to
a computer programming language used to
control access to data stored in a database
(Authorization). In particular, it is a
component of Structured Query Language
(SQL). DCL statements control the level of
access that users have on database objects.
Categories of SQL

GRANT gives user's access privileges to


database. Allows users to read/write on
certain database objects

REVOKE withdraw access privileges given


with the GRANT command. Keeps users from
read/write permission on database objects
Categories of SQL
TCL (Transaction Control Language): A Transaction
Control Language (TCL) is a computer language and
a subset of SQL, used to control transactional
processing in a database. TCL statements allow you
to control and manage transactions to maintain the
integrity of data within SQL statements.
TCL statements are used to manage the changes
made by DML statements. It allows statements to be
grouped together into logical transactions.
Categories of SQL

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to


which you can later roll back

ROLLBACK - restore database to original since


the last COMMIT
SQL Statement
Database Languages

Two classes of DML


Procedural DMLs user specifies
what data are required and how to get
or compute the data.
Nonprocedural DMLs (Declarative
DMLs) user specifies what data are
required without specifying how to get
or compute the data.
Database Languages

Query: A query is a statement


requesting the retrieval of
information. The portion of a DML
that involves information retrieval
is called a query language.
Parts of SQL

SQL has become the standard


relational database language. The SQL
language has several parts:
1. Data Definition Language (DDL):
The SQL DDL provides commands for
defining relation schemas, deleting
relation, modifying relation schemas
and creating indices.
Parts of SQL
2. Interactive Data Manipulation
Language (DML): The SQL DML includes
a query language based on both the
relational algebra and tuple relational
calculus. It includes also commands to
insert into, delete tuples from and modify
(update) tuples in the database.
3. View Definition: The SQL DDL
includes commands for defining views.
Parts of SQL

4. Transaction Control: SQL includes


commands for specifying the beginning
and ending of transactions.
5. Embedded SQL and Dynamic SQL:
These two define how SQL statements
can be embedded within general
purpose language like C, C++, Java,
PL/I, Cobol, Pascal, Fortran, RPG etc.
Parts of SQL

6. Integrity: The SQL DDL includes


commands for specifying integrity
constraints that the data stored in the
database must satisfy. Updates that violate
integrity constraints are disallowed.
7. Authentication: The SQL DDL includes
commands for specifying commands
across rights to relations and views.
Domain Types in SQL

char(n). Fixed length character string, with


user-specified length n. The full form character.
varchar(n). The full form is character varying.
Variable length character strings, with user-
specified maximum length n.
int. Integer (a finite subset of the integers that
is machine-dependent).
smallint. Small integer (a machine-dependent
subset of the integer domain type).
Domain Types in SQL

numeric(p,d). Fixed point number, with


user-specified precision of p digits, with n
digits to the right of decimal point.
real, double precision. Floating point
and double-precision floating point
numbers, with machine-dependent
precision.
float(n). Floating point number, with user-
specified precision of at least n digits.
Creation of Table

create table employee


(employee_name varchar (25) not null,
street varchar(20) not null,
city varchar(20) not null,
primary key (employee_name));
Data insertion

insert into employee


values ('A', 'Spring', 'Pittsfield');

insert into employee


values ('B', 'Senator', 'Brooklyn');
Basic Structure

A relational database consists of a


collection of relations, each of which is
assigned a unique name. Each
relation has a structure consisting of
their attributes and domains.
Basic Structure

The basic structure of an SQL expression


consists of three clauses:
1. select corresponds to the projection
operation of the relational algebra
expression. It is used to list the attributes
desired in the result of the query.
2. from corresponds to the Cartesian
product operation of the relational algebra.
It lists the relations to be scanned in the
evaluation of the expression.
Basic Structure

3. where corresponds to the


selection predicate of the
relational algebra. It consists of a
predicate involving attributes of
the relations that appear in the
from clause.
Basic Structure

General format:

Select A1, A2, A3


from r1, r2, r3
where P
Basic Structure

A typical SQL query has the form:


select A1, A2, ., An
from r1, r2, ., rm
where P

Each Ai represents an attribute and


each ri a relation. P is a predicate.
Basic Structure

Example1. Find the name of the customer


with customer-id 192-83-7465

Select customer.customer-name
from customer
where customer.customer-id= 192-83-7465
Basic Structure

Example2. Find the balances of all accounts held


by the customer with customer-id 192-83-7465
select account.balance
from depositor, account
where depositor.customer-id = 192-83-7465 and
depositor.account-number = account.account-
number
Basic Structure

SQL forms the Cartesian product of


the relations named in the from
clause, performs a relational algebra
selection using the where clause
predicate and then projects the result
onto the attributes of the select
clause.
The select Clause

a) Find the names of all branches in the loan


relation.
select branch-name from loan
Since duplicate elimination is time-
consuming, SQL allows duplicates in
relations as well as in the results of SQL
expressions. But duplicates are not allowed
in relational algebra because they are
considered as set.
The select Clause

To force the elimination of duplicates,


a keyword distinct is inserted after
select.
select distinct branch-name form loan
The select Clause

SQL allows to use keyword all to


specify explicitly that duplicates are
not removed. Since supplicate
retention is default, it is generally not
needed to use all keyword.
select all branch-name form loan
The asterisk * symbol can be used to
denote all attributes
select * from loan
The select Clause

The select clause may also contain


arithmetic expressions involving the
operators +, -, * and / operating on
constants or attributes of tuples.
[Generalized projection in relational
algebra]
select loan-number, amount * 100 from
loan
The select Clause

SQL also provides special data types


such as various forms of date type
and allows several arithmetic functions
on them.
ADD_ MONTH(d, n), LAST_DAY(d),
MONTS_BETWEEN(d1, d2), LAST_DAY
(date, char) etc.
The where Clause

a) Find all loan numbers for loans


made at the Mirpur branch with loan
amounts greater than 1200.

select loan-number
from loan
where branch-name=Mirpur and
amount > 1200
The where Clause
SQL uses the logical connectives and, or and
not rather than mathematical symbols , V
and in where clause. The operands of the
logical connectives can be expressions
involving the comparison operatiors =, <>, >, <,
>=, > and >=. SQL allows to use comparison
operators to compare strings and arithmetic
expressions as well as special types such as
dates.
SQL includes a between comparison to simplify
where clause that specify <= and >=. It is also
possible to use not between operator.
The where Clause

b) Find the loan number of those loans


with loan amounts between 10,000
and 100,000.
select loan-number
from loan
where amount between 10000 and
100000
The from Clause

The from clause by itself defines a


Cartesian product of the relations in
the clause. Since natural join is
defined in terms of a Cartesian
product, a selection and a projection, it
is relatively simple to write an SQL
expression for natural join.
The from Clause

a) For all customers who have a loan from the


bank, find their names, loan numbers and
loan amount.
select customer_name, loan.loan_number,
amount
from borrower, loan
where loan.loan_number =borrower.loan_number
Thank
You

S-ar putea să vă placă și