SQL Queries funda

24
Data A collection of facts from which conclusions may be drawn; In computer science, data is any information in a form suitable for use with a computer. Database A database is a collection of data that is organized so that its contents can easily be accessed, managed, and updated. The most prevalent type of database RDBMS & DBMS RDBMS is a Relational Data Base Management System Relational DBMS. This adds the additional condition that the system supports a tabular structure for the ... A DBMS also has to provide some uniform methods independent of a specific application for accessing the information that is stored. Cardinality In mathematics, the cardinality of a set is a measure of the "number of elements of the set".Cardinality is a facet on a slot on a class. Cardinality represents the exact number of values which should be on that slot for that class. The number of rows in a table or the number of indexed entries in a defined index. Codd's 12 rules Codd's 12 rules are a set of 12 rules proposed by Edgar F. Codd, a pioneer of the relational model for databases, designed to define what is required from a database management system in order for it to be considered relational, i.e., an RDBMS. [1][2] Codd produced these rules as part of a personal campaign to prevent his vision of the relational database being diluted, as database vendors scrambled in the early 1980s to repackage existing products with a relational veneer. Rule 12 was particularly designed to counter such a positioning. In fact,

Transcript of SQL Queries funda

Page 1: SQL Queries funda

Data

A collection of facts from which conclusions may be drawn; In computer science, data is any information in a form suitable for use with a computer.

Database

A database is a collection of data that is organized so that its contents can easily be accessed, managed, and updated. The most prevalent type of database

RDBMS & DBMS

RDBMS is a Relational Data Base Management System Relational DBMS. This adds the additional condition that the system supports a tabular structure for the ...

A DBMS also has to provide some uniform methods independent of a specific application for accessing the information that is stored.

Cardinality

In mathematics, the cardinality of a set is a measure of the "number of elements of the set".Cardinality is a facet on a slot on a class. Cardinality represents the exact number of values which should be on that slot for that class. The number of rows in a table or the number of indexed entries in a defined index.

Codd's 12 rules

Codd's 12 rules are a set of 12 rules proposed by Edgar F. Codd, a pioneer of the

relational model for databases, designed to define what is required from a database

management system in order for it to be considered relational, i.e., an RDBMS. [1][2]

Codd produced these rules as part of a personal campaign to prevent his vision of

the relational database being diluted, as database vendors scrambled in the early

1980s to repackage existing products with a relational veneer. Rule 12 was

particularly designed to counter such a positioning. In fact, the rules are so strict that

all popular so-called "relational" DBMSs fail on many of the criteria

The rules

Rule 000: The system must qualify as relational, as a database, and as a

management system.

Page 2: SQL Queries funda

For a system to qualify as a relational database management system

(RDBMS), that system must use its relational facilities (exclusively) to manage

the database.

Rule 1: The information rule:

All information in the database is to be represented in one and only one way,

namely by values in column positions within rows of tables.

Rule 2: The guaranteed access rule:

All data must be accessible with no ambiguity. This rule is essentially a

restatement of the fundamental requirement for primary keys. It says that

every individual scalar value in the database must be logically addressable by

specifying the name of the containing table, the name of the containing

column and the primary key value of the containing row.

Rule 3: Systematic treatment of null values:

The DBMS must allow each field to remain null (or empty). Specifically, it

must support a representation of "missing information and inapplicable

information" that is systematic, distinct from all regular values (for example,

"distinct from zero or any other number," in the case of numeric values), and

independent of data type. It is also implied that such representations must be

manipulated by the DBMS in a systematic way.

Rule 4: Active online catalog based on the relational model:

The system must support an online, inline, relational catalog that is accessible

to authorized users by means of their regular query language. That is, users

must be able to access the database's structure (catalog) using the same

query language that they use to access the database's data.

Rule 5: The comprehensive data sublanguage rule:

The system must support at least one relational language that

(a) Has a linear syntax

(b) Can be used both interactively and within application programs,

(c) Supports data definition operations (including view definitions), data

manipulation operations (update as well as retrieval), security and integrity

constraints, and transaction management operations (begin, commit, and

rollback).

Page 3: SQL Queries funda

Rule 6: The view updating rule:

All views that are theoretically updatable must be updatable by the system.

Rule 7: High-level insert, update, and delete:

The system must support set-at-a-time insert, update, and delete operators.

This means that data can be retrieved from a relational database in sets

constructed of data from multiple rows and/or multiple tables. This rule states

that insert, update, and delete operations should be supported for any

retrievable set rather than just for a single row in a single table.

Rule 8: Physical data independence:

Changes to the physical level (how the data is stored, whether in arrays or

linked lists etc.) must not require a change to an application based on the

structure.

Rule 9: Logical data independence:

Changes to the logical level (tables, columns, rows, and so on) must not

require a change to an application based on the structure. Logical data

independence is more difficult to achieve than physical data independence.

Rule 10: Integrity independence:

Integrity constraints must be specified separately from application programs

and stored in the catalog. It must be possible to change such constraints as

and when appropriate without unnecessarily affecting existing applications.

Rule 11: Distribution independence:

The distribution of portions of the database to various locations should be

invisible to users of the database. Existing applications should continue to

operate successfully :

(a) when a distributed version of the DBMS is first introduced; and

(b) when existing distributed data are redistributed around the system.

Rule 12: The nonsubversion rule:

If the system provides a low-level (record-at-a-time) interface, then that

interface cannot be used to subvert the system, for example, bypassing a

relational security or integrity constraint.

Page 4: SQL Queries funda

Some of Oracle's tools to access the database and create programs are:

SQL*Plus has a command line interface. With it, you can access the database and write stored procedures, you can run SQL commands to retrieve data and you can run scripts of either SQL, PL/SQL or built-in SQL*Plus commands, or a mixture of those three things.

Oracle Developer is a 4GL GUI application Builder. With Developer, you can create forms, reports, and graphics. Oracle*Forms and Oracle*Reports are two components of Oracle Developer. Earlier versions created client-server applications, but the more recent versions create web applications that run under the Oracle Application Server (OAS). OAS is a web-based application server sold by Oracle. OAS is licensed separately and is very expensive (as are its closed source competitors). The current version is OAS 10g.

HTML DB is a fairly new application builder geared toward web development (added to the DB with release 9iR2). HTML DB does not need an application server. This tool runs from the database and can be presented to the web using the Apache web server that comes with the database. Since this is not an additional license, it provides a cheaper way to develop applications. Developer is a feature-rich thick client with all of the normal GUI widgets. HTML DB is HTML-based and is very thin and limited to the HTML provided widgets.

Oracle Enterprise Manager (OEM) is the Enterprise GUI tool to manage the database. From this tool, you can perform any action in the database that is required. This tool is primarily used for administration but can also be provided to developers for application tuning and monitoring. In Oracle 10g, OEM also provides Grid control.

What is SQL, how is it pronounced, and where did it come from?

SQL is the acronym for Structured Query Language. It is a data retrieval and manipulation language.

It is usually pronounced as "es-que-el" or "sequel". I pronounce it both ways and my ears don't even notice a difference anymore.

SQL came from Dr. EF Codd in the late 60's and was embraced by scientists at IBM including RF Boyce (ever heard of Boyce-Codd Normal Form (BCNF)?).

Though IBM (as it has done with most computer technology) was a heavy lifter making SQL a workable language, it was not the first to really exploit it (as with most of its computer technology).

No, it was good old Oracle that released the first commercial product based on SQL. And, since Oracle's earliest customer was the U.S. Government, the popularity of SQL and Oracle was secured.

Standard SQL is characterized by its ease of use and great power in basic operations.

Because it does not really excel at advanced analytics, each vendor invariably creates its own extensions to ANSI SQL. Oracle is no exception. Where, in some technologies, being

Page 5: SQL Queries funda

100% ANSI or ISO compliant can be a good thing, it's usually not in the world of RDBMS's.

This is largely because of the architectural differences of the various RDBMS platforms.

Why use SQL?

It is the most powerful and flexible tool available for dealing with databases.

Why do some people hate SQL?

Because they are (lazy?)...(stupid?)... it's hard to find a nice word, but I'll say they are just ignorant.

Many developers think SQL is universal or at least should be. They understand perfectly that you can't take VB code and get a Java compiler to compile it, but they don't understand that 2 databases can have even slight variations. As a result, they try to keep their DATABASE application code DATABASE agnostic and then say a lot of silly things like "Oracle sucks."

We'll discuss re-educating developers (they want to succeed as much as you do) later. In the next few posts, we'll go over how to use SQL and how Oracle handles it.

How runs. (PROCESS)

-Translate the statement and verify the syntax is valid-check the data dictionary and make sure the referenced objects exist-get parsing locks on all required objects so the definitions don't change-check and make sure the executing user has privileges to the objects-figure out the best way (execution plan) to perform the request-load all this into a shared SQL area so others won't have to get this far-(route distributed statements)

There are 3 things Oracle needs to know from your statment in order to run:

What Where (don't confuse with WHERE-clause) When (because the WHERE-clause goes here)

like

do something over there when it's 3:00 or delete from employees where term_date >sysdate-712;

WHAT

What do you want your statement to do? The basic options are

SELECT ____ -- return some data [SELECT col1 FROM tab1;] If you want more than one

Page 6: SQL Queries funda

column, just list them and seperate them with a comma.

UPDATE -- change some data [UPDATE tab1 SET col1='a';]

INSERT -- add some data [INSERT INTO tab1 (col1, col2, col4) VALUES ('b',1,sysdate);]

DELETE --remove some data [DELETE FROM tab1;] *this would delete everything

(from) WHERE

Where to do WHAT from above. If there is more than one place (table) involved, just list them and seperate them with a comma.

See the use of tab1 above.

WHEN

This is an optional piece that contains the conditional logic you want to use. It is the WHERE-Clause. In most cases, you are making a big mistake by not using this optional piece. We will see how important the WHERE-Clause is soon, especially when we discuss indexes.

In this statement

delete from employees where term_date <sysdate-712;

the where-clause says ONLY delete data older than two years.

Course Outline.

Writing Basic SQL Select Statements [  ] List the capabilities of SQL SELECT

statements [  ] Execute a basic SELECT statement [  ] Differentiate between SQL

statements and iSQL*Plus commands

Restricting and Sorting Data [  ] Limit the rows retrieved by a query [  ] Sort the rows retrieved by a query

Single-Row Functions [  ] Describe various types of functions

available in SQL [  ] Use character, number, and date

functions in SELECT statements [  ] Use conversion functions

Subqueries [  ] Describe the types of problems that

subqueries can solve [  ] Define subqueries [  ] List the types of subqueries [  ] Write single-row and multiple-row

subqueries

Producing Readable Output with iSQL*Plus [  ] Produce queries that require a

substitution variable [  ] Produce more readable output [  ] Create and execute script files

Manipulating Data [  ] Describe each DML statement [  ] Insert rows into a table [  ] Update rows in a table [  ] Delete rows from a table

Creating Views [  ] Describe a view [  ] Create, alter the definition, and drop

a view [  ] Retrieve data through a view [  ] Insert, update and delete data

through a view

Creating Other Database Objects [  ] Create, maintain and use sequences [  ] Create and maintain indexes [  ] Create private and public synonyms

Page 7: SQL Queries funda

Displaying Data from Multiple Tables [  ] Write SELECT statements to access

data from more than one table using equality and nonequality joins

[  ] View data that generally does not meet a join condition by using outer joins

[  ] Join a table to itself using a self-join

Aggregating Data using Group Functions [  ] Identify the available group functions [  ] Use group functions [  ] Group data using the GROUP BY

clause [  ] Include or exclude grouped rows by

using the HAVING clause

[  ] Merge rows in a table [  ] Control transactions

Creating and Managing Tables [  ] Describe the main database objects [  ] Create tables [  ] Describe the datatypes that can be

used when specifying column definition

[  ] Alter table definitions [  ] Drop, rename and truncate tables

Including Constraints [  ] Describe constraints [  ] Create and maintain constraints

SELECT

Purpose

Use a SELECT statement or subquery to retrieve data from one or more tables, object tables,

views, object views, or materialized views.

If part or all of the result of a SELECT statement is equivalent to an existing materialized view,

then Oracle Database may use the materialized view in place of one or more tables specified in

the SELECT statement. This substitution is called query rewrite. It takes place only if cost

optimization is enabled and the QUERY_REWRITE_ENABLED parameter is set to TRUE. To determine

whether query write has occurred, use the EXPLAIN PLAN statement.

See Also:

Chapter 9, "SQL Queries and Subqueries" for general information on queries and subqueries

Oracle Database Data Warehousing Guide for more information on materialized views and query rewrite

EXPLAIN PLAN

Additional Topics

Page 8: SQL Queries funda

Prerequisites Syntax

Semantics

Examples

Prerequisites

For you to select data from a table or materialized view, the table or materialized view must be in

your own schema or you must have the SELECT privilege on the table or materialized view.

For you to select rows from the base tables of a view:

You must have the SELECT privilege on the view, and Whoever owns the schema containing the view must have the SELECT privilege on the

base tables.

The SELECT ANY TABLE system privilege also allows you to select data from any table or any

materialized view or the base table of any view.

To issue an Oracle Flashback Query using the flashback_query_clause, you must have

the SELECT privilege on the objects in the select list. In addition, either you must have

FLASHBACK object privilege on the objects in the select list, or you must have FLASHBACK ANY

TABLE system privilege.

Syntax

select::=

Description of the illustration select.gif

(for_update_clause ::= )

subquery::=

Page 15: SQL Queries funda

Description of the illustration model_clause.gif

(cell_reference_options ::= , return_rows_clause ::= , reference_model ::= , main_model ::= )

cell_reference_options::=

Description of the illustration cell_reference_options.gif

return_rows_clause::=

Description of the illustration return_rows_clause.gif

reference_model::=

Description of the illustration reference_model.gif

(model_column_clauses ::= , cell_reference_options ::= )

main_model::=

Description of the illustration main_model.gif

(model_column_clauses ::= , cell_reference_options ::= , model_rules_clause ::= )

model_column_clauses::=

Page 18: SQL Queries funda

Description of the illustration order_by_clause.gif

for_update_clause ::=

Description of the illustration for_update_clause.gif

Semantics

subquery_factoring_clause

The WITH query_name clause lets you assign a name to a subquery block. You can then

reference the subquery block multiple places in the query by specifying the query name. Oracle

Database optimizes the query by treating the query name as either an inline view or as a

temporary table.

You can specify this clause in any top-level SELECT statement and in most types of subqueries.

The query name is visible to the main query and to all subsequent subqueries except the

subquery that defines the query name itself.

Restrictions on Subquery Factoring This clause is subject to the following restrictions:

You can specify only one subquery_factoring_clause in a single SQL statement. You cannot specify a query_name in its own subquery. However, any query_name defined in the subquery_factoring_clause can be used in any subsequent named query block in the subquery_factoring_clause.

Page 19: SQL Queries funda

In a compound query with set operators, you cannot use the query_name for any of the component queries, but you can use the query_name in the FROM clause of any of the component queries.

See Also:

Oracle Database Concepts for information about inline views Oracle Database Data Warehousing Guide and Oracle Database

Application Developer's Guide - Fundamentals for information on using the subquery factoring feature

"Subquery Factoring: Example"

ALL

Specify ALL if you want the database to return all rows selected, including all copies of duplicates. The default is ALL.

* (asterisk)

Specify the asterisk to select all columns from all tables, views, or materialized views listed in the FROM clause.

If you are selecting from a table rather than from a view or a materialized view, then columns that have been marked as UNUSED by the ALTER TABLE SET UNUSED statement are not selected.

http://youngcow.net/doc/oracle10g/server.102/b14200/statements_10002.htm

Page 20: SQL Queries funda

order_by_clause

Use the order_by_clause to specify how data is ordered within a partition. For all analytic

functions except PERCENTILE_CONT and PERCENTILE_DISC (which take only a single key), you

can order the values in a partition on multiple keys, each defined by a value_expr and each

qualified by an ordering sequence.

Within each function, you can specify multiple ordering expressions. Doing so is especially

useful when using functions that rank values, because the second expression can resolve ties

between identical values for the first expression.

Whenever the order_by_clause results in identical values for multiple rows, the function

returns the same result for each of those rows. Please refer to the analytic example for SUM for

an illustration of this behavior.

Restriction on the ORDER BY Clause

When used in an analytic function, the order_by_clause must take an expression (expr). The

SIBLINGS keyword is not valid (it is relevant only in hierarchical queries). Position (position)

and column aliases (c_alias) are also invalid. Otherwise this order_by_clause is the same as

that used to order the overall query or subquery.

Page 21: SQL Queries funda

ASC | DESC

Specify the ordering sequence (ascending or descending). ASC is the default.

NULLS FIRST | NULLS LAST

Specify whether returned rows containing nulls should appear first or last in the ordering

sequence.

NULLS LAST is the default for ascending order, and NULLS FIRST is the default for descending

order.

Analytic functions always operate on rows in the order specified in the order_by_clause of the

function. However, the order_by_clause of the function does not guarantee the order of the

result. Use the order_by_clause of the query to guarantee the final result ordering