Sunteți pe pagina 1din 22

STRUCTURED QUERY LANGUAGE

 SQL was first implemented in IBM's System R in the late 1970's.


 SQL is the de-facto standard query language for creating and manipulating data in
relational databases.
 Some minor syntax differences, but the majority of SQL is standard across MS Access,
Oracle, Sybase, Informix, etc.
 SQL is either specified by a command-line tool or is embedded into a general purpose
programming language such as COBOL, "C", Pascal, Java, C++, etc.
 SQL is a standardized language monitored by the American National Standards Institute
(ANSI) as well as by National Institute of Standards (NIST).
o ANSI 1990 - SQL 1 standard
o ANSI 1992 - SQL 2 Standard (sometimes called SQL-92)
o ANSI 1999 - SQL 1999 - adds regular expressions, triggers, some Object oriented
concepts
o ANSI 2003 - SQL 2003 - XML features, auto generated data (e.g., auto number)
o ANSI 2006 - SQL 2006 - Further XML Integration using XQuery, XPath, etc.
o ANSI 2008 - SQL 2008 - Additional commands usch as Truncate

SQL HAS TWO MAJOR PARTS:

1. Data Definition Language (DDL) Used to create (define) data structures


such as tables, indexes, clusters
2. Data Manipulation Language (DML) is used to store, retrieve and update
data from tables.
3. Data Control Languages(DCL) is used to control the access of data and
rights of the users

SQL DATA TYPES

Each implementation of SQL uses slightly different names for the data types.

1. Numeric Data Types


 Integers: INTEGER, INT or SMALLINT
 Real Numbers: FLOAT, REAL, DOUBLE, PRECISION
 Formatted Numbers: DECIMAL(i,j), NUMERIC(i,j)

2. Character Strings

 TWO MAIN TYPES: FIXED LENGTH AND VARIABLE LENGTH.


1. Fixed length of n characters: CHAR(n) or CHARACTER(n)
2. Variable length up to size n: VARCHAR(n)
Date and Time

Note: Implementations vary widely for these data types.

DATE: Has 10 positions in the format: YYYY-MM-DD

TIME: Has 8 positions in the format: HH:MM:SS

1. TIME (i): Defines the TIME data type with an additional i positions for fractions of a
second. For example: HH:MM:SS:dd and Offset from UTZ. +/- HH:MM

2. TIMESTAMP

3. INTERVAL: Used to specify some span of time measured in days or minutes, etc.

4. Other ways of expressing dates:


 Store as characters or integers with Year, Month Day:
19972011
 Store as Julian date:
1997283

Note: MS Access, SQL Server and Oracle store date and time information together in a
DATE data type.

Examples of Data Types for Some Popular RDBMS

Data types most often used are shown in bold letters

Storage
Data Type Range of Values
Size
Byte 1 byte 0 to 255
Boolean 2 bytes True or False.
Integer 2 bytes -32,768 to 32,767.
Long (long
4 bytes -2,147,483,648 to 2,147,483,647.
integer)
Single (single- -3.402823E38 to -1.401298E-45 for negative
precision 4 bytes values; 1.401298E-45 to 3.402823E38 for
floating-point) positive values.
-1.79769313486232E308 to
Double (double-
-4.94065645841247E-324 for negative values;
precision 8 bytes
4.94065645841247E-324 to
floating-point)
1.79769313486232E308 for positive values.
Currency (scaled -922,337,203,685,477.5808 to
8 bytes
integer) 922,337,203,685,477.5807.
Date 8 bytes January 1, 100 to December 31, 9999.
Object 4 bytes Any Object reference.
10 bytes +
String (variable- 0 to approx. 2 billion (approx. 65,400 for MS
string
length) Windows version 3.1).
length
String (fixed- Length of
1 to approximately 65,400.
length) string
Variant (with
16 bytes Any numeric value up to the range of a Double.
numbers)
22 bytes +
Variant (with
string Same range as for variable-length String.
characters)
length

Oracle supports the following data types:

1. Numeric: BINARY_INTEGER, DEC, DECIMAL, DOUBLE PRECISION,


FLOAT, INT, INTEGER, NATURAL, NATURALN, NUMBER,
NUMERIC, PLS_INTEGER, POSITIVE, POSITIVEN, REAL, SMALLINT
2. Date: DATE (Note: Also stores time.)
3. Character: CHAR, CHARACTER, STRING, VARCHAR, VARCHAR2
4. Others: BOOLEAN, LONG, LONG RAW, RAW

DATA DEFINITION LANGUAGE

DDL is used to define the schema of the database.

1. Create a database schema

 Create, Drop or Alter a table


 Create or Drop an Index
 Define Integrity constraints
 Define access privileges to users
 Define access privileges on objects

NOTE: SQL2 specification supports the creation of multiple schemas per database each
with a distinct owner and authorized users.

2. Creating a Schema

Note: To try out these SQL examples in MS Access, go to the Queries form and choose New,
then choose Design View and then close the next dialog box. Under the View menu, choose
SQL. From this point, you can type in any SQL statement and execute it. Note that MS
Access's DDL syntax is extremely limited. Most of the DDL statements below (including
domains, NOT NULL constraints and referential integrity constraints) are not supported.

3. Creating a Table:

 CREATE TABLE employee (


Last_Name VARCHAR(20) NOT NULL,
First_name VARCHAR(18) NOT NULL,
Soc_Sec VARCHAR(11) NOT NULL,
Date_of_Birth DATE,
Salary NUMBER(8,2) ) ;

 CREATE TABLE dependant (


Last_Name VARCHAR(20) NOT NULL,
First_name VARCHAR(18) NOT NULL,
Soc_Sec VARCHAR(11) NOT NULL,
Date_of_Birth DATE,
Employee_Soc_Sec VARCHAR(11) NOT NULL );

Note: When naming tables, columns and other database objects, do not include spaces in the
names. For example, do not call the last name column: Last Name
If you wish to separate words in a name, use the underscore character.

4. Specifying Primary and Foreign keys:

CREATE TABLE order_header (


order_number NUMBER(10,0) NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10),
PRIMARY KEY (order_number)
);

CREATE TABLE order_items (


order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0),
PRIMARY KEY (order_number, line_item),
FORIEGN KEY (order_number)
REFERENCES order_header (order_number),
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
);

 CREATE INDEX order_index


ON order_header (order_number) ASC ;

 CREATE INDEX items_index


ON order_items (order_number, line_item) ASC ;

Example: CREATE INDEX employee_index


ON employee (ssn) ;

5. Specifying Constraints on Columns and Tables

Constraints on attributes:

 NOT NULL - Attribute may not take a NULL value


 DEFAULT - Store a given default value i no value is specified
 PRIMARY KEY - Indicate which attribute(s) form the primary key
 FOREIGN KEY - Indicate which attribute(s) form a foreign key.
This enforces referential integrity
 UNIQUE - Indicates which attribute(s) must have unique values.

Specify when constraint should be enforced:

I. Immediate
II. Deferrable until commit time

6. Referential Integrity Constraint: Specify the behavior for child tuples when a parent
tuple is modified.

Action to take if referential integrity is violated:

 SET NULL - Child tuples foreign key is set to NULL - Orphans.


 SET DEFAULT - Set the value of the foreign key to some default value.
 CASCADE - Child tuples are updated (or deleted) according to the action take
on the parent tuple.
Examples of ON DELETE and ON UPDATE

 CREATE TABLE order_items (


order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0),
PRIMARY KEY (order_number, line_item),
FORIEGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE,
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
);

Constraints can also be given names so that they can later be modified or dropped
easily.

 CREATE TABLE order_header (


order_number NUMBER(10,0) NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10),
CONSTRAINT pk_order_header
PRIMARY KEY (order_number)
);

 CREATE TABLE order_items (


order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0),

CONSTRAINT pk_order_items
PRIMARY KEY (order_number, line_item),

CONSTRAINT fk1_order_items
FORIEGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE,

CONSTRAINT fk2_order_items
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE
);

An even better approach is to create the tables without constraints and then add them
separately with ALTER TABLE statements

 CREATE TABLE order_header (


order_number NUMBER(10,0) NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10)
);

 ALTER TABLE order_header


ADD CONSTRAINT pk_order_header
PRIMARY KEY (order_number);

 CREATE TABLE order_items (


order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0)
);

 ALTER TABLE order_items ADD


CONSTRAINT pk_order_items
PRIMARY KEY (order_number, line_item) ;

 ALTER TABLE order_items ADD


CONSTRAINT fk1_order_items
FORIEGN KEY (order_number)
REFERENCES order_header (order_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE;
 ALTER TABLE order_items ADD
CONSTRAINT fk2_order_items
FOREIGN KEY (part_number)
REFERENCES parts (part_number)
ON DELETE SET DEFAULT
ON UPDATE CASCADE;

7. Creating indexes on table columns:

 To speed up retrieval of orders given order_number:


CREATE INDEX idx_order_number ON order_header (order_number) ;

 To speed up retrieval of orders given sales person:


CREATE INDEX idx_sales_person ON order_header (sales_person) ;

We give the first part of the index name as "idx" just as a convention.

8. Removing Schema Components with DROP

 DROP SCHEMA schema_name CASCADE


Drop the entire schema including all tables. CASCADE option deletes all data, all
tables, indexes, domains, etc.

 DROP SCHEMA schema_name RESTRICT


Removes the schema only if it is empty.

 DROP TABLE table_name


Remove the table and all of its data.

 DROP TABLE table_name CASCADE


Remove the table and all related tables as specified by FOREIGN KEY constraints.

 DROP TABLE table_name RESTRICT


Remove the table only if it is not referenced (via a FORIEGN KEY constraint) by
other tables.

 DROP INDEX index_name


Removes an index.

 DROP CONSTRAINT table_name.constraint_name


Removes a constraint from a table.
9. Changing Schema Components with ALTER

 Changing Attributes:
ALTER TABLE student ALTER last_name VARCHAR(35);
ALTER TABLE student ALTER gpa DROP DEFAULT
ALTER TABLE student ALTER gpa SET DEFAULT 0.00;

 Adding Attributes:
ALTER TABLE student ADD admission DATE;

 Removing Attributes (not widely implemented):


ALTER TABLE student DROP home_phone;

DATA MANIPULATION LANGUAGE

DDL is used to create and specify the schema. DML is then used to manipulate (select,
insert, update, delete) data.

1. Inserting Data into Tables

General syntax:

INSERT INTO tablename (column1, column2, ... columnX)


VALUES (val1, val2, ... valX);

Examples:

 INSERT INTO employee (first_name, last_name, street, city, state, zip)


VALUES ("Buddy", "Rich", "123 Sticks Ln.", "Fillville", "TN", "31212");

 INSERT INTO stocks (symbol, close_date, close_price)


VALUES ("IBM", "03-JUN-94", 104.25);

 INSERT INTO student_grades (student_id, test_name, score, grade)


VALUES (101, "Quiz 1", 88, "B+");

2. Retrieving Data from Tables with Select

Main way of getting data out of tables is with the SELECT statement.

SELECT syntax:

SELECT column1, column2, ... columnN


FROM tableA, tableB, ... tableZ
WHERE condition1, condition2, ...conditionM
GROUP BY column1, ...
HAVING condition
ORDER BY column1, column2, ... columnN

Assume an employees table:


employees(employee_id, first_name, last_name, street, city, state, zip)
and a "Stocks" table:
stocks(symbol, close_date, close_price)

Some example queries:

 SELECT employee_id, last_name, first_name


FROM employees
WHERE last_name = "Smith"
ORDER BY first_name DESC

 SELECT employee_id, last_name, first_name


FROM employees
WHERE salary > 40000
ORDER BY last_name, first_name DESC

 SELECT *
FROM employees
ORDER BY 2;

 SELECT symbol, close_price


FROM stocks
WHERE close_date > "01-JAN-95" AND
symbol = "IBM"
ORDER BY close_date

 SELECT symbol, close_date, close_price


FROM stocks
WHERE close_date >= "01-JAN-95"
ORDER BY symbol, close_date
RELATIONAL OPERATORS AND SQL

Relational operators each have implementations in SQL.

employee_id, last_name, first_name ( salary > 40000 (EMPLOYEE) )

SELECT employee_id, last_name, first_name


FROM employee
WHERE salary > 40000

AVG (salary) ( state = 'NJ' (EMPLOYEE) )

SELECT AVG(salary)
FROM employee
WHERE state = 'NJ'

last_name = 'Smith' state = 'NY' (EMPLOYEE)

SELECT *
FROM employee
WHERE last_name = 'Smith' AND state = 'NY'

 SQL Built-in Functions

Example Table students:

Name Major Grade


Bill CIS 95
Mary CIS 98
Sue Marketing 88
Tom Finance 92
Alex CIS 79
Sam Marketing 89
Jane Finance 83
...
Note: To try out these examples, create the table in MS Access and enter the data
shown above. Go to the Queries form and choose New, then choose Design View and
then close the next dialog box. Under the View menu, choose SQL.

 Average grade in the class:

SELECT AVG(grade)
FROM students;
Results:
AVG (GRADE)
----------
89.1428571

 Give the name of the student with the highest grade in the class:

This is an example of a subquery

SELECT name, grade


FROM students
WHERE grade =
(SELECT MAX (grade) FROM students);

Results:

NAME GRADE
-------------- -----
Mary 98

 Show the students with the highest grades in each major:

SELECT name, major, grade


FROM students s1
WHERE grade =
(
SELECT max (grade)
FROM students s2
WHERE s1.major = s2.major
)
ORDER BY grade DESC;

Results:

NAME MAJOR GRADE


------------- -------------------- -----
Mary CIS 98
Tom Finance 92
Sam Marketing 89

Note the two aliases given to the students table: s1 and s2. These allow us to refer
to different views of the same table.
SELECTING FROM 2 OR MORE TABLES

In the FROM portion, list all tables separated by commas. Called a Join.

The WHERE part becomes the Join Condition

Example table EMPLOYEE:


Name Department Salary
Joe Finance 50000
Alice Finance 52000
Jill MIS 48000
Jack MIS 32000
Fred Accounting 33000

Example table DEPARTMENTS:


Department Location
Finance NJ
MIS CA
Accounting CA
Marketing NY

 List all of the employees working in California:

SELECT employee.name
FROM employee, department
WHERE employee. department = department. department
AND department. location = 'CA';

Results:
NAME
--------------------------------
Jill
Jack
Fred

 List each employee name and what state (location) they work in. List them in order
of location and name:

SELECT employee.name, department.location


FROM employee, department
WHERE employee. department = department.department
ORDER BY department.location, employee.name;
Results:
NAME LOCATION
--------------- -------------
Fred CA
Jack CA
Jill CA
Alice NJ
Joe NJ

This is similar to a LEFT JOIN.

 List each department and all employees that work there. Show the department and
location even if no employees work there.

SELECT department.department, department.location,


employee.name
FROM employee RIGHT JOIN department
ON employee.department = department.department
ORDER BY department.location, employee.name;

Results:
DEPARTMENT LOCATION NAME
------------- ---------------- ----------------
Accounting CA Fred
MIS CA Jack
MIS CA Jill
Finance NJ Alice
Finance NJ Joe
Marketing NY NULL

 What is the highest paid salary in California ?

SELECT MAX(employee.salary)
FROM employee, department
WHERE employee.department = department.department
AND department.location = 'CA';

Results:
MAX(SALARY)
------------
48000

3. Cartesian Product of the two tables:

SELECT * FROM employee, department;


Results:
Name employee.Department Salary Department.Dep Location
Joe Finance 50000 Finance NJ
Joe Finance 50000 MIS CA
Joe Finance 50000 Accounting CA
Joe Finance 50000 Marketing NY
Alice Finance 52000 Finance NJ
Alice Finance 52000 MIS CA
Alice Finance 52000 Accounting CA
Alice Finance 52000 Marketing NY
Jill MIS 48000 Finance NJ
Jill MIS 48000 MIS CA
Jill MIS 48000 Accounting CA
Jill MIS 48000 Marketing NY
Jack MIS 32000 Finance NJ
Jack MIS 32000 MIS CA
Jack MIS 32000 Accounting CA
Jack MIS 32000 Marketing NY
Fred Accounting 33000 Finance NJ
Fred Accounting 33000 MIS CA
Fred Accounting 33000 Accounting CA
Fred Accounting 33000 Marketing NY

 In which states do our employees work?

SELECT DISTINCT location


FROM department;

 From our Bank Accounts example.

 List the Customer name and their total account holdings:

SELECT customers.LastName, Sum(Balance)


FROM customers, accounts
WHERE customers.CustomerID = accounts.customerid
GROUP BY customers.LastName

Results:

LASTNAME SUM(BALANCE)
--------- ------------
Axe $15,000.00
Builder $1,300.00
Jones $1,000.00
Smith $6,000.00

We can also use a Column Alias to change the title of the columns

SELECT customers.LastName, Sum(Balance) AS TotalBalance


FROM customers, accounts
WHERE customers.CustomerID = accounts.customerid
GROUP BY customers.LastName

Results:

LASTNAME TotalBalance
--------- ------------
Axe $15,000.00
Builder $1,300.00
Jones $1,000.00
Smith $6,000.00

Here is a combination of a function and a column alias:

SELECT name, department,


salary AS CurrentSalary,
(salary * 1.03) AS ProposedRaise
FROM employee;

Results:

name department CurrentSalary ProposedRaise


-------- ------------ ------------- -------------
Alice Finance 52000 53560
Fred Accounting 33000 33990
Jack MIS 32000 32960
Jill MIS 48000 49440
Joe Finance 50000 51500

4. Recursive Queries and Aliases

For example: A student can tutor one or more other students. A student has only one tutor.
STUDENTS (StudentID, Name, Student_TutorID)

StudentID Name Student_TutorID


S101 Bill NULL
S102 Alex S101
S103 Mary S101
S104 Liz S103
S105 Ed S103
S106 Sue S101
S107 Petra S106

Provide a listing of each student and the name of their tutor:

SELECT s1.name AS Student, tutors.name AS Tutor


FROM students s1, students tutors
WHERE s1.student_tutorid = tutors.studentid;

Results:

Student Tutor
---------- ----------
Alex Bill
Mary Bill
Sue Bill
Liz Mary
Ed Mary
Petra Sue

The above is called a "recursive" query because it access the same table two times.

We give the table two aliases called s1 and tutors so that we can compare different aspects of
the same table.

However, as is, the table is missing something: We don't see who is tutoring Bill Smith. Use
LEFT JOIN:

SELECT s1.name AS Student, tutors.name AS Tutor


FROM students s1 LEFT JOIN students tutors
ON s1.student_tutorid = tutors.studentid;

Results:

Student Tutor
---------- ----------
Bill
Alex Bill
Mary Bill
Sue Bill
Liz Mary
Ed Mary
Petra Sue

Here is one more twist: Suppose we were interested in those students who do not tutor
anyone? Use RIGHT JOIN

 How many students does each tutor work with ?

SELECT s1.name AS TutorName,


COUNT(tutors.student_tutorid) AS NumberTutored
FROM students s1, students tutors
WHERE s1.studentid = tutors.student_tutorid
GROUP BY s1.name;

Results:

TutorName NumberTutored
---------- -------------
Bill 3
Mary 2
Sue 1

5. WHERE Clause Expressions

There are a number of expressions one can use in a WHERE clause.

i) Typical Logic expressions:


COLUMN = value

ii) Also: < > = != <= >=

iii) Also consider BETWEEN

SELECT name, grade, "You Got an A"


FROM students
WHERE grade between 91 and 100

iv) Subqueries using = (equals):

SELECT name, grade


FROM students
WHERE grade =
(SELECT MAX(grade) FROM students );
This assumes the subquery returns only one tuple as a result. Typically used for
aggregate functions.

v) Subqueries using IN:

 SELECT name
FROM employee
WHERE department IN ('Finance', 'MIS');

 SELECT name
FROM employee
WHERE department IN
(SELECT department
FROM departments
WHERE location = 'CA');

In the above case, the subquery returns a set of tuples. The IN clause returns
true when a tuple matches a member of the set.

vi) Subqueries using EXISTS:

 SELECT name, salary


FROM employee
WHERE EXISTS
(SELECT name
FROM EMPLOYEE e2
WHERE e2.salary > employee.salary)
AND EXISTS
(SELECT name
FROM EMPLOYEE e3
WHERE e3.salary < employee.salary)

Results:
name salary
----------- ----------
Joe 50000
Jill 48000
Fred 33000

The above query shows all employees names and salaries where there is at least
one person who makes more money (the first exists) and at least one person who
makes less money (second exists).
vii) NOT EXISTS:

 SELECT name, salary


FROM employee
WHERE NOT EXISTS
(SELECT name
FROM EMPLOYEE e2
WHERE e2.salary > employee.salary)

Results:
name salary
--------- ----------
Alice 52000

Above query shows all employees for whom there does not exist an employee
who is paid less.

viii) LIKE operator:

Use the LIKE operator to perform a partial string match. Generally, the %
character is used as the wild card although in some DBMS, the * character is
used.

 Show all employees whose name starts with 'S'

SELECT name, salary


FROM employee
WHERE name LIKE 'S%';

 Show all employees whose name contains the letters 'en'

SELECT name, salary


FROM employee
WHERE name LIKE '%en%';

Note that chatacters within quotes are case sensitive.

 Show all employees whose name contains the letter 'e' and the letter 'n' in that
order:

SELECT name, salary


FROM employee
WHERE name LIKE '%e%n%';
 Show all employees whose name contains the letter 'e' and the letter 'n' in any
order:

SELECT name, salary


FROM employee
WHERE name LIKE '%e%n%' OR
name LIKE '%n%e%';

6. Deleting Tuples with DELETE

DELETE is used to remove tuples from a table.

With no WHERE clause, DELETE will remove all tuples from a table.

 Remove all employees:

DELETE employee;

 Remove only employees making more than $50,000

DELETE employee
WHERE salary > 50000;

 Remove all employees working in California:

DELETE employee
WHERE department IN
(SELECT department
FROM department
WHERE location = 'CA');

DELETE will not be successful if a constraint would be violated. For example, consider
the department attribute in the Employee table as a Foreign Key. Removing a
department would then be contingent upon no employees working in that department.
This is what we call enforcing Referential Integrity

7. Change Values using UPDATE

The UPDATE command is used to change attribute values in the database.

UPDATE uses the SET clause to overwrite the value.


 Change the last name of an Employee:

UPDATE employee
SET last_name = 'Smith'
WHERE employee_id = 'E1001';

 Give an Employee a raise:

UPDATE employee
SET salary = salary * 1.05
WHERE employee_id = 'E1001';

8. DEFINING VIEWS:

It is possible to define a particular view of a table (or tables). For example, if we commonly
access just 2 or 3 columns in a table, we can define a view on that table and then use the view
name when specifying queries.

Assume an employees table:


employees(employee_id, first_name, last_name, street, city, state, zip, department, salary)

 CREATE VIEW emp_address AS


SELECT first_name, last_name, street,
city, state, zip
FROM employee;

 CREATE VIEW emp_salary AS


SELECT first_name, last_name, salary
FROM employee;

 CREATE VIEW avg_sal_dept AS


SELECT department, AVG(salary)
FROM employee
GROUP BY department;

One can then query these views as if they were tables

 SELECT *
FROM emp_address
ORDER BY last_name;

 SELECT *
FROM avg_sal_dept
WHERE department = 'Finance';

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