Vous êtes sur la page 1sur 50

Structured Query Language

SQL

9/8/2019
SEQUEL
• Structured English QUEry Language
1. implemented by System R
2. easy to learn & use
3. based on familiar English keywords &
avoided difficult relational algebra concepts
such as the division operator
4. also included update operators and a few
other concepts such as view creation &
definition of constraints
• SEQUEL was found to be a trademark for
something else …
– so, the name was changed to SQL: Structured
Query Language
• First product based on SQL was called
Oracle (1979) by a company called
Relational Software, Inc.
• IBM gets in the game in 1981 with
SQL/Data System
• SQL was implemented by all major
relational database suppliers & is now the
world’s most widely used database
language.
• ANSI project to develop SQL standards
– ANSI SQL, SQL-92 (SQL2) and SQL3
What is SQL?

– When a user wants to get some


information from a database file, he can
issue a query.
– A query is a user–request to retrieve data
or information with a certain condition.
– SQL is a query language that allows user to
specify the conditions. (instead of algorithms)

9/8/2019
Concept of SQL

– The user specifies a certain condition.


– The program will go through all the
records in the database file and select those
records that satisfy the condition.
– Statistical information of the data.
– The result of the query will then be stored
in form of a table.
9/8/2019
SQL COMMANDS
SQL

Data Definition Data Manipulation Data Control Transaction Control


Language(DDL) Language(DML) Langauge Langauge

Create
Alter Insert commit
Grant
Drop Delete Rollback
Revoke
Truncate Update savepoint
Rename Select
2 Basic structure of an SQL
query
General SELECT, ALL / DISTINCT, *,
Structure AS, FROM, WHERE

Comparison IN, BETWEEN, LIKE "% _"

Grouping GROUP BY, HAVING,


COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )

Display Order ORDER BY, ASC / DESC

Logical AND, OR, NOT


Operators

Output INTO TABLE / CURSOR


TO FILE [ADDITIVE], TO PRINTER, TO SCREEN

Union UNION

9/8/2019
DATA TYPES
• Character
• char ( length)
• ex: char(10)
• Character
• varchar2(length)
• ex: varchar2(5)
• Number
• number(3) eg., values should be 123, 467
• number (4,1) eg., values should be 123.4, 124.6, 22.5
• Date
• Date
• Eg., 22-oct-82 or 22-oct-1982
One preliminary note..
• SQL is case insensitive!!
CREATE TABLE = create table = CreAte TAblE

• Quoted text, however, is case sensitive


“Payroll” != “payroll”
1. CREATE-Syntax 1
a. simple creation
CREATE TABLE < tablename> (
<column name1 > < datatype>,
<column name 2> < datatype>,
<column name 3> < datatype>);

Create table book(


Bookno number(5),
Bookname varchar2(20),
Authorname varchar2(25),
Dop date,
Price number(6,2));
• INSERT INTO table_name VALUES
(value1, value2,....)
• Insert into table_name
values(&value1,&value2)
CREATE-Syntax 2
Table-level Primary key constraint
CREATE TABLE < tablename> (
<column name 1> < datatype>,
<column name 2> < datatype> unique ,
<column name 3> < datatype> ,
primary key ( <column name2>));

Create table book(


Bookno number(5),
Bookname varchar2(20),
Authorname varchar2(25),
Dop date,
Price number(6,2),
Primary key (Bookno));
Row-level Primary key constraint
CREATE TABLE < tablename> (
<column name1 > < datatype> primary key,
<column name 2> < datatype>,
<column name 3> < datatype>);

Create table book(


Bookno number(5) primary key,
Bookname varchar2(20),
Authorname varchar2(25),
Dop date,
Price number(6,2));
CREATE-Syntax 3 with constraint name and
Foreign Key
with constraint name and FK

CREATE TABLE < tablename1> (


<column name 1> < datatype>,
<column name 2> < datatype>,
constraint < constraint name1 > primary key ( <column name1>),
constraint <constraint name2> foreign key (<column name2>)
references <tablename2> (<column name1>) );
CREATE-Syntax 4 with check
constraint
with check constraint

CREATE TABLE < tablename> (


<column name1 > < datatype> ,
<column name 2> < datatype>,
check ( < column name 1 > in ( values) )
check ( < column name 2 > between <val1> and <val2> ) );

• Check (bookname in (‘prog in c’, ‘DBMS’,’Data structures’))


• Check (price between 0 and 5000)
2. ALTER
a. Add –to add new columns

ALTER TABLE <tablename> add ( <column name > < datatype>)


Eg., alter table emp add(SAL NUMBER(6));

b. Modify the datatype or increase / decrease the column width

ALTER TABLE <tablename> modify ( <column name > <newdatatype>)


EG., alter table emp modify(sal number(4));

c. drop –delete column or remove constraint

ALTER TABLE <tablename> drop column < column name>;


Eg., alter table emp drop coloumn sal;
ALTER TABLE <tablename> drop constraint < constraint name > ;

*** Constraints addition and column changing (datatype or decreasing the


width) can be done only if column values are null.
ALTER TABLE Persons ADD PRIMARY KEY (ID);

ALTER TABLE Persons


ADD CONSTRAINT PK_Person PRIMARY KEY (ID);

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(ID);

ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(ID);

ALTER TABLE Orders


DROP CONSTRAINT FK_PersonOrder;

select constraint_name,constraint_type,table_name from


user_constraints;
3. TRUNCATE
• Removes the rows, not the definition
• TRUNCATE TABLE <tablename>;

4. DROP
• Removes the rows and table definition
• DROP TABLE <tablename>;

5. RENAME
• Changes table name
• RENAME < old tablename> to < new tablename>;
DML STATEMENT
1. 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
LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

And this SQL statement:


INSERT INTO Persons
VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')

LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

Hetland Camilla Hagabakka 24 Sandnes


Insert Data in Specified
Columns
LastName FirstName Address City

Pettersen Kari Storgt 20 Stavanger

Hetland Camilla Hagabakka 24 Sandnes

And This SQL statement:


INSERT INTO Persons (LastName, Address)
VALUES ('Rasmussen', 'Storgt 67')

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
Rasmussen Storgt 67
2. Update one Column in a Row

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

We want to add a first name to the person with a last name of


"Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67
2. Update several Columns in a
Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger
3. The Delete Statement
The DELETE statement is used to delete rows in a table.
Syntax

DELETE FROM table_name


WHERE column_name = some_value
Delete a Row
LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

"Nina Rasmussen" is going to be deleted:


DELETE FROM Person WHERE LastName = 'Rasmussen'

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
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
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
To select the columns named "LastName" and "FirstName",
use a SELECT statement like this:
SELECT LastName, FirstName FROM Persons
Persons

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

výsledok

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
Select All Columns

To select all columns from the "Persons" table, use a *


symbol instead of column names, like this:
SELECT * FROM Persons

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
The Result Set

The result from a SQL query is stored in a result-set. Most database


software systems allow navigation of the result set with
programming functions, like: Move-To-First-Record, Get-Record-
Content, Move-To-Next-Record, etc.
Programming functions like these are not a part of this tutorial. To
learn about accessing data with function calls, please visit our ADO
tutorial.
Semicolon after SQL Statements?

Semicolon is the standard way to separate each SQL statement in


database systems that allow more than one SQL statement to be
executed in the same call to the server.
Some SQL tutorials end each SQL statement with a semicolon. Is
this necessary? We are using MS Access and SQL Server 2000
and we do not have to put a semicolon after each SQL statement,
but some database programs force you to use it.
The SELECT DISTINCT Statement
The DISTINCT keyword is used to return only distinct (different)
values.
The SELECT statement returns information from table columns.
But what if we only want to select distinct elements?
With SQL, all we need to do is to add a DISTINCT keyword to the
SELECT statement:
Syntax

SELECT DISTINCT column_name(s)


FROM table_name
Using the DISTINCT keyword

To select ALL values from the column named "Company" we use


a SELECT statement like this:
SELECT Company FROM Orders
Orders
Company
Sega
Company OrderNumber
W3Schools
Sega 3412
Trio
W3Schools 2312
W3Schools
Trio 4678
W3Schools 6798
Note that "W3Schools" is listed twice in the result-set.
You should not use DISTINCT keyword twice in the query.
To select only DIFFERENT values from the column named
"Company" we use a SELECT DISTINCT statement like this:
SELECT DISTINCT Company FROM Orders
Orders
Company
Sega
Company OrderNumber W3Schools
Sega 3412 Trio
W3Schools 2312
Trio 4678
W3Schools 6798
Select All Columns
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
Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a
WHERE clause to the SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960

LastName FirstName Address City Year


Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
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 Persons WHERE FirstName='Tove'

This is wrong:

SELECT * FROM Persons WHERE FirstName=Tove


And /or
• Select city from weather where
humidity>60 and humidity<80 or temp>60;

• Select * from weather where temp!=80;


order
• Select city from weather order by temp;
(by default it is ascending order otherwise we can put asc.)

Select city,temp from weather order by temp desc;

Select * from weather order by humidity,temp desc;

Select * from weather where humidity>70 order by temp;

Order of clause

select--------from------------where-------order by
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 persons with first names
that start with an 'O':
SELECT * FROM Persons
WHERE FirstName LIKE 'O%'

The following SQL statement will return persons with first names
that end with an 'a':
SELECT * FROM Persons
WHERE FirstName LIKE '%a'
Using LIKE

The following SQL statement will return persons with first names
that contain atleast 3 characters
SELECT * FROM Persons
WHERE FirstName LIKE ‘___%‘;

The following SQL statement will return persons with first names that contain
third character to be ‘s’

SELECT * FROM Persons


WHERE FirstName LIKE ‘__s%‘;
mismatching
• To find the mismatching characters we will
use, not like operator.

• Select * from weather where city not like ‘%ad%’;

• We can use like operator to compare with


numbers.

• Select * from weather where temp like 50;


Null / not null
• Find the name of employees who do not get commission.

• Select ename from emp where comm is null;


*******************************************************************
• Find the name of employees who get commission.

• Select ename from emp where comm is not null;


*********************************************************************
• Find the name of president.

• Select ename from emp where mgr is null


Aggregate functions
• It is used for grouping the data.
• It cannot be combined with another aggregate
functions and it cannot be used with where
clause.

• Sum()
• Avg()
• Max()
• Min()
• Count()
Aggregate functions
• Select sum(sal) from emp;

• Select avg(sal) from emp;


• Select max(sal) from emp;
• Select min(sal) from emp;
• Select count(sal) from emp;
• Select count(comm) from emp;
(it will count the number of non-empty values)
TCL

1. COMMIT
• To permanently save
• COMMIT;
2. SAVEPOINT
• To make markers in a lengthy transaction
• SAVEPOINT <savepoint name>;
3. ROLLBACK
• To undo changes till last commit
• ROLLBACK;
• To undo changes till a marker
• ROLLBACK <savepoint name>;

Vous aimerez peut-être aussi