Pages

Powered By Blogger

Saturday, 2 November 2013

How to Download 10th Class Marks Memo?

Are you lost 10th Class Certificate? Don't Worry


10th Class Marks memo is very important document for students in India. It acts as proof for Date of Birth in various occasions. So we need to store this marks memo in safe place.

Sometimes we may lost this valuable document. In such a situation no need to worry about it. You can download this 10th standard marks memo from Board of Secondary Education website by following this video tutorial.

Must and Should you have 

Hall Ticket Number
Date of Birth 
Year of Examination.

Simple way download 10th class marks memo.

Click This Link  http://182.72.241.154/sscht/sscresultsdetails.aspx

Download Marks Memo

Friday, 19 July 2013

Disable a foreign key

The syntax for disabling a foreign key is:

ALTER TABLE table_name
disable CONSTRAINT constraint_name;

For example:

If you had created a foreign key as follows:

CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY
(supplier_id)
);

CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

In this example, we've created a primary key on the supplier table called supplier_pk. It
consists of only one field - the supplier_id field. Then we've created a foreign key called
fk_supplier on the products table that references the supplier table based on the
supplier_id field.

If we then wanted to disable the foreign key called fk_supplier, we could execute the
following command:


ALTER TABLE products
disable CONSTRAINT fk_supplier;

Download FOREIGNKEYDISABLE.pdf

FOR (NESTED) - 2ND

P21.WRITE A PROGRAM TO PRINT THE FOLLOWING DESIGN:

~~~~1
~~~121
~~12321
~1234321
123454321


SQL> set serveroutput on;
SQL> Declare
i number;
j number;
n number;
k number;
m number;
Begin
n := #
for i in 1..n loop
for j in 1..n-i loop
dbms_output.put('~');
end loop;
for k in 1..i loop
dbms_output.put(k);
end loop;
for k in reverse 1..i-1 loop
dbms_output.put(k);
end loop;
dbms_output.put_line(' ');
end loop;
end;
/

Enter value for num: 6
old 8: n := #
new 8: n := 6;


~~~~~1
~~~~121
~~~12321
~~1234321
~123454321
12345654321


PL/SQL procedure successfully completed.


P22.WRITE A PROGRAM TO PRINT THE FOLLOWING DESIGN:

~~~~~~~~1
~~~~~~~121
~~~~~~12321
~~~~~1234321
~~~~123454321
~~~12345654321
~~1234567654321
~123456787654321
12345678987654321
~123456787654321
~~1234567654321
~~~12345654321
~~~~123454321
~~~~~1234321
~~~~~~12321
~~~~~~~121
~~~~~~~~1


Declare
i number ;
j number;
n number;
k number;
m number;
Begin
n := &n;
for i in 1..n loop
for j in 1..n-i loop
dbms_output.put('~');
end loop;
for k in 1..i loop
dbms_output.put(k);
end loop;
for k in reverse 1..i-1 loop
dbms_output.put(k);
end loop;
dbms_output.put_line(' ');
end loop;
for i in reverse 1..n-1 loop
for j in 1..n-i loop
dbms_output.put('~');
end loop;
for k in 1..i loop
dbms_output.put(k);
end loop;
for k in reverse 1..i-1 loop
dbms_output.put(k);
end loop;
dbms_output.put_line(' ');
end loop;
end;

Enter value for n: 5
old 8: n:=&n;
new 8: n:=5;


~~~~~~~~1
~~~~~~~121
~~~~~~12321
~~~~~1234321
~~~~123454321
~~~12345654321
~~1234567654321
~123456787654321
12345678987654321
~123456787654321
~~1234567654321
~~~12345654321
~~~~123454321
~~~~~1234321
~~~~~~12321
~~~~~~~121
~~~~~~~~1


PL/SQL procedure successfully completed.


Download FOR_NESTED-2ND.pdf

FOR (NESTED)

P18.WRITE A PROGRAM TO PRINT THE FOLLOWING DESIGN.

1
12
123
1234
12345


Declare
i number ;
j number;
n number;
Begin
n := &n;
for i in 1..n loop
for j in 1..i loop
dbms_output.put(j);
end loop;
dbms_output.put_line(' ');
end loop;
end;
/

Enter value for n: 5
old 6: n:=&n;
new 6: n:=5;


P19. WRITE A PROGRAM TO DISPLAY NUMBERS OF THE FORM

0 0 0 0 0
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25


SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
I NUMBER;
J NUMBER ;
K NUMBER;
BEGIN
FOR I IN 0 .. 5 LOOP
FOR J IN 1..5 LOOP
K := I*J;
DBMS_OUTPUT.PUT(K || ' ');
END LOOP;
DBMS_OUTPUT. PUT_LINE (' ');
END LOOP;
END;
/

0 0 0 0 0
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25


PL/SQL procedure successfully completed.

P20. WRITE A PL/SQL CODE TO ACCEPT THE TEXT AND
REVERSE THE GIVEN TEXT. AND CHECK THE TEXT IS PALINDROME OR NOT.


SQL> DECLARE
G varchar(20);
R varchar(20);
Begin
G := '&g';
dbms_output.put_line('THE GIVEN TEXT : '|| G);
for i in REVERSE 1.. Length (G) loop
R := R || substr(G,i,1);
end loop;
dbms_output.put_line('THE REVERSED TEXT : '||R);
IF R=G THEN
dbms_output.put_line('THE GIVEN TEXT IS PALINDROME ');
ELSE
dbms_output.put_line('THE GIVEN TEXT IS NOT PALINDROME ');
END IF;
end;
/

Enter value for g: hello
old 5: G := '&g';
new 5: G := 'hello';
THE GIVEN TEXT : hello
THE REVERSED TEXT : olleh
THE GIVEN TEXT IS NOT PALINDROME
PL/SQL procedure successfully completed.


SQL> /

Enter value for g: malayalam
old 5: G := '&g';
new 5: G := 'malayalam';
THE GIVEN TEXT : malayalam
THE REVERSED TEXT : malayalam
THE GIVEN TEXT IS PALINDROME
PL/SQL procedure successfully completed.


Download FOR_NESTED.pdf

FOR

P14. WRITE A PROGRAM TO PRINT THE MULTIPLICATION TABLE OF A
GIVEN NO:

SQL> Declare
r number;
no number;
Begin
no:=&NO;
r := &Range;
FOR I IN 1..r LOOP
dbms_output.put_line(no||' X '|| i || ' = ' ||i*no);
end loop;
end;
/

Enter value for no: 5
old 5: no:=&NO;
new 5: no:=5;

Enter value for range: 5
old 6: r := &Range;
new 6: r := 5;
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
PL/SQL procedure successfully completed.


P15. WRITE A PROGRAM TO GENERATE EVEN NUMBERS FROM GIVEN RANGE (1 TO N),
AND FIND ITS SUM.


SQL> declare
i number(5);
n number(5);
v number(5);
s number(5):=0;
Begin
n := &Range;
for i in 1 .. n/2 loop
v := i*2;
s := s+v;
dbms_output.put_line(v);
end loop;
dbms_output.put_line('The sum of Even Numbers from 1 to '||n||' = ' ||s);
end;
/

Enter value for range: 10
old 7: n := &Range;
new 7: n := 10;
2
4
6
8
10
The sum of Even Numbers from 1 to 10 = 30
PL/SQL procedure successfully completed.


P16. WRITE A PROGRAM TO GENERATE FIRST 10 TERMS OF THE
FIBONACCI SERIES.


SQL> declare
a number:= 0 ;
b number:= 1;
c number;
begin
dbms_output.put('The series : ');
dbms_output.put(a||' '||b||' ');
for i in 3..10 loop
c := a + b;
dbms_output.put(c||' ');
a := b;
b := c;
end loop;
dbms_output.put_line(' ');
end;
/

The series : 0 1 1 2 3 5 8 13 21 34
PL/SQL procedure successfully completed.


P17.WRITE A PROGRAM TO FIND THE FACTORIAL OF A NUMBER.

Declare
n number(2);
i number(2);
f number(5):=1;
Begin
n :=&n;
for i in 1..n loop
f := f * i;
end loop;
dbms_output.put_line(' The factorial value = '||f);
end;

Enter value for n: 5
old 6: n:=&n;
new 6: n:=5;
The factorial value = 120


DOWNLOAD FOR.pdf

FOR Loop

The following example uses a simple FOR loop to insert ten rows into a database table.
The values of a loop index, counter variable, and either of two character strings are
inserted. Which string is inserted depends on the value of the loop index.

PL/SQL Block

DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN -- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;

Output Table

SQL> SELECT * FROM temp ORDER BY col1;

NUM_COL1 NUM_COL2 CHAR_COL
--------   --------     ---------
1             100      i is odd
2             200      i is even
3             300      i is odd
4             400      i is even
5             500      i is odd
6            600       i is even
7            700       i is odd
8            800       i is even
9            900       i is odd
10          1000     i is even

Sample 2. Cursors

The following example uses a cursor to select the five highest paid employees from the
emp table.

Input Table

SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;

ENAME            EMPNO           SAL
----------            ---------             --------
KING                  7839              5000
SCOTT               7788              3000
FORD                 7902              3000
JONES               7566               2975
BLAKE               7698              2850
CLARK               7782              2450
ALLEN               7499              1600
TURNER            7844              1500
MILLER             7934              1300
WARD                7521              1250
MARTIN            7654              1250
ADAMS             7876               1100
JAMES              7900                950
SMITH               7369               800

PL/SQL Block

DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC; -- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal NUMBER(7,2);
BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND;
INSERT INTO temp VALUES (my_sal, my_empno, my_ename);
COMMIT;
END LOOP;
CLOSE c1;
END;

Output Table

SQL> SELECT * FROM temp ORDER BY col1 DESC;

NUM_COL1    NUM_COL2    CHAR_COL
--------                    --------              --------
5000                        7839                   KING
3000                        7902                   FORD
3000                        7788                   SCOTT
2975                        7566                   JONES
2850                        7698                   BLAKE

Sample 3. Scoping

The following example illustrates block structure and scope rules. An outer block
declares two variables named x and counter and loops four times. Inside this loop is a
sub-block that also declares a variable named x. The values inserted into the temp table
show that the two x's are indeed different.

PL/SQL Block

DECLARE
x NUMBER := 0;
counter NUMBER := 0;

BEGIN
FOR i IN 1..4 LOOP
x := x + 1000;
counter := counter + 1;
INSERT INTO temp VALUES (x, counter, 'in OUTER loop');
DECLARE
x NUMBER := 0; -- this is a local version of x
BEGIN
FOR i IN 1..4 LOOP
x := x + 1; -- this increments the local x
counter := counter + 1;
INSERT INTO temp VALUES (x, counter, 'inner loop');
END LOOP;
END;
END LOOP;
COMMIT;
END;

Output Table
SQL> SELECT * FROM temp ORDER BY col2;

NUM_COL1  NUM_COL2  CHAR_COL
--------             --------               -------------
1000                    1                 in OUTER loop
1                          2                 inner loop
2                          3                 inner loop
3                         4                  inner loop
4                         5                   inner loop
2000                   6                   in OUTER loop

Download FORLOOP.pdf

EXISTS Condition

The EXISTS condition is considered "to be met" if the subquery returns at least one row.

The syntax for the EXISTS condition is:

SELECT columns
FROM tables
WHERE EXISTS ( subquery );

The EXISTS condition can be used in any valid SQL statement - select, insert, update, or
delete.

Example #1

Let's take a look at a simple example. The following is an SQL statement that uses the
EXISTS condition:

SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);

This select statement will return all records from the suppliers table where there is at least
one record in the orders table with the same supplier_id.

Example #2 - NOT EXISTS

The EXISTS condition can also be combined with the NOT operator.

For example,

SELECT *
FROM suppliers
WHERE not exists (select * from orders Where suppliers.supplier_id =
orders.supplier_id);

This will return all records from the suppliers table where there are no records in the
orders table for the given supplier_id.

Example #3 - DELETE Statement

The following is an example of a delete statement that utilizes the EXISTS condition:

DELETE FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);

Example #4 - UPDATE Statement

The following is an example of an update statement that utilizes the EXISTS condition:

UPDATE suppliers
SET supplier_name
=
( SELECT customers.name
FROM customers
WHERE customers.customer_id =
suppliers.supplier_id)
WHERE EXISTS
( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);

Example #5 - INSERT Statement

The following is an example of an insert statement that utilizes the EXISTS condition:

INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT account_no, name
FROM suppliers
WHERE exists (select * from orders Where suppliers.supplier_id = orders.supplier_id);

Download EXISTSCondition.pdf

Wednesday, 17 July 2013

Named System Exceptions

Named system exceptions are exceptions that have been given names by PL/SQL. They
are named in the STANDARD package in PL/SQL and do not need to be defined by the
programmer.

The syntax for the Named System Exception in a procedure is:

CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section

EXCEPTION
WHEN exception_name1 THEN
[statements]

WHEN exception_name2 THEN
[statements]

WHEN exception_name_n THEN
[statements]

WHEN OTHERS THEN
[statements]

END [procedure_name];

The syntax for the Named System Exception in a function is:

CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section

EXCEPTION
WHEN exception_name1 THEN
[statements]

WHEN exception_name2 THEN
[statements]

WHEN exception_name_n THEN
[statements]

WHEN OTHERS THEN
[statements]

END [function_name];

Here is an example of a procedure that uses a Named System Exception:

CREATE OR REPLACE PROCEDURE add_new_supplier
(supplier_id_in IN NUMBER, supplier_name_in IN VARCHAR2)
IS

BEGIN
INSERT INTO suppliers (supplier_id, supplier_name )
VALUES ( supplier_id_in, supplier_name_in );

EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
raise_application_error (-20001,'You have tried to insert a duplicate supplier_id.');

WHEN OTHERS THEN
raise_application_error (-20002,'An error has occurred inserting a supplier.');

END;

In this example, we are trapping the Named System Exception called
DUP_VAL_ON_INDEX. We are also using the WHEN OTHERS clause to trap all
remaining exceptions.

Download EXCEPTIONNAMED_SYSTEM.pdf

WHEN OTHERS Clause

The WHEN OTHERS clause is used to trap all remaining exceptions that have not been
handled by your Named System Exceptions and Named Programmer-Defined
Exceptions.

The syntax for the WHEN OTHERS clause in a procedure is:

CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section

EXCEPTION
WHEN exception_name1 THEN
[statements]

WHEN exception_name2 THEN
[statements]

WHEN exception_name_n THEN
[statements]

WHEN OTHERS THEN
[statements]

END [procedure_name];

The syntax for the WHEN OTHERS clause in a function is:

CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section

EXCEPTION
WHEN exception_name1 THEN
[statements]

WHEN exception_name2 THEN
[statements]

WHEN exception_name_n THEN
[statements]

WHEN OTHERS THEN
[statements]

END [function_name];

Here is an example of a procedure that uses a WHEN OTHERS clause:

CREATE OR REPLACE PROCEDURE add_new_order
(order_id_in IN NUMBER, sales_in IN NUMBER)
IS
no_sales EXCEPTION;

BEGIN
IF sales_in = 0 THEN
RAISE no_sales;

ELSE
INSERT INTO orders (order_id, total_sales )
VALUES ( order_id_in, sales_in );
END IF;

EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
raise_application_error (-20001,'You have tried to insert a duplicate order_id.');

WHEN no_sales THEN
raise_application_error (-20001,'You must have sales in order to submit the order.');

WHEN OTHERS THEN
raise_application_error (-20002,'An error has occurred inserting an order.');

END;

In this example, if an exception is encountered that is not a DUP_VAL_ON_INDEX or a
no_sales, it will be trapped by the WHEN OTHERS clause.

Frequently Asked Questions

Question: Is there any way to get the ORA error number (and/or description) for the
errors that will fall into OTHERS?

Something like:

WHEN OTHERS THEN
'Error number ' & Err.Number& ' has happen.'

Answer: Yes, you can use SQLCODE function to retrieve the error number and
SQLERRM function to retrieve the error message.

For example, you could raise the error as follows:

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;

Or you could log the error to a table as follows:


EXCEPTION
WHEN OTHERS THEN
err_code := SQLCODE;
err_msg := substr(SQLERRM, 1, 200);

INSERT INTO audit_table (error_number, error_message)
VALUES (err_code, err_msg);
END;

Download EXCEPTIONOTHERCLAUSEWHENOTHERSClause.pdf

DROP TABLE Statement

The DROP TABLE statement allows you to remove a table from the database.

The basic syntax for the DROP TABLE statement is:

DROP TABLE table_name;





For example:

DROP TABLE supplier;

This would drop table called supplier.

Download DROPTABLEStatement.pdf

Drop a foreign key

The syntax for dropping a foreign key is:

ALTER TABLE table_name
drop CONSTRAINT constraint_name;

For example:

If you had created a foreign key as follows:

CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY
(supplier_id)
);

CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

In this example, we've created a primary key on the supplier table called supplier_pk. It
consists of only one field - the supplier_id field. Then we've created a foreign key called
fk_supplier on the products table that references the supplier table based on the
supplier_id field.

If we then wanted to drop the foreign key called fk_supplier, we could execute the
following command:

ALTER TABLE products
drop CONSTRAINT fk_supplier;

Download Dropaforeignkey.pdf.html

DISTINCT Clause



The DISTINCT clause allows you to remove duplicates from the result set. The
DISTINCT clause can only be used with select statements.

The syntax for the DISTINCT clause is:

SELECT DISTINCT columns
FROM tables
WHERE predicates;

Example #1

Let's take a look at a very simple example.

SELECT DISTINCT city
FROM suppliers;

This SQL statement would return all unique cities from the suppliers table.

Example #2

The DISTINCT clause can be used with more than one field.

For example:

SELECT DISTINCT city, state
FROM suppliers;

This select statement would return each unique city and state combination. In this case,
the distinct applies to each field listed after the DISTINCT keyword.
 















Friday, 5 July 2013

Disable a foreign key

The syntax for disabling a foreign key is:

ALTER TABLE table_name
disable CONSTRAINT constraint_name;

For example:

If you had created a foreign key as follows:

CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY
(supplier_id)
);

CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

In this example, we've created a primary key on the supplier table called supplier_pk. It
consists of only one field - the supplier_id field. Then we've created a foreign key called
fk_supplier on the products table that references the supplier table based on the
supplier_id field.

If we then wanted to disable the foreign key called fk_supplier, we could execute the
following command:

ALTER TABLE products
disable CONSTRAINT fk_supplier;

Download Disableaforeignkey.pdf.html

DELETE Statement

The DELETE statement allows you to delete a single record or multiple records from a
table.

The syntax for the DELETE statement is:

DELETE FROM table
WHERE predicates;

Example #1 - Simple example

Let's take a look at a simple example:

DELETE FROM suppliers
WHERE supplier_name = 'IBM';

This would delete all records from the suppliers table where the supplier_name is IBM.

You may wish to check for the number of rows that will be deleted. You can determine
the number of rows that will be deleted by running the following SQL statement before
performing the delete.

SELECT count(*)
FROM suppliers
WHERE supplier_name = 'IBM';

Example #2 - More complex example

You can also perform more complicated deletes.

You may wish to delete records in one table based on values in another table. Since you
can't list more than one table in the FROM clause when you are performing a delete, you
can use the EXISTS clause.

For example:

DELETE FROM suppliers
WHERE EXISTS
( select customers.name
from customers
where customers.customer_id = suppliers.supplier_id
and customers.customer_name = 'IBM' );

This would delete all records in the suppliers table where there is a record in the
customers table whose name is IBM, and the customer_id is the same as the supplier_id.

If you wish to determine the number of rows that will be deleted, you can run the
following SQL statement before performing the delete.

SELECT count(*) FROM suppliers
WHERE EXISTS
( select customers.name
from customers
where customers.customer_id = suppliers.supplier_id
and customers.customer_name = 'IBM' );

Frequently Asked Questions

Question: How would I write an SQL statement to delete all records in TableA whose
data in field1 & field2 DO NOT match the data in fieldx & fieldz of TableB?

Answer: You could try something like this:

DELETE FROM TableA
WHERE NOT EXISTS
( select *
from TableB
where TableA .field1 = TableB.fieldx
and TableA .field2 = TableB.fieldz );

Download DELETEStatement.pdf.html

Procedure with cursor

Question: In Oracle, I have a table called "wine" and a stored procedure that outputs a
cursor based on the "wine" table.

I've created an HTML Form where the user can enter any combination of three values to
retrieve results from the "wine" table. My problem is that I need a general "select"
statement that will work no matter what value(s), the user enters.

Example:

parameter_1= "Chianti"
parameter_2= "10"
parameter_3= wasn't entered by the user but I have to use in the select statement. And
this is my problem. How to initialize this parameter to get all rows for column3?

SELECT * FROM wine
WHERE column1 = parameter_1
AND column2 = parameter_2
AND column3 = parameter_3;.

The output of my stored procedure must be a cursor.

Answer: To solve your problem, you will need to output a dynamic PLSQL cursor in
Oracle.

Let's take a look at how we can do this. We've divided this process into 3 steps.

Step 1 - Table Definition

First, we need a table created in Oracle called "wine". Below is the create statement for
the wine table.

create table wine
( col1 varchar2(40),
col2 varchar2(40),
col3 varchar2(40)
);

We've made this table definition very simple, for demonstration purposes.

Step 2 - Create package

Next, we've created a package called "winepkg" that contains our cursor definition. This
needs to be done so that we can use a cursor as an output parameter in our stored
procedure.

create or replace PACKAGE winepkg
IS
/* Define the REF CURSOR type. */
TYPE wine_type IS REF CURSOR RETURN wine%ROWTYPE;
END winepkg;

This cursor will accept all fields from the "wine" table.

Step 3 - Create stored procedure

Our final step is to create a stored procedure to return the cursor. It accepts three
parameters (entered by the user on the HTML Form) and returns a cursor (c1) of type
"wine_type" which was declared in Step 2.

The procedure will determine the appropriate cursor to return, based on the value(s) that
have been entered by the user (input parameters).

create or replace procedure find_wine2
(col1_in in varchar2,
col2_in in varchar2,
col3_in in varchar2,
c1 out winepkg.wine_type)
as

BEGIN

/* all columns were entered */
IF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) > 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col1 = col1_in
and wine.col2 = col2_in
and wine.col3 = col3_in;

/* col1 and col2 were entered */
ELSIF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) = 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col1 = col1_in
and wine.col2 = col2_in;

/* col1 and col3 were entered */
ELSIF (length(col1_in) > 0) and (length(col2_in) = 0) and (length(col3_in) > 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col1 = col1_in
and wine.col3 = col3_in;

/* col2 and col3 where entered */
ELSIF (length(col1_in) = 0) and (length(col2_in) > 0) and (length(col3_in) > 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col2 = col2_in
and wine.col3 = col3_in;

/* col1 was entered */
ELSIF (length(col1_in) > 0) and (length(col2_in) = 0) and (length(col3_in) = 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col1 = col1_in;

/* col2 was entered */
ELSIF (length(col1_in) = 0) and (length(col2_in) > 0) and (length(col3_in) = 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col2 = col2_in;

/* col3 was entered */
ELSIF (length(col1_in) = 0) and (length(col2_in) = 0) and (length(col3_in) > 0)
THEN
OPEN c1 FOR
select *
from wine
where wine.col3 = col3_in;

END IF;

END find_wine2;

Download CURSOR_WITHPROCEDURE.pdf.html

Cursor with variable

Question: I'm trying to use a variable in an IN CLAUSE.

Assumptions & declarations:

1. Ref_cursor is of type REF CURSOR declared in Package
2. I will to pass a comma separated Numbers as a string
3. This should be used in the query in the IN Clause
4. Execute the Query and Return the Output as REF Cursor

Something similar to the following:

Create or Replace Function func_name (inNumbers in Varchar2)
Return PackageName.ref_cursor
As
out_cursor PackageName.Ref_cursor;

Begin
Open out_cursor
For Select * from Table_name
where column_name in (inNumbers);

Return out_cursor;
End;

I seem to be getting an error when I try the code above. How can I use a variable in an IN
CLAUSE?

Answer: Unfortunately, there is no easy way to use a variable in an IN CLAUSE if the
variable contains a list of items. We can, however, suggest two alternative options:

Option #1

Instead of creating a string variable that contains a list of numbers, you could try storing
each value in a separate variable. For example:

Create or Replace Function func_name
Return PackageName.ref_cursor
As
out_cursor PackageName.Ref_cursor;
v1 varchar(2);
v2 varchar(2);
v3 varchar(2);

Begin

v1 := '1';
v2 := '2';
v3 := '3';

Open out_cursor
For Select * from Table_name
where column_name in (v1, v2, v3);

Return out_cursor;

End;


Option #2

You could try storing your values in a table. Then use a sub-select to retrieve the values.

For example:

Create or Replace Function func_name
Return PackageName.ref_cursor
As
out_cursor PackageName.Ref_cursor;

Begin

Open out_cursor
For Select * from Table_name
where column_name in (select values from list_table);

Return out_cursor;

End;

In this example, we've stored our list in a table called list_table.

Download CURSORWITHVARIABLE.pdf.html

Cursor within a cursor

Question: In PSQL, I want to declare a cursor within cursor. The second cursor should
use a value from the first cursor in the "where clause". How can I do this?

Answer: Below is an example of how to declare a cursor within a cursor.

In this example, we have a cursor called get_tables that retrieves the owner and
table_name values. These values are then used in a second cursor called get_columns.

create or replace procedure MULTIPLE_CURSORS_PROC is
v_owner varchar2(40);
v_table_name varchar2(40);
v_column_name varchar2(100);

/* First cursor */
cursor get_tables is
select distinct tbl.owner, tbl.table_name
from all_tables tbl
where tbl.owner = 'SYSTEM';

/* Second cursor */
cursor get_columns is
select distinct col.column_name
from all_tab_columns col
where col.owner = v_owner
and col.table_name = v_table_name;

begin

-- Open first cursor
open get_tables;
loop
fetch get_tables into v_owner, v_table_name;

open get_columns;
loop
fetch get_columns into v_column_name;

end loop;
close get_columns;

end loop;
close get_tables;

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
end MULTIPLE_CURSORS_PROC;

The trick to declaring a cursor within a cursor is that you need to continue to open and
close the second cursor each time a new record is retrieved from the first cursor. That
way, the second cursor will use the new variable values from the first cursor

Download CURSORWITHINCURSOR.pdf.html

Cursor Basics

A cursor is a SELECT statement that is defined within the declaration section of your
PLSQL code. We'll take a look at three different syntaxes for cursors.

Cursor without parameters (simplest)

The basic syntax for a cursor without parameters is:

CURSOR cursor_name
IS
SELECT_statement;

For example, you could define a cursor called c1 as below.

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

The result set of this cursor is all course_numbers whose course_name matches the
variable called name_in.

Below is a function that uses this cursor.

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;

end if;

close c1;

RETURN cnumber;

END;

Cursor with parameters

The basic syntax for a cursor with parameters is:

CURSOR cursor_name (parameter_list)
IS
SELECT_statement;

For example, you could define a cursor called c2 as below.

CURSOR c2 (subject_id_in IN varchar2)
IS
SELECT course_number
from courses_tbl
where subject_id = subject_id_in;

The result set of this cursor is all course_numbers whose subject_id matches the
subject_id passed to the cursor via the parameter.

Cursor with return clause

The basic syntax for a cursor with a return clause is:

CURSOR cursor_name
RETURN field%ROWTYPE
IS
SELECT_statement;

For example, you could define a cursor called c3 as below.

CURSOR c3
RETURN courses_tbl%ROWTYPE
IS
SELECT *
from courses_tbl
where subject = 'Mathematics';

The result set of this cursor is all columns from the course_tbl where the subject is
Mathematics.

OPEN Statement

Once you've declared your cursor, the next step is to open the cursor.
The basic syntax to OPEN the cursor is:

OPEN cursor_name;

For example, you could open a cursor called c1 with the following command:

OPEN c1;

Below is a function that demonstrates how to use the OPEN statement:

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;

end if;

close c1;

RETURN cnumber;

END;

FETCH Statement

The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so
that some type of operation can be performed on the data. After declaring and opening
your cursor, the next step is to FETCH the rows from your cursor.

The basic syntax for a FETCH statement is:

FETCH cursor_name INTO <list of variables>;

For example, you could have a cursor defined as:

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

The command that would be used to fetch the data from this cursor is:

FETCH c1 into cnumber;

This would fetch the first course_number into the variable called cnumber;

Below is a function that demonstrates how to use the FETCH statement.

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;

end if;

close c1;

RETURN cnumber;

END;

CLOSE Statement

The final step of working with cursors is to close the cursor once you have finished using
it.

The basic syntax to CLOSE the cursor is:

CLOSE cursor_name;

For example, you could close a cursor called c1 with the following command:

CLOSE c1;

Below is a function that demonstrates how to use the CLOSE statement:

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;

end if;

close c1;

RETURN cnumber;

END;

Below is an example of how you might use the %NOTFOUND attribute.

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;
CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;

close c1;

RETURN cnumber;

END;

SELECT FOR UPDATE Statement

The Select For Update statement allows you to lock the records in the cursor result set.
You are not required to make changes to the records in order to use this statement. The
record locks are released when the next commit or rollback statement is issued.

The syntax for the Select For Update is:

CURSOR cursor_name
IS
select_statement
FOR UPDATE [of column_list] [NOWAIT];

For example, you could use the Select For Update statement as follows:

CURSOR c1
IS
SELECT course_number, instructor
from courses_tbl
FOR UPDATE of instructor;

If you plan on updating or deleting records that have been referenced by a Select For
Update statement, you can use the Where Current Of statement.

WHERE CURRENT OF Statement

If you plan on updating or deleting records that have been referenced by a Select For
Update statement, you can use the Where Current Of statement.

The syntax for the Where Current Of statement is either:

UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;

OR

DELETE FROM table_name
WHERE CURRENT OF cursor_name;

The Where Current Of statement allows you to update or delete the record that was last
fetched by the cursor.

Updating using the WHERE CURRENT OF Statement

Here is an example where we are updating records using the Where Current Of
Statement:

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in
FOR UPDATE of instructor;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;

else
UPDATE courses_tbl
SET instructor = 'SMITH'
WHERE CURRENT OF c1;

COMMIT;

end if;

close c1;

RETURN cnumber;

END;

Deleting using the WHERE CURRENT OF Statement

Here is an example where we are deleting records using the Where Current Of
Statement:

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in
FOR UPDATE of instructor;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;

else
DELETE FROM courses_tbl
WHERE CURRENT OF c1;

COMMIT;

end if;

close c1;

RETURN cnumber;

END;

Download CURSORBasics.pdf.html

Creating Procedures

In Oracle, you can create your own procedures.

The syntax for a procedure is:

CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];

When you create a procedure or function, you may define parameters. There are three
types of parameters that can be declared:

1. IN - The parameter can be referenced by the procedure or function. The value of
the parameter can not be overwritten by the procedure or function.
2. OUT - The parameter can not be referenced by the procedure or function, but the
value of the parameter can be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the procedure or function and the
value of the parameter can be overwritten by the procedure or function.

The following is a simple example of a procedure:

CREATE OR REPLACE Procedure UpdateCourse
( name_in IN varchar2 )
IS
cnumber number;

cursor c1 is
select course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;

insert into student_courses
( course_name,
course_number)
values ( name_in,
cnumber );

commit;

close c1;

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;

This procedure is called UpdateCourse. It has one parameter called name_in. The
procedure will lookup the course_number based on course name. If it does not find a
match, it defaults the course number to 99999. It then inserts a new record into the
student_courses table.

Download CREATINGPROCEDURES.pdf.html

Creating Functions

In Oracle, you can create your own functions.

The syntax for a function is:

CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];

When you create a procedure or function, you may define parameters. There are three
types of parameters that can be declared:

1. IN - The parameter can be referenced by the procedure or function. The value of
the parameter can not be overwritten by the procedure or function.
2. OUT - The parameter can not be referenced by the procedure or function, but the
value of the parameter can be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the procedure or function and the
value of the parameter can be overwritten by the procedure or function.

The following is a simple example of a function:

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

cursor c1 is
select course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;

close c1;

RETURN cnumber;

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;

This function is called FindCourse. It has one parameter called name_in and it returns a
number. The function will return the course number if it finds a match based on course
name. Otherwise, it returns a 99999.

You could then reference your new function in an SQL statement as follows:

select course_name, FindCourse(course_name) as course_id
from courses
where subject = 'Mathematics';

Download CreatingFunctions.pdf.html

CREATE TABLE

The CREATE TABLE statement allows you to create and define a table.

The basic syntax for a CREATE TABLE statement is:

CREATE TABLE table_name
( column1 datatype null/not null,
column2 datatype null/not null,
...
);

Each column must have a datatype. The column should either be defined as "null" or "not
null" and if this value is left blank, the database assumes "null" as the default.

For example:

CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50)
);

Practice Exercise #1:

Create a customers table that stores customer ID, name, and address information. The
customer ID should be the primary key for the table.

Solution:

The CREATE TABLE statement for the customers table is:

CREATE TABLE customers
( customer_id number(10) not null,
customer_name varchar2(50) not null,
address varchar2(50),
city varchar2(50),
state varchar2(25),
zip_code varchar2(10),
CONSTRAINT customers_pk PRIMARY KEY
(customer_id)
);

Practice Exercise #2:

Based on the departments table below, create an employees table that stores employee
number, employee name, department, and salary information. The primary key for the
employees table should be the employee number. Create a foreign key on the employees
table that references the departments table based on the department_id field.

CREATE TABLE departments
( department_id number(10) not null,
department_name varchar2(50) not null,
CONSTRAINT departments_pk PRIMARY KEY
(department_id)
);

Solution:

The CREATE TABLE statement for the employees table is:

CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
department_id number(10),
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY
(employee_number),
CONSTRAINT fk_departments
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
);

Download CREATETABLE.pdf.html

Thursday, 4 July 2013

CREATE a table from another table

You can also create a table from an existing table by copying the existing table's
columns.

It is important to note that when creating a table in this way, the new table will be
populated with the records from the existing table (based on the SELECT Statement).

Syntax #1 - Copying all columns from another table

The basic syntax is:

CREATE TABLE new_table
AS (SELECT * FROM old_table);

For example:

CREATE TABLE suppliers
AS (SELECT *
FROM companies
WHERE id > 1000);

This would create a new table called suppliers that included all columns from the
companies table.

If there were records in the companies table, then the new suppliers table would also
contain the records selected by the SELECT statement.

Syntax #2 - Copying selected columns from another table

The basic syntax is:

CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n FROM old_table);

For example:

CREATE TABLE suppliers
AS (SELECT id, address, city, state, zip
FROM companies
WHERE id > 1000);

This would create a new table called suppliers, but the new table would only include the
specified columns from the companies table.

Again, if there were records in the companies table, then the new suppliers table would
also contain the records selected by the SELECT statement.

Syntax #3 - Copying selected columns from multiple tables

The basic syntax is:

CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n
FROM old_table_1, old_table_2, ... old_table_n);

For example:

CREATE TABLE suppliers
AS (SELECT companies.id, companies.address, categories.cat_type
FROM companies, categories
WHERE companies.id = categories.id
AND companies.id > 1000);

This would create a new table called suppliers based on columns from both the
companies and categories tables.

Frequently Asked Questions

Question: How can I create a table from another table without copying any values from
the old table?

Answer: To do this, the basic syntax is:

CREATE TABLE new_table
AS (SELECT * FROM old_table WHERE 1=2);

For example:

CREATE TABLE suppliers
AS (SELECT * FROM companies WHERE 1=2);

This would create a new table called suppliers that included all columns from the
companies table, but no data from the companies table.

Download CREATEatablefromanothertable.pdf.html

COUNT Function

The COUNT function returns the number of rows in a query.

The syntax for the COUNT function is:

SELECT COUNT(expression)
FROM tables
WHERE predicates;

Note:

The COUNT function will only count those records in which the field in the brackets is
NOT NULL.

For example, if you have the following table called suppliers:

Supplier_ID      Supplier_Name   State
1                         IBM                    CA
2                       Microsoft
3                        NVIDIA

The result for this query will return 3.

Select COUNT(Supplier_ID) from suppliers;

While the result for the next query will only return 1, since there is only one row in the
suppliers table where the State field is NOT NULL.

Select COUNT(State) from suppliers;

Simple Example
For example, you might wish to know how many employees have a salary that is above
$25,000 / year.

SELECT COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000;

In this example, we've aliased the count(*) field as "Number of employees". As a result,
"Number of employees" will display as the field name when the result set is returned.

Example using DISTINCT

You can use the DISTINCT clause within the COUNT function.

For example, the SQL statement below returns the number of unique departments where
at least one employee makes over $25,000 / year.

SELECT COUNT(DISTINCT department) as "Unique departments"
FROM employees
WHERE salary > 25000;

Again, the count(DISTINCT department) field is aliased as "Unique departments". This
is the field name that will display in the result set.

Example using GROUP BY

In some cases, you will be required to use a GROUP BY clause with the COUNT
function.

For example, you could use the COUNT function to return the name of the department
and the number of employees (in the associated department) that make over $25,000 /
year.

SELECT department, COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;

Because you have listed one column in your SELECT statement that is not encapsulated
in the COUNT function, you must use a GROUP BY clause. The department field must,
therefore, be listed in the GROUP BY section.

Performance Tuning

Since the COUNT function will return the same results regardless of what NOT NULL
field(s) you include as the COUNT function parameters (ie: within the brackets), you can
change the syntax of the COUNT function to COUNT(1) to get better performance as the
database engine will not have to fetch back the data fields.

For example, based on the example above, the following syntax would result in better
performance:

SELECT department, COUNT(1) as "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;

Now, the COUNT function does not need to retrieve all fields from the employees table
as it had to when you used the COUNT(*) syntax. It will merely retrieve the numeric
value of 1 for each record that meets your criteria.

Practice Exercise #1:

Based on the employees table populated with the following data, count the number of
employees whose salary is over $55,000 per year.

CREATE TABLE employees
( employee_number number(10) not null,
employee_name varchar2(50) not null,
salary number(6),
CONSTRAINT employees_pk PRIMARY KEY
(employee_number)
);

INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1001, 'John Smith', 62000);

INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1002, 'Jane Anderson', 57500);

INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1003, 'Brad Everest', 71000);

INSERT INTO employees (employee_number, employee_name, salary)
VALUES (1004, 'Jack Horvath', 42000);

Solution:

Although inefficient in terms of performance, the following SQL statement would return
the number of employees whose salary is over $55,000 per year.

SELECT COUNT(*) as "Number of employees"
FROM employees
WHERE salary > 55000;

It would return the following result set:

Number of
employees
3

A more efficient implementation of the same solution would be the following SQL
statement:

SELECT COUNT(1) as "Number of employees"
FROM employees
WHERE salary > 55000;

Now, the COUNT function does not need to retrieve all of the fields from the table (ie:
employee_number, employee_name, and salary), but rather whenever the condition is
met, it will retrieve the numeric value of 1. Thus, increasing the performance of the SQL
statement.

Practice Exercise #2:

Based on the suppliers table populated with the following data, count the number of
distinct cities in the suppliers table:

CREATE TABLE suppliers
( supplier_id number(10) not null,
supplier_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT suppliers_pk PRIMARY KEY
(supplier_id)
);

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5001, 'Microsoft', 'New York');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5002, 'IBM', 'Chicago');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5003, 'Red Hat', 'Detroit');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5004, 'NVIDIA', 'New York');

INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5005, 'NVIDIA', 'LA');

Solution:

The following SQL statement would return the number of distinct cities in the suppliers
table:

SELECT COUNT(DISTINCT city) as "Distinct Cities"
FROM suppliers;

It would return the following result set:

Distinct Cities
4

Practice Exercise #3:

Based on the customers table populated with the following data, count the number of
distinct cities for each customer_name in the customers table:

CREATE TABLE customers
( customer_id number(10) not null,
customer_name varchar2(50) not null,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY
(customer_id)
);

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7001, 'Microsoft', 'New York');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7002, 'IBM', 'Chicago');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7003, 'Red Hat', 'Detroit');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7004, 'Red Hat', 'New York');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7005, 'Red Hat', 'San Francisco');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7006, 'NVIDIA', 'New York');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7007, 'NVIDIA', 'LA');

INSERT INTO customers (customer_id, customer_name, city)
VALUES (7008, 'NVIDIA', 'LA');

Solution:

The following SQL statement would return the number of distinct cities for each
customer_name in the customers table:

SELECT customer_name, COUNT(DISTINCT city) as "Distinct Cities"
FROM customers
GROUP BY customer_name;

It would return the following result set:

CUSTOMER_NAME      Distinct Cities

IBM                                      1
Microsoft                              1
NVIDIA                               2
Red Hat                                3

Download COUNTFunction.pdf.html