Documente Academic
Documente Profesional
Documente Cultură
SQL Schema
A schema is an object that contains other objects.
The concept of an SQL schema was incorporated with SQL
in order to group together tables and other constructs that
belong to the same database application.
A schema is created via the CREATE SCHEMA statement,
which can include all the schema elements definitions.
Alternatively, the schema can be assigned a name and
authorization identifier, and the elements can be defined
later.
For example, the following statement creates a schema
called COMPANY, owned by the user with authorization
identifier Uname. Note that each statement in SQL ends
with a semicolon.
CREATE SCHEMA COMPANY AUTHORIZATION Uname;
Tables of a Database
To assist you with creating a table, you use a Data Definition Language
(DDL) command that is CREATE TABLE, followed by a name.
CREATE TABLE TableName . . .
After creating a table, it becomes part of its database and you can use
that table over and over again.
you can explicitly attach the schema name to the relation name,
separated by a period. For example, by writing
CREATE TABLE COMPANY.EMPLOYEE ...
If you don't specify a particular schema, the default dbo schema takes
ownership of the table.
In some cases, you may want to create a table to test something and
you would not need to use that table the next time you connect to the
server. Such a table is referred to as a temporary table.
To create a temporary table, start its name with #, followed by the
desired name.
Once the table has been created, it would be available as long as you
are using the same connection to the server.
If you close Microsoft SQL Server, the table would be automatically
deleted.
Identity Columns
To solve the problem of uniquely identifying a record, you can
create a column whose main purpose is to distinguish one record
from another.
The SQL allows you to create a column whose data type is an
integer type but the user doesn't have to enter data for that
column.
A value would automatically be entered into the field when a new
record is created.
This type of column is called an identity column.
You cannot create an identity column on an existing table, only on a
new table.
to indicate that a column would be used as an identity column after
its name and data type, type identity followed by parentheses.
Between the parentheses, enter the seed value, followed by a
comma, followed by the increment value. Here is an example:
CREATE TABLE StoreItems( ItemID int IDENTITY(1, 1) NOT NULL,
Category nvarchar(50),
[Item Name] nvarchar(100) NOT NULL,
Size varchar(20),
[Unit Price] money);
Renaming a Table
sp_rename ExistingTableName, TableNewName;
The names of tables should be included in single-quotes. Here is an
example:
sp_rename 'StaffMembers', 'Employees';
Deleting a Table
DROP TABLE TableName;
Referring to a Table
There are three main ways you can do : To refer to, or to indicate, a
table:
You can simply type its name. An example would be
Students
You can type the schema name, followed by the period operator,
followed by the name of the table.
Registration.Students
You can type the name of the database to which the table belongs,
followed by the period operator, followed by the schema, followed
by the period operator, and followed by the name of the table.
test.Registration.Students
Here is an example:
sp_rename Enrolled.grade', Grade', 'COLUMN'
Deleting a Column
ALTER TABLE TableName
DROP COLUMN ColumnName
Here is an example:
ALTER TABLE Enrolled
DROP COLUMN Grade;
Creating a Record
The DDL command to perform data entry is INSERT INTO combined
with VALUES.
The primary statement uses the following syntax:
INSERT INTO TableName VALUES(Column1, Column2, Column_n);
The VALUES keyword indicates that you are ready to list the values
of the columns.
The values of the columns must be included in parentheses.
If the column is a BIT data type, you must specify one of its values
a s 0 o r 1.
If the column is a numeric type, you should pay attention to the
number you type.
If the column was configured to receive an integer (int, bigint,
smallint), you should provide a valid natural number without the
decimal separator.
If the column is for a decimal number (float, real, decimal,
numeric), you can type the value with its character separator (the
period for US English).
If you provide a value for the identity column, you would receive an error
sname
Rating
ag e
22
Desta
29
Birtukan
31
sid
bid
D ay
45.0
22
101
10/10/98
33.0
22
102
10/10/98
Lema
5 5 .5
22
103
10/8/98
32
And inet
25.5
22
104
58
Ruhama
10
3 5 .0
31
64
H one lign
35.0
71
Zelalem
10
74
H one lign
85
95
bid
bname
color
101
Inte rlake
blue
102
Inte rlake
red
10/7/98
103
Clipper
green
102
11/10/98
104
Marine
red
31
103
11/6/98
16 . 0
31
104
11/12/98
35.0
64
101
9/5/98
Alemu
25.5
64
102
9/8/98
Bob
63.5
74
103
9/8/98
If a column has values that are difficult to identify, you can use a CASE conditional statement to customize the
result(s). Here is an example:
CREATE TABLE Persons(FirstName nvarchar(20),
LastName nvarchar(20),
GenderID int);
Find the names of sailors Who have reserved boat number 103
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND R.bid=103
This query contains join of two tables, followed by a selection by boat
number.
unless they are needed to resolve an ambiguity, the use of range variables
is optional
SELECT sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND bid=103
Only the occurrences of sid have to be qualified, since this column appears
in both the Sailors and Reserves tables.
An equivalent way to write this query is:
SELECT sname
FROM Sailors, Reserves
WHERE Sailors.sid = Reserves.sid AND bid=103
This query shows that table names can be used implicitly as row variables.
Compute increments for the ratings of persons who have sailed two different
boats on the same day:
SELECT S.sname, S.rating+1 AS rating
FROM Sailors S, Reserves R1, Reserves R2
WHERE S.sid = R1.sid AND S.sid = R2.sid
AND R1.day = R2.day AND R1.bid <> R2.bid
SQL provides support for pattern matching through the LIKE operator, along with
the use of the wild-card symbols:
% (which stands for zero or more arbitrary characters) and
_ (which stands for exactly one, arbitrary, character).
Note that unlike the other comparison operators, blanks can be significant for the
LIKE operator. Thus, 'Jeff' = Jeff' is true while 'Jeff LIKE Jeff ' is false.
Find the ages of sailors whose name begins and ends with B and has at least three
characters.
SELECT S.age
FROM Sailors S
WHERE S.sname LIKE 'B%B'
The only such sailor is Bob, and his age is 63.5.
The following query results a list of Sailor whose sname begins with a, b, c, d, or e.
Find all sids of sailors who have a rating of 10 or reserved boat 104.
SELECT S.sid
FROM Sailors S
WHERE S.rating = 10
UNION
SELECT R.sid
FROM Reserves R
WHERE R.bid = 104
The first part of the union returns the sids 58 and 71.
The second part returns 22 and 31.
The answer is therefore, the set of sids 22, 31, 58, and 71.
In contrast to the default that duplicates are not eliminated unless
DISTINCT is specified in the basic query form,
the default for UNION queries is that duplicates are eliminated! To
retain duplicates, UNION ALL must be used.
Similarly, INTERSECT ALL retains duplicates, and EXCEPT ALL also
retains duplicates.
NESTED QUERIES
One of the most powerful features of SQL is nested queries.
A nested query is a query that has another query embedded within it;
the embedded query is called a subquery.
The embedded query can of course be a nested query itself; thus
queries that have very deeply nested structures are possible.
SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid = 103 )
The nested subquery computes the set of sids for sailors who have
reserved boat 103(the set contains 22, 31, and 74), and
the top-level query retrieves the names of sailors whose sid is in this
set.
The IN operator allows us to test whether a value is in a given set of
elements
Note that it is very easy to modify this query to find all sailors who
have not reserved boat 103:
we can just replace IN by NOT IN!
Find the names of sailors who have reserved boat number 103:
SELECT S.sname
FROM Sailors S
WHERE EXISTS ( SELECT *
FROM Reserves R
WHERE R.bid = 103
AND R.sid = S.sid )
The EXISTS operator is another set comparison operator, such as IN.
It allows us to test whether a set is nonempty, an implicit
comparison with the empty set.
The occurrence of S in the subquery (in the form of the literal S.sid)
is called a correlation, and such queries are called correlated
queries.
We used a special symbol * because all we want to do is to check
that a qualifying row exists, and do not really want to retrieve any
columns from the row.
by using NOT EXISTS instead of EXISTS, we can compute the names
of sailors who have not reserved a boat number 103.
Set-Comparison Operators
We have already seen the set-comparison operators
EXISTS, and IN, along with their negated versions.
SQL also supports op ANY and op ALL,
where op is one of the arithmetic comparison
operators {<, <=, =, <>, >=, >}.
SOME is also available, but it is just a synonym for ANY.
Ex. Find sailors whose rating is better than some sailor
called Honelign.
SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERE S2.sname = 'Honelign' )
What if there were no sailor called Honelign?
In this case the comparison S.rating > ANY ... is defined to return false, and
the query returns an empty answer set.
Ex:- Find sailors whose rating is better than every sailor called
Honelign:
Just replace ANY with ALL in the WHERE clause of the outer
query.
SELECT S.sid
FROM Sailors S
WHERE S.rating > ALL ( SELECT S2.rating
FROM Sailors S2
WHERE S2.sname = 'Honelign' )
SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2 )
The subquery computes the set of all rating values in Sailors.
The outer WHERE condition is satisfied only when S.rating is greater than or equal
to each of these rating values, that is, when it is the largest rating value.
Note that IN and NOT IN are equivalent to = ANY and <> ALL, respectively.
AGGREGATE OPERATORS
SQL supports five aggregate operations, which can be applied on any
column, say A, of a relation:
1. COUNT ([DISTINCT] A): The number of (unique) values in the A column.
2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.
3. AVG ([DISTINCT] A): The average of all (unique) values in the A column.
4. MAX (A): The maximum value in the A column.
5. MIN (A): The minimum value in the A column.
Note that it does not make sense to specify DISTINCT in conjunction with
MIN or MAX (although SQL does not preclude this).
Ex:- Find the average age of all sailors:
SELECT AVG (S.age)
FROM Sailors S
Of course, the WHERE clause can be used to restrict the sailors considered
in computing the average age.
Ex:- Find the average age of sailors with a rating of 10:
SELECT AVG (S.age)
FROM Sailors S
WHERE S.rating = 10
Observe that this version of the preceding query is illegal (SQL disallows it):
SELECT B.bid, COUNT (*) AS reservationcount
FROM Boats B, Reserves R
WHERE R.bid = B.bid
GROUP BY B.bid
HAVING B.color = 'red'
Only the columns that appear in the GROUP BY clause can appear in the
HAVING clause, unless they appear as arguments to an aggregate operator in
the HAVING clause.
E.g Find the average age of sailors for each rating level that has at least two
sailors:
SELECT
S.rating, AVG (S.age) AS avgage
FROM
Sailors S
GROUP BY S.rating
HAVING
COUNT (*) > 1
After identifying groups based on rating, we retain only groups with at least
two sailors.
Data Joins
A data join is a technique of creating a list of records from more than one
table, using all columns from all tables involved, or selecting only the desired
columns from one or all of the tables involved.
In the SQL, the basic formula to create a join is:
SELECT WhatColumn(s)
FROM ChildTable
TypeOfJoin ParentTable
ON Condition
ChildTable specifies the table that holds the records that will be retrieved.
ParentTable specifies the table that holds the column with the primary key
that will control what records, related to the child table that will display.
Condition is a logical expression used to validate the records that will be
isolated. The condition can be created using the following formula:
Table1Column Operator Table2Column
To create the condition, you start with the ON keyword.
You can assign the primary key column of the parent table to the foreign key
column of the child table.
Because both columns likely have the same name, to distinguish them, their
names should be qualified.
Cross Joins
A cross join creates a list of all records from both tables
as follows:
1. the first record from the parent table is associated to
each record from the child table, then
2. the second record from the parent table is associated
to each record from the child table, and so on.
3. In this case, there is no need of a common column
between both tables. In other words, you will not use
the ON clause.
Ex.
SELECT S.sid, R.bid
FROM (Sailors S CROSS JOIN Reserves R)
Inner Joins
Imagine you have two tables that can be linked through
one's primary key and another's foreign key:
Genders
Persons
Notice that some records in the Persons table don't have an entry for the
GenderID column and were marked with NULL by the database engine.
When creating a query of records of the Persons table, if you want your list
to include only records that have an entry, you can create it as inner join.
Notice that the query result starts with the first record of
the parent table, and
lists the records of the child table that have the entry
corresponding to that first record.
Then it moves to the next sid value of parent table.
For example, we can define a view that allows sailors to see other sailors
all information but not their age, and allow all sailors to access this view,
but not the underlying Sailors table.
CREATE VIEW sailor_info
AS SELECT sid,sname,rating
FROM Sailors
Renaming a View
sp_rename CurrentViewName, NewName;
E.g. sp_rename sailor_info, sailors_info;
Altering a View
After a view has been created, you may find out that it has an unnecessary
column, it needs a missing column, it includes unnecessary records, or
some records are missing.
Fortunately, you can change the structure or the code of a view.
For example, you can create a SELECT statement that includes a
modification of the existing code or a completely new statement.
ALTER VIEW sailors_info
AS SELECT sid,sname,rating,age
FROM Sailors
If we do not need a view any more, we can use the DROP VIEW command
to dispose of it.
For example,
DROP VIEW sailors_info;
The UPDATE command is used to modify attribute values of one or more selected
tuples.
a WHERE clause in the UPDATE command selects the tuples to be modified from a
single relation.
However, updating a primary key value may propagate to the foreign key values of
tuples in other relations if such a referential triggered action is specified in the
referential integrity constraints of the DDL.
The SET clause in the UPDATE command specifies the attributes to be modified and
their new values.
For example, to change the sid and sname of sailor with sid 22 in to 20 and 'Daniel',
respectively, we use:
UPDATE Sailors
SET
sid = 20,sname = 'Daniel'
WHERE
sid = 22;
UPDATE
Sailors
SET
rating = rating + 1
WHERE
age > 40;
It is also possible to specify NULL or DEFAULT as the new attribute value.
UPDATE Sailors
SET
rating = null
WHERE
age = 45;