Introduction to SQL
1
Fall 2001 Database Systems 1
SQL
• A simple “logical” and “declarative” language for
communicating with a DBMS to carry out different tasks
– querying data (select statements)
– inserting, updating and deleting rows in a table
– creating, replacing, altering, and dropping objects
– controlling access to the database and its objects
– guaranteeing database consistency and integrity
• DDL: data definition language
• DML: data manipulation language
• Most DBMSs “speak” SQL
Fall 2001 Database Systems 2
SQL
• SQL developed by IBM and first implemented by
Relational Software Inc. (now Oracle) in 1979
• The last published standard (ANSI and ISO) called
SQL92 (or SQL2) sets four levels of compliance:
entry, transitional, intermediate and full
• All DBMSs should have at least entry level
compliance
• Most DBMSs support various advanced features as
well as vendor specific features
• SQL3 (also called SQL99) is the next target
standard which is still being developed
Introduction to SQL
2
Fall 2001 Database Systems 3
SQL - DDL
• A database installation is usually called a
database instance (for example ora8 for rcs).
– For a specific instance, there are multiple users
• Created by CREATE USER command by the DBA
• A user is considered to own his/her own schema (user =
schema)
• Each user has the ability to
– Change his/her own password
ALTER USER suppiluliumas IDENTIFIED BY greatking;
– Perform operations that he/she is allowed to! (access
rights/security)
Fall 2001 Database Systems 4
SQL - DDL
• To create a table (relation), we use the following
command:
• General form
CREATE TABLE <Table_Name>
(Attribute_1 <Type>[DEFAULT <value>][<Null
constraint>],
Attribute_2 <Type>[DEFAULT <value>][<Null
constraint>],
…
Attribute_n <Type>[DEFAULT <value>][<Null
constraint>],
[<Constraints>])
Introduction to SQL
3
Fall 2001 Database Systems 5
SQL – DDL
• There is an undo for most operations: CREATE TABLE tablename,
DROP TABLE tablename
• Bids tables:
CREATE TABLE BUYERS (
BUYID INT,
NAME CHAR(20) NOT NULL,
EMAIL VARCHAR2(20),
PRIMARY KEY (BUYID)
) ;
When writing commands in Sqlplus, use a “;” to end each command.
Fall 2001 Database Systems 6
SQL – DDL Data types
• Numeric
– INT, SHORTINT
– REAL (FLOAT), DOUBLE PRECISION
– DECIMAL(i,j)
• Character-string
– CHAR(n), VARCHAR(n)
• Bit-string
– BIT(n), BIT VARYING(n)
• Date
– YYYY-MM-DD
• Time
– HH:MM:SS
• Timestamp
– both DATE and TIME fields plus a minimum of six positions for
fractions of seconds
Introduction to SQL
4
Fall 2001 Database Systems 7
Attribute constraints
• Not null
– Specifies that an attribute cannot contain null values
• Unique
– Specifies that an attribute cannot contain duplicates
• Primary key
– Designates a set of columns as the table’s primary key
– Implies UNIQUE and NOT NULL
• Foreign key
– Designates a set of columns as the foreign key in a referential
constraint
Fall 2001 Database Systems 8
SQL – DDL
CREATE TABLE BIDS (
BID INT,
BIDDATE DATE NOT NULL,
IID INT NOT NULL,
BUYID INT NOT NULL,
AMOUNT INT NOT NULL,
PRIMARY KEY (BID),
FOREIGN KEY (IID) REFERENCES ITEMS(IID),
FOREIGN KEY (BUYID) REFERENCES
BUYERS(BUYID)
) ;
Introduction to SQL
5
Fall 2001 Database Systems 9
SQL – DDL Insert
• Insert tuples into tables:
INSERT INTO OWNERS
VALUES(1, ‘Smith’, ‘Smith@aol.com’) ;
INSERT INTO
ITEMS(IID, OID, NAME, LOCATION)
VALUES(1, 1, ‘Scales’, ‘Boston’) ;
Fall 2001 Database Systems 10
SQL - Select
• The main body of an SQL select statement is:
SELECT projection columns
FROM relations
WHERE selection and join conditions
• SQL statements produce a “bag” of tuples, i.e. duplicates
are not removed automatically unless a “DISTINCT”
statement precedes the column name!
• Any relational algebra query involving only selection,
projection and join operations can be translated to a single
SQL query of the above form
Introduction to SQL
6
Fall 2001 Database Systems 11
Find the names and identifiers of all items located in “Boston”
SELECT Name, Iid
FROM Items
WHERE Location = ‘Boston’
Find all buyers
SELECT *
FROM Buyers
Find the identifier of all bids of $20 or higher placed on Date 9/2
SELECT Bid
FROM Bids
WHERE Amount > 20 AND Date= ‘9/2’
Fall 2001 Database Systems 12
[BAGS] Find the identifier of all buyers who placed a bid
SELECT BuyId SELECT DISTINCT BuyId
FROM Bids FROM Bids
[JOIN and ALIAS] Find the names of owners and the names of products
that they own
SELECT O.name, I.name
FROM Owners O, Items I
WHERE O.Oid = I.Oid
Find the name and email of owners of items located in Boston
SELECT O.name, O.email
FROM Owners O, Items I
WHERE O.Oid = I.Oid AND I.Location = ‘Boston’
Aliases
Join condition
Do we need to
use “DISTINCT”
in this query?
Introduction to SQL
7
Fall 2001 Database Systems 13
SQL
Execute an SQL body of the form
SELECT A1…An
FROM R1…Rm
WHERE C
as follows:
for all combinations of tuples r1…rm from relations R1…Rm do
if the tuple combination r1…rm together satisfy C then
include the attributes A1…An from r1…rm in the
resulting bag of tuples
end-for
If keyword “distinct” is used, remove duplicates
Fall 2001 Database Systems 14
SQL - Set Operations
• The set membership conditions “IN” and “NOT IN” are
used for any sets:
SELECT Name
FROM Items
WHERE Location IN (‘Dallas’, ‘Boston’)
• SQL statements return a set of tuples as well. We can
substitute an SQL statement for a set as long as it is
compatible with the compared attribute!
Introduction to SQL
8
Fall 2001 Database Systems 15
SQL - Nested Statements
• Find the name of all buyers who have a bid
SELECT Name
FROM Buyers
WHERE BuyId IN ( SELECT BuyID
FROM Bids )
• Find the name of buyers who did not bid on an item located
in “Boston”
SELECT B.Name
FROM Buyers B
WHERE B.BuyId NOT IN ( SELECT B2.BuyID
FROM BIDS B2, Items I
WHERE I.Location = ‘Boston’
AND B2.buyid = I.buyid )
Fall 2001 Database Systems 16
SQL - Nested Statements
SELECT A1…An
FROM R1…Rm
WHERE C op (SELECT A’1…A’m FROM R’1…R’k WHERE C’)
is executed as follows:
for all combinations of tuples r1…rm from relations R1…Rm do
execute subquery Temp = ( SELECT A’1…A’m FROM R’1…R’k
WHERE C’) using values of r1…rm
if C op Temp is true for the tuple combination r1…rm then
include the attributes A1…An from r1…rm in the resulting bag of tuples
end-for
Introduction to SQL
9
Fall 2001 Database Systems 17
Subselect comparisons
• Find the buyers who placed the highest bids
SELECT B.buyid
FROM Bids B
WHERE B.Amount >=ALL (SELECT B2.Amount
FROM Bids B2)
Fall 2001 Database Systems 18
Subselect comparisons
• Find all items with a bid
SELECT I.Name
FROM Items I
WHERE I.Iid =ANY (SELECT B.Iid FROM Bids
B)
• Subselect comparisons
ΘANY
ΘALL
where Θ is one of <, =, >, <=, >=, <>
Introduction to SQL
10
Fall 2001 Database Systems 19
Union
• Find the name and email of all owners and buyers
(SELECT O.Name, O.Email
FROM Owners O )
UNION
(SELECT B.Name, B.Email
FROM Buyers B)
• Like in the algebra, a union can only be performed among
compatible sub-expressions.
• Union removes duplicates!
• To retain duplicates use “UNION ALL”!
Fall 2001 Database Systems 20
More on WHERE
• Find all buyers whose name starts with “G”
SELECT B.*
FROM Buyers B
WHERE B.Name LIKE ‘G%’
• Find all bids between $20 and $40
SELECT B.*
FROM Bids B
WHERE B.Amount BETWEEN 20 AND 40
• Find all buyers who name starts with a letter
between A and G
SELECT B.*
FROM Buyers B
WHERE B.Name BETWEEN ‘A%’ AND ‘G%’
Regular expression
Introduction to SQL
11
Fall 2001 Database Systems 21
SQL – selection conditions
• An expression (produces a value)
– Any attribute name
– Any constant
– Any function over these
– Examples: ITEMS.IID 4 ITEMS.IID+10
BIDS.AMOUNT*5/20
GREATER(BIDS.AMOUNT, 20)
‘Sibel’ || ‘Adali’
– Regular expressions:
• An underscore (_) in the pattern matches exactly one character (as
opposed to one byte in a multibyte character set) in the value.
• A percent sign (%) in the pattern can match zero or more characters
(as opposed to bytes in a multibyte character set) in the value. Note
that the pattern '%' cannot match a null.
Fall 2001 Database Systems 22
SQL - conditions
• Unary conditions
– Expression IS NULL (5 IS NULL) ?
– EXISTS SQL-Expression
• Binary conditions
– Expression > Expression (10 < Bids.amount)?
– Expression LIKE Expression
– Expression (NOT) IN Expression (5 IN (5,10,25))?
• Combination of these conditions with AND, OR,
NOT
Introduction to SQL
12
Fall 2001 Database Systems 23
SQL – functions
• Functions can be used in both SELECT and
WHERE statements. Examples:
– Math functions: ABS, FLOOR, LOG, MOD
– String functions: Concatenation (||), UPPER, LOWER,
SUBSTR
– Date functions: ADD_MONTHS, SYSDATE,
MONTHS_BETWEEN
– Conversion functions: TO_DATE, TO_CHAR
– Example:
• TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI:SS’)
Fall 2001 Database Systems 24
Conditions and Null
• If a column has a null value, then this column
cannot make a condition in the WHERE clause
evaluate to true or false.
• A selection condition A and B evaluates to true if
and only if both A and B evaluate to true.
• A selection condition A or B evaluates to true if and
only if either one of A or B evaluate to true.
• A selection condition not (A) evaluates to true if and
only if A evaluates to false.

[Www.pkbulk.blogspot.com]dbms05

  • 1.
    Introduction to SQL 1 Fall2001 Database Systems 1 SQL • A simple “logical” and “declarative” language for communicating with a DBMS to carry out different tasks – querying data (select statements) – inserting, updating and deleting rows in a table – creating, replacing, altering, and dropping objects – controlling access to the database and its objects – guaranteeing database consistency and integrity • DDL: data definition language • DML: data manipulation language • Most DBMSs “speak” SQL Fall 2001 Database Systems 2 SQL • SQL developed by IBM and first implemented by Relational Software Inc. (now Oracle) in 1979 • The last published standard (ANSI and ISO) called SQL92 (or SQL2) sets four levels of compliance: entry, transitional, intermediate and full • All DBMSs should have at least entry level compliance • Most DBMSs support various advanced features as well as vendor specific features • SQL3 (also called SQL99) is the next target standard which is still being developed
  • 2.
    Introduction to SQL 2 Fall2001 Database Systems 3 SQL - DDL • A database installation is usually called a database instance (for example ora8 for rcs). – For a specific instance, there are multiple users • Created by CREATE USER command by the DBA • A user is considered to own his/her own schema (user = schema) • Each user has the ability to – Change his/her own password ALTER USER suppiluliumas IDENTIFIED BY greatking; – Perform operations that he/she is allowed to! (access rights/security) Fall 2001 Database Systems 4 SQL - DDL • To create a table (relation), we use the following command: • General form CREATE TABLE <Table_Name> (Attribute_1 <Type>[DEFAULT <value>][<Null constraint>], Attribute_2 <Type>[DEFAULT <value>][<Null constraint>], … Attribute_n <Type>[DEFAULT <value>][<Null constraint>], [<Constraints>])
  • 3.
    Introduction to SQL 3 Fall2001 Database Systems 5 SQL – DDL • There is an undo for most operations: CREATE TABLE tablename, DROP TABLE tablename • Bids tables: CREATE TABLE BUYERS ( BUYID INT, NAME CHAR(20) NOT NULL, EMAIL VARCHAR2(20), PRIMARY KEY (BUYID) ) ; When writing commands in Sqlplus, use a “;” to end each command. Fall 2001 Database Systems 6 SQL – DDL Data types • Numeric – INT, SHORTINT – REAL (FLOAT), DOUBLE PRECISION – DECIMAL(i,j) • Character-string – CHAR(n), VARCHAR(n) • Bit-string – BIT(n), BIT VARYING(n) • Date – YYYY-MM-DD • Time – HH:MM:SS • Timestamp – both DATE and TIME fields plus a minimum of six positions for fractions of seconds
  • 4.
    Introduction to SQL 4 Fall2001 Database Systems 7 Attribute constraints • Not null – Specifies that an attribute cannot contain null values • Unique – Specifies that an attribute cannot contain duplicates • Primary key – Designates a set of columns as the table’s primary key – Implies UNIQUE and NOT NULL • Foreign key – Designates a set of columns as the foreign key in a referential constraint Fall 2001 Database Systems 8 SQL – DDL CREATE TABLE BIDS ( BID INT, BIDDATE DATE NOT NULL, IID INT NOT NULL, BUYID INT NOT NULL, AMOUNT INT NOT NULL, PRIMARY KEY (BID), FOREIGN KEY (IID) REFERENCES ITEMS(IID), FOREIGN KEY (BUYID) REFERENCES BUYERS(BUYID) ) ;
  • 5.
    Introduction to SQL 5 Fall2001 Database Systems 9 SQL – DDL Insert • Insert tuples into tables: INSERT INTO OWNERS VALUES(1, ‘Smith’, ‘Smith@aol.com’) ; INSERT INTO ITEMS(IID, OID, NAME, LOCATION) VALUES(1, 1, ‘Scales’, ‘Boston’) ; Fall 2001 Database Systems 10 SQL - Select • The main body of an SQL select statement is: SELECT projection columns FROM relations WHERE selection and join conditions • SQL statements produce a “bag” of tuples, i.e. duplicates are not removed automatically unless a “DISTINCT” statement precedes the column name! • Any relational algebra query involving only selection, projection and join operations can be translated to a single SQL query of the above form
  • 6.
    Introduction to SQL 6 Fall2001 Database Systems 11 Find the names and identifiers of all items located in “Boston” SELECT Name, Iid FROM Items WHERE Location = ‘Boston’ Find all buyers SELECT * FROM Buyers Find the identifier of all bids of $20 or higher placed on Date 9/2 SELECT Bid FROM Bids WHERE Amount > 20 AND Date= ‘9/2’ Fall 2001 Database Systems 12 [BAGS] Find the identifier of all buyers who placed a bid SELECT BuyId SELECT DISTINCT BuyId FROM Bids FROM Bids [JOIN and ALIAS] Find the names of owners and the names of products that they own SELECT O.name, I.name FROM Owners O, Items I WHERE O.Oid = I.Oid Find the name and email of owners of items located in Boston SELECT O.name, O.email FROM Owners O, Items I WHERE O.Oid = I.Oid AND I.Location = ‘Boston’ Aliases Join condition Do we need to use “DISTINCT” in this query?
  • 7.
    Introduction to SQL 7 Fall2001 Database Systems 13 SQL Execute an SQL body of the form SELECT A1…An FROM R1…Rm WHERE C as follows: for all combinations of tuples r1…rm from relations R1…Rm do if the tuple combination r1…rm together satisfy C then include the attributes A1…An from r1…rm in the resulting bag of tuples end-for If keyword “distinct” is used, remove duplicates Fall 2001 Database Systems 14 SQL - Set Operations • The set membership conditions “IN” and “NOT IN” are used for any sets: SELECT Name FROM Items WHERE Location IN (‘Dallas’, ‘Boston’) • SQL statements return a set of tuples as well. We can substitute an SQL statement for a set as long as it is compatible with the compared attribute!
  • 8.
    Introduction to SQL 8 Fall2001 Database Systems 15 SQL - Nested Statements • Find the name of all buyers who have a bid SELECT Name FROM Buyers WHERE BuyId IN ( SELECT BuyID FROM Bids ) • Find the name of buyers who did not bid on an item located in “Boston” SELECT B.Name FROM Buyers B WHERE B.BuyId NOT IN ( SELECT B2.BuyID FROM BIDS B2, Items I WHERE I.Location = ‘Boston’ AND B2.buyid = I.buyid ) Fall 2001 Database Systems 16 SQL - Nested Statements SELECT A1…An FROM R1…Rm WHERE C op (SELECT A’1…A’m FROM R’1…R’k WHERE C’) is executed as follows: for all combinations of tuples r1…rm from relations R1…Rm do execute subquery Temp = ( SELECT A’1…A’m FROM R’1…R’k WHERE C’) using values of r1…rm if C op Temp is true for the tuple combination r1…rm then include the attributes A1…An from r1…rm in the resulting bag of tuples end-for
  • 9.
    Introduction to SQL 9 Fall2001 Database Systems 17 Subselect comparisons • Find the buyers who placed the highest bids SELECT B.buyid FROM Bids B WHERE B.Amount >=ALL (SELECT B2.Amount FROM Bids B2) Fall 2001 Database Systems 18 Subselect comparisons • Find all items with a bid SELECT I.Name FROM Items I WHERE I.Iid =ANY (SELECT B.Iid FROM Bids B) • Subselect comparisons ΘANY ΘALL where Θ is one of <, =, >, <=, >=, <>
  • 10.
    Introduction to SQL 10 Fall2001 Database Systems 19 Union • Find the name and email of all owners and buyers (SELECT O.Name, O.Email FROM Owners O ) UNION (SELECT B.Name, B.Email FROM Buyers B) • Like in the algebra, a union can only be performed among compatible sub-expressions. • Union removes duplicates! • To retain duplicates use “UNION ALL”! Fall 2001 Database Systems 20 More on WHERE • Find all buyers whose name starts with “G” SELECT B.* FROM Buyers B WHERE B.Name LIKE ‘G%’ • Find all bids between $20 and $40 SELECT B.* FROM Bids B WHERE B.Amount BETWEEN 20 AND 40 • Find all buyers who name starts with a letter between A and G SELECT B.* FROM Buyers B WHERE B.Name BETWEEN ‘A%’ AND ‘G%’ Regular expression
  • 11.
    Introduction to SQL 11 Fall2001 Database Systems 21 SQL – selection conditions • An expression (produces a value) – Any attribute name – Any constant – Any function over these – Examples: ITEMS.IID 4 ITEMS.IID+10 BIDS.AMOUNT*5/20 GREATER(BIDS.AMOUNT, 20) ‘Sibel’ || ‘Adali’ – Regular expressions: • An underscore (_) in the pattern matches exactly one character (as opposed to one byte in a multibyte character set) in the value. • A percent sign (%) in the pattern can match zero or more characters (as opposed to bytes in a multibyte character set) in the value. Note that the pattern '%' cannot match a null. Fall 2001 Database Systems 22 SQL - conditions • Unary conditions – Expression IS NULL (5 IS NULL) ? – EXISTS SQL-Expression • Binary conditions – Expression > Expression (10 < Bids.amount)? – Expression LIKE Expression – Expression (NOT) IN Expression (5 IN (5,10,25))? • Combination of these conditions with AND, OR, NOT
  • 12.
    Introduction to SQL 12 Fall2001 Database Systems 23 SQL – functions • Functions can be used in both SELECT and WHERE statements. Examples: – Math functions: ABS, FLOOR, LOG, MOD – String functions: Concatenation (||), UPPER, LOWER, SUBSTR – Date functions: ADD_MONTHS, SYSDATE, MONTHS_BETWEEN – Conversion functions: TO_DATE, TO_CHAR – Example: • TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI:SS’) Fall 2001 Database Systems 24 Conditions and Null • If a column has a null value, then this column cannot make a condition in the WHERE clause evaluate to true or false. • A selection condition A and B evaluates to true if and only if both A and B evaluate to true. • A selection condition A or B evaluates to true if and only if either one of A or B evaluate to true. • A selection condition not (A) evaluates to true if and only if A evaluates to false.