+ All Categories
Home > Documents > OCP - SQL&PL_SQL(Vol1)

OCP - SQL&PL_SQL(Vol1)

Date post: 10-Apr-2015
Category:
Upload: api-3814149
View: 706 times
Download: 9 times
Share this document with a friend
322
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder Volume One S Participant Guide Edition 1.1 M03989 T1001E11
Transcript
Page 1: OCP - SQL&PL_SQL(Vol1)

���������� �� ��� �� ������ ������ ���� ���������� ����� ��� ��� � �������� ����

������� ���

�� �

������

Page 2: OCP - SQL&PL_SQL(Vol1)

Authors

Neena KochharDebby Kramer

Technical Contributorsand Reviewers

Christian BauwensDebra BowmanLenny BrunsonJackie CollinsRalf DurbenBrian FryAnthony HolbrookKarlene JensenSarah JonesGlenn MaslenSundar NagarathnamSandra SchrickUlrike SchwinnRosemarie TrumanJenny TsaiLaura Van Deusen

Publishers

Stephanie JonesKimberly LeeJennifer RobertsonMark Turangan

��������� �������� ������������ ����� ����� ��� ������ ����� ���

���� ���!"�������� �������� ����������� ��#��"����� �# ������ �����������$ �� ��

��� ���� !���� � ������� �����"��� ���������� ������������ �� !�� ��� ������%

�!�� ��� �� ���� ��������� &� ��������� ��'� (� ���� ����������� �# ��� ��#�'���

�� �����&����� )# ���� ���!"�������� �� ���� ���� �� � *�+� ,� ���"��� ������ �#

��� -�����"��� �# -�#����� ���� �� �� ���� ���� '��� (��������� (����� ��� ��� #��%

��'��� ������ �� �������&��.

�������� ����� ������

*��� �!��������� �� �������!�� &� ��� ,� ���"��� �� �!&/��� �� ������������ #��

��""������ ��"�!��� ��#�'��� ��� ����� &� ���"�� �� &� (��������� (����� ��#�%

'��� !���� 0������ ��'� ��� �� ��� #���� �� �!&��������� 1�2 1�2 1��2 �# -0�(+

�3����4%4��� (����� �� ��������� -��� ��� ��"�!��� +�#�'��� 1����&�� �� 2�

���� "������� �� ��� ������� �# �� "�� ��� &� ������ �� ��� #��" �� &� ��� "����

'����!� ��� �5����� ����� '������ ���"������ �# ���6����'��� ��!������ +�� ����

���!� �#������ ������������ ��� ����� ������� �� � �������� �# ��������� ��' ���

"�� ���!�� �� �� �� ���7�� ���"���� ����������

)# ���� ���!"�������� �� ���� ���� �� �*�+� ,� ���"��� ������ ��� '����� ��� -�%

����"��� �# -�#����� ���� �� �� ���� ���� '��� 8(��������� (������9 �� ��#���� ��

0�( 3����4%�:� (����� �� -���%,������� ����!���� ��������� ))) 1;!�� �� 42�

��� ��#��"����� �� ���� ���!"��� �� �!&/��� �� ������ '����!� ������� )# ��! #���

��� ���&��"� �� ��� ���!"��������� ������ ������ ���" �� '������ �� 6����'���

��!������ +�� ����� ������ ������������ 3 ������ <��='��� >�5 �3� �� (��%

'���+������ ���:�3������������������ ���� ���'������ ���� ���� ���!"���

�� ����� #����

+?@A<�!�� <@7+?@� <�����!�� >!������ -� ������7�� ������4 +�� ��� ������

+�� ��� -���� ����7�� ��� -�������7� ��� �����"��=� �� ���������� �����%

"��=� �# ������ ������������

��� ����� ����!��� �� ��"���� ��"�� ��� !��� #�� ������#������� �!������ �����

��� "�� &� �����"��=� �# ����� �������� � �'�����

Page 3: OCP - SQL&PL_SQL(Vol1)

���

��������

���� �

������ ��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

������� ���

����� ������������ �����

����������� ����������� ���

� ����������� ���� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

������ ���������� ���

������ ������� ���

��� ��������� ������� ������� ��!

"����# ������#��� ����� ��$%

&��� �� ������' ��$!

��� ������ ��� ��� "�� ��($

")*+ ")*,����+ �� �*-")* ��(�

"�##�� "������� .�� � �#���������� ������ ��(!

"�##��� ����

�� �������� ���� ���� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $��

��� /���� )���� /���0 $��

1����#���� 2���������� $�$�

����#� 1������ $�($

��� ������������� �������� $�(�

*������ ��������� "����� $�(�

3������� 4��� 5����� $�(%

���������� ��� "�������� �� �������� �6� $��$

")*,���� ��##�� � $���

*������ �� �� ")*,���� $��%

��������� ����� "�������� $��!

")*,���� 2 ����� ��##�� � $�7$

")*,���� 8��� ��##�� � �� ������ 9��� $�7�

�������� � ����� $�7�

"�##��� $��$

�������� �������6 $���

�������� $ $���

�� �������� ������� ���� ���� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� (��

�� ����� �6� 6��� ��� � 2 /: ������ (��

*�#����� "������ �6� 6��� ��� &922 ������ (�$$

��#������� ��������� (�$�

Page 4: OCP - SQL&PL_SQL(Vol1)

��

4������� 2���������� (�$%

")* ��������� (�$!

)������� ��� 6��� 3������� ��� ������ (�(%

���� �� ����� ���� (�(!

"�##��� (���

�������� �������6 (���

�������� ( (��%

�� ����� ��� �������� ���� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� ���

�������6 ���

"����� �6 8�������� ��%

��������� 8�������� ��!

4�#��� 8�������� ��$%

������ ��� 8��#�� ��(�

;���� 1����#���� ��������� 6��� ���� ��(�

��� 8�������� ��(%

���������� 8�������� ����

��<�91 8������� 6��� ��� 8��#��� ����

��<�91 8������� 6��� 4�#��� 8��#��� ��7�

��<4;3/2 �� ��< 1�2 8�������� ��7!

4������ "����� �6 8�������� ���$

4������ 8�������� ����

"�##��� ����

�������� �������6 ���%

�������� � ���!

� !��"�#��� !��� ���� $��"� %�&�� ��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� 7��

�������6 7��

&��� �� � ��������� ��� ���' 7�%

"�#��� =��� )���� 7�!

;���� ����� 1������ 7�$%

4���2>������ 7�$!

�������� ���� � 6��� 4� ����� 3���� 7�($

=������ � ����� �� ������ 7�(�

"�##��� 7�(%

�������� �������6 7�(!

�������� 7 7��$

'� (��" �������� '��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� ���

�������6 ���

.���� 8�������� ��%

Page 5: OCP - SQL&PL_SQL(Vol1)

��� .�;� /: ������ ��$�

������� )������ ;���� .���� 8�������� ��$!

.����� &����� .����� ��(�

��� 915�4. ������ ��(�

"�##��� ���$

�������� �������6 ����

�������� � ���7

)� �&*����� )��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� ?��

�������6 ?��

"��>������ ?�%

9�6 1�� 4���� "��>������ �������� ' ?�!

"����� �6 "��>������ ?�$$

2����� 6��� "��>������ ?�$�

3������� �6 "��>������ ?�$%

915�4. ������ 6��� 4���� "��>������ ?�$!

"�##��� ?�($

�������� �������6 ?�(�

�������� ? ?�(�

���� �

+� �"����#��� �����&�� �� ������ +��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� %��

�������6 %��

"����������� 5�������� %�%

"����� 1#������ "����������� 5�������� %�!

������� ;��� 5�������� %�$�

������� 5����� ���� � "����� 8��� %�($

"�##��� %�(�

�������� �������6 %�(�

�������� % %�(?

,� -������� �� !��� $������ ��� !���&��� !����� ,��� � � � � � � � � � � � � � � � � � � � � � � �

���������� @��

�������6 @��

"����# ������#��� ����� @�%

������� ����� @�!

��� 3� �� @�$$

2����� ����������� 3� ����� @�$�

2����� ����������� 3� �� �������� @�$�

��������� ����������� �� A��� @�(�

�������� ��� ������� @�(!

"�##��� @��!

Page 6: OCP - SQL&PL_SQL(Vol1)

��

.� �������� %�&�� .��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� !��

�������6 !��

�������� ������ !�%

������% �������� !�$�

����������� !�$�

�������� � ����� ���# � ����� �������� ����� !�(�

�������� � ����� ���# �6� �� 1������ ����� !��$

������#��� ����� �������� !���

"�##��� !���

�������� �������6 !��%

�������� ! !��!

�/� -���� !��� !��������# �/��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $B��

�������6 $B��

)������� ��� ��� ��������� $B�%

����0��� ����������� �� � ����� $B�$�

"�##��� $B�$%

�������� �������6 $B�$!

�������� $B $B�($

��� $���"����� !��� ����� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $$��

�������6 $$��

1 ��� � 4�6 �6 �� � ����� $$�%

������� �6� ���# 1������ ����� $$�$!

;� ����� �6� $$�($

������� �6� $$�(!

����������� ���������� $$���

��##������ ������� $$��!

������ /��0 ������� $$�7�

������ /��0 ������� �� � "�������� $$�7�

"����#��� *���� ������0 $$�7%

"�##��� $$�7!

�������� �������6 $$��$

�������� $$ $$���

��� 0������ %�&�� ��� ����������� ����� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $(��

�������6 $(��

1 ��� � ����#� $(�%

3� ������ � ����#� $(�!

1 ��� �� ������� � ���������� $(�$$

Page 7: OCP - SQL&PL_SQL(Vol1)

���

�������� �� 2������� � ���������� $(�$�

������� � ����� $(�$%

���#��� �� ���������� � ����� $(�$!

1 ��� � ��##��� �� � ����� $(�($

"�##��� $(�(�

�������� �������6 $(�(�

�������� $( $(�(%

��� �������� ��*����� ����� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $���

�������6 $���

�������� � "�>����� $��%

;���� � "�>����� $��$�

1������� � "�>����� $��$%

�#����� � "�>����� $��$!

"�##��� $��($

�������� �������6 $��(�

�������� $� $��(�

� � �������� ����� � ��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $7��

�������6 $7��

�������� � 5��6 $7�%

������#��� 3* ���������� �� � 5��6 $7�$�

������#��� 5��6 4�#�� �� "��������� $7�($

�#����� � 5��6 $7�(�

"�##��� $7�(�

�������� �������6 $7�(%

�������� $7 $7�(!

�'� �������� ������� �'��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $���

�������6 $���

&��� �� ��� �� �� ;�� ' $��%

�� �� "�������� $��!

�������� �� �� �� $��$�

������#��� �� ���� $��$%

�#����� �� �� �� $��$!

"�##��� $��($

�������� �������6 $��(�

�������� $� $��(�

�)� ��������� 1��� 0����� �)��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $?��

�������6 $?��

Page 8: OCP - SQL&PL_SQL(Vol1)

����

"����# ���������� $?�%

&��� �� � ���' $?�$$

�������� :��� ����6�� $?�$�

.������� ������ ���������� $?�$�

������#��� ���������� .����� $?�($

���0��� ������ ���������� $?�(�

�������� � "�����# ��� �� ������ $?�(�

"�##��� $?�(!

�������� �������6 $?��$

�������� $? $?���

�+� �����# �� �2� ��� �2�3 � �+��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

"�##��� �� ")* �� ")*,���� $%��

�������� �������6 $%�!

�������� $% $%�$$

���� �

�,� -������� �� �4�2� �,��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $@��

�������6 $@��

�*-")* /���0 "�������� $@�!

��� �*-")* 2������#��� $@�$�

1���� ����� ��� /��� �� $@�$%

�.� 5����� �� ������� 5���� �.��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� $!��

�������6 $!��

������ ����� ��� /��� �� ������������ $!�%

����� ��� /��� �� ��#������� $!�!

��� ������ 4�������� $!�$�

��� ����������� $!�(�

��� ������# ;��� 2 ���� $!�(%

��� "���� ������# ;��� 2 ���� $!��$

�������� � "���� ������# ;��� $!���

������#��� ���� 1������ �� ��� ����������� $!���

"������ � /���0����� $!��%

2��#����� *���� 5�������� $!�7�

"�##��� $!�7�

�������� �������6 $!�7%

�������� $! $!�7!

�/� $�����6��� ���������� ���7 �&"������� �/��� � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� (B��

�������6 (B��

Page 9: OCP - SQL&PL_SQL(Vol1)

��

�������� � "��������# (B�%

�������� � ����� ��� (B�!

��#������ 8�������� �� ����� ���� (B�$�

�������� � 8������� (B�$%

����0��� "��������#� (B�($

"�##��� (B�(!

�������� �������6 (B��$

�������� (B (B���

��� !����"��� � ���"� �4�2� 5��8 ����� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� ($��

�������6 ($��

�������� �*-")* 5�������� �� ��������� ($�%

�������� "����� 5�������� ($�!

�������� ��#������ �������� ($�$�

�*-")* /���0 "����� ���� ($�(�

1�������� 5����� �� 5�������� ($�(!

������##��� .�� ������ ($�7�

"�##��� ($�7!

�������� �������6 ($��$

�������� ($ ($���

��� ����������� ���7 -���� ����� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� ((��

�������6 ((��

��������� ��� ;���� �*-")* ((�%

"2*2�� 2��������� ((�$�

3����������� ��� ;���� �*-")* ((�$!

")* ������ ((�(�

����������� ������������ ((�(%

"�##��� ((��$

�������� �������6 ((���

�������� (( ((���

��� ��������� ��� �� �4�2� 5��8� ����� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� (���

�������6 (���

��� �8 "����#��� (��%

/��� ��� *������ ��� ������ (��$�

*��� "����#���� (��$%

"�##��� (��(!

�������� �������6 (���$

�������� (� (����

Page 10: OCP - SQL&PL_SQL(Vol1)

� � ��������� 2����� &# 1���� 9�"���� ������ � ��� � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� (7��

�������6 (7��

����������� 2������� ������� (7�%

2������� ������ 1��������� (7�$%

������� �� ���� � (7�($

������� 6��� ����#����� (7�(�

������ 8� *���� (7�(�

1������� ��� &922 �;24� �8 ������ (7�(%

"�##��� (7�(!

�������� �������6 (7��$

�������� (7 (7���

�'� 9���� :������ �'��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

���������� (���

�������6 (���

2�������� ����� (��%

�������� 2��������� (��!

�������� ��� ����� ������% "����� 2��������� (��$$

�������� 4������ ����� ������% "����� 2��������� (��$�

�������� ;���� ����� 2��������� (��$%

2���� �������� 8�������� (��$!

����������� 2��������� (��($

"�##��� (��(�

�������� �������6 (��(�

�������� (� (��(%

�)� �����# �� �4�2� �)��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

"�##��� (?��

�������� �������6 (?�!

�������� (? (?�$$

����

0 ������� ������� 0��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

������� 1��

�������� $ "�������� 1�7

�������� ( "�������� 1�@

�������� � "�������� 1�(B

�������� 7 "�������� 1�(!

�������� � "�������� 1��!

�������� ? "�������� 1�7?

�������� % "�������� 1���

�������� ! "�������� 1��!

�������� $B "�������� 1�?�

Page 11: OCP - SQL&PL_SQL(Vol1)

��

�������� $$ "�������� 1�?@

�������� $( "�������� 1�@(

�������� $� "�������� 1�@@

�������� $7 "�������� 1�!%

�������� $� "�������� 1�$B�

�������� $? "�������� 1�$B!

�������� $% "�������� 1�$$?

�������� $! "�������� 1�$�7

�������� (B "�������� 1�$��

�������� ($ "�������� 1�$�@

�������� (( "�������� 1�$?�

�������� (� "�������� 1�$%B

�������� (7 "�������� 1�$%%

�������� (� "�������� 1�$@?

�������� (? "�������� 1�$!(

5 %�&� !�����"����� ��� !��� 5��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

"�##�� "������� .�� � ������� �����# /��

"<�;"��32 ����� /�7

"< 2�� ����� /�%

"<23� ����� /�@

"<�31.2 ����� /�$B

"<�4524��: ����� /�$$

"<��23 ����� /�$?

"<� ����� /�(B

"<�� ;�� ����� /�((

"<2.��4 ����� /�(�

"<&129�;"2 ����� /�(?

� 1���� �2�3 � �� ������ ��"���� ��� $����� �4�2� ���� ���� � � � � � � � � � � �

���������� ���

�������6 ���

2������� ��##�� � �� ")*,���� ��%

��#������� �� ")* �� ")*,���� ��##�� � ��!

")*,���� "2� ��##�� � ��$$

�������� � ����� ��$�

�������� �� �������� �*-")* /���0� ��(�

2������� ��##�� � �� ")*,���� ��(�

������� ����� �� ������ 5����� ��(%

�������� �� ")*,���� ���$

��������� �������� �� � "��������# ����

2�������� "���� "��������#� ���%

"�##��� ��7$

�������� �������6 ��7�

Page 12: OCP - SQL&PL_SQL(Vol1)

���

�������� � ��7�

�������� � "�������� ��7%

! ������ ������ ��� �������� !��� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �

����� ��� ���� ��

����� "������� ��

(�����#

�����

Page 13: OCP - SQL&PL_SQL(Vol1)

�������

Page 14: OCP - SQL&PL_SQL(Vol1)

������ � ������� ��� ��� ������ �� �� �������� �� ����� �

��� ��

����� �� ��� � �� � �����

Before you begin this course, you should be able to use a graphical user interface(GUI). Required prerequisites are familiarity with data processing concepts andtechniques.

� �� � ����� �� ����� !��

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder is aninstructor-led course featuring lecture and hands-on exercises. The concepts and skillsintroduced are reinforced by online demonstrations and written practice sessions.

� �� � �" �� ����� !��

Lesson Aim

Lesson 1: Selecting Rows In order to extract data from the databaseyou need to use the Structured QueryLanguage (SQL) SELECT command.

You will want to create SELECTstatements that you can use time andtime again. You will also see how to saveyour statements for later use.

Lesson 2: Limiting Selected Rows This lesson will cover how to restrict therows and columns that are displayed, aswell as how to specify the order in whichthe rows are presented.

Page 15: OCP - SQL&PL_SQL(Vol1)

������� ��

��� �� ���������

Lesson Aim

Lesson 3: Single Row Functions Functions make the basic query blockmore powerful and are used tomanipulate data values. This is the firstof two lessons that explore functions.You will focus on single row character,number, and date functions, as well asthose functions that convert data fromone type to another, for example,character data to numeric.

Lesson 4: Displaying Data from MultipleTables

This lesson will cover how to obtain datafrom more than one table, using themany different methods available.

Lesson 5: Group Functions This lesson further addresses functions.You will focus on obtaining summaryinformation, such as averages, for groupsof rows. You will discuss how to grouprows in a table into smaller sets, and howto specify search criteria for groups ofrows.

Lesson 6: Subqueries This lesson covers more advancedfeatures of the SELECT statement. Youcan write subqueries in the WHEREclause of another SQL statement toobtain values based on an unknownconditional value.

Lesson 7: Specifying Variables atRuntime

You can create a command filecontaining a WHERE clause to restrictthe rows displayed. To change thecondition each time the command file isrun, you use substitution variables.Substitution variables can replace valuesin the WHERE clause, a text string, andeven a column or a table name.

Page 16: OCP - SQL&PL_SQL(Vol1)

������ � ������� ��� ��� ������ �� �� �������� �� ������

��� �� ���������

Lesson Aim

Lesson 8: Overview of Data Modelingand Database Design

Before you build your tables, you designyour database. You examine the datamodeling process and relational databaseconcepts, and define normalization. Youalso translate an entity relationshipmodel into a relational database design.

Lesson 9: Creating Tables You will create tables. You will alsobuild integrity constraints, which arerules governing what can and cannot bedone with the data.

Lesson 10: Oracle Data Dictionary The Oracle data dictionary is one of themost important components of theOracle7 Server. It consists of a set oftables and views that provide a read-onlyreference to the database.

Lesson 11: Manipulating Data Once your tables have been created, youwill need to add new rows, makechanges to rows in a table, or delete rowsby using data manipulation commands.This lesson covers using SQL commandsto make changes to data. A number ofthese data manipulation commands makeup a transaction, which you may eithersave or delete using transaction controls.

Lesson 12: Altering Tables andConstraints

After you create your tables, you mayneed to change the table structuresbecause you omitted a column, yourcolumn definition needs to be changed,or you want to enable or disableconstraints. This lesson will demonstratehow you can amend table structures aswell as add and remove constraints.

Page 17: OCP - SQL&PL_SQL(Vol1)

������� ��

��� �� ���������

Lesson Aim

Lesson 13: Creating Sequences Many applications require the use ofunique numbers as primary key values.You can either build code into theapplication to handle this requirement oruse a sequence to generate uniquenumbers. This lesson covers creating andusing sequences that crate uniquenumbers.

Lesson 14: Creating Views In this lesson, you will see how viewscan be used to present data to users in avariety of ways. In addition, you will seehow integrity constraints can beenforced, if using a view to insert,update, or delete data.

Lesson 15: Creating Indexes If you want to improve the performanceof some queries, you should considercreating an index. You can also useindexes to enforce uniqueness on acolumn or a collection of columns.

Lesson 16: Controlling User Access This lesson describes the Oracle7 Serverdecentralized security system. Using thecommands covered in this lesson, youcan control database access to specificobjects and add new users with differentlevels of access privileges. You canprovide alternative names for objects byusing the CREATE SYNONYMcommand.

Page 18: OCP - SQL&PL_SQL(Vol1)

������ � ������� ��� ��� ������ �� �� �������� �� ������

��� �� ���������

Lesson Aim

Lesson 17: Summary of SQL andSQL*Plus (optional)

This lesson reviews the basic commandscovered in the course so far.

Lesson 18: Overview of PL/SQL Overview lesson of how to create anduse PL/SQL program units andsubprograms using Oracle ProcedureBuilder.

Lesson 19: Basics of Procedure Builder A key feature of proceduralprogramming is the ability to create anddebug code quickly and easily.Procedure Builder provides all of thefunctionality necessary for you tosuccessfully develop and debug PL/SQLprograms. This lesson enables you tomanipulate PL/SQL code usingProcedure Builder.

Lesson 20: Modularizing Programmingwith Subprograms

Modularity allows you to break yourcode into manageable, well-definedunits. Each of these units in PL/SQL hastwo types of subprograms calledprocedures and functions. You will learnthe structure of subprograms and how toinvoke them.

Lesson 21: Developing a SimplePL/SQL Block

Create a simple PL/SQL block afterlearning the various elements thatcompose a block.

Lesson 22: Interacting with Oracle Access the database and controltransactions through SQL statements inPL/SQL.

Page 19: OCP - SQL&PL_SQL(Vol1)

������� � �

��� �� ���������

Lesson Aim

Lesson 23: Using Control Structures Control the flow of your PL/SQL blockby using conditional statements andloops.

Lesson 24: Processing Queries withExplicit Cursors

Use a multiple row SELECT statementwithin PL/SQL to process many rows.Declare and control explicit cursors,which are used in loops, including thecursor FOR loop.

Lesson 25: Error Handling When you execute PL/SQL code, youmay encounter errors. The error causesthe PL/SQL block to halt with anexception. You can trap the exceptionand perform actions conditionally usingexception handlers.

Lesson 26: Summary of PL/SQL(optional)

Review the topics covered in the course.Create a PL/SQL-based application formanipulating and maintaininginformation in your database.

Page 20: OCP - SQL&PL_SQL(Vol1)

������ � ������� ��� ��� ������ �� �� �������� �� ������

#����� ��$� �� ��

������ ��$� �� ��

Title Part Number

Oracle7 Server SQL Reference, Release 7.3 A32538

SQL*Plus User’s Guide and Reference, Release 3.3 A42562–1

PL/SQL User’s Guide and Reference, Release 2.3 A32542

Oracle7 Server SQL Language Quick Reference 5421–70–1292

SQL*Plus Quick Reference, Release 3.3 A42561

Oracle Procedure Builder 1.5 Developer’s Guide A32485

Oracle7 Server Concepts Manual, Release 7.3 A32534

Oracle Press: Oracle Beginner’s Guide A31178–1

Oracle Press: Oracle Complete Reference A10197–1

%�� ��� #���������

� System Release Bulletins

� Installation and User’s Guides

� read.me Files

� International Oracle User’s Group (IOUG) Articles

� Oracle Magazine

Page 21: OCP - SQL&PL_SQL(Vol1)

������� ��

�&'���'� � ����� ��

�&'���'� � ����� �� ( � � ���

Convention Object or Term Example

Uppercase Commands,functions,column names,table names,PL/SQL objects,schemas

Use the SELECT command to viewinformation stored in the LAST_NAMEcolumn of the S_EMP table.

Lowercase,italic

File names,syntax variables,usernames,passwords

where: role is the name of the role to becreated.

Initial cap Triggers andbutton names

Assign a When–Validate–Item trigger to theS_ORD block.

Press the Cancel button.

Italic Books, names ofcourses andmanuals, andemphasizedwords or phrases

For further information on the subject see:Oracle7 Server SQL Language ReferenceManual

Do not save changes to the database.

Quotation marks Lesson moduletitles referencedwithin a course

This subject is covered in Lesson 3, “Workingwith Objects.”

Italic bold The first time aglossary word isreferred to in asection

The algorithm inserts the new key.

Page 22: OCP - SQL&PL_SQL(Vol1)

������ � ������� ��� ��� ������ �� �� �������� �� ������

�&'���'� � ����� �� ���������

�&'���'� � ����� �� ( � � ���

Convention Object or Term Example

Uppercase Commands,functions

SQL> SELECT userid2 FROM s_emp;

Lowercase,italic

Syntax variables SQL> CREATE ROLE role;

Lowercase Column names,table names, filenames, PL/SQLobjects

. . .OG_ACTIVATE_LAYER (OG_GET_LAYER (’prod_pie_layer’)). . .

SQL> SELECT last_name2 FROM s_emp;

SQLDBA> DROP USER scott2> IDENTIFIED BY tiger;

Bold Text that mustbe entered by auser.

SQL> SELECT userid2 FROM s_emp;

Vertical bar Separatesalternativesyntax elements

OFF | ON

Brackets Optional itemslist in syntax

[OFF | ON]

Braces Mandatoryitems list insyntax

{OFF | ON}

Underlining Default value insyntax

{OFF | ON}

Page 23: OCP - SQL&PL_SQL(Vol1)

������� ��

�&'���'� � ����� �� ���������

�&)$�� ���� � �� � *��)��

Guidance relating to the subject matter, such as hints or advice.

For more information, seea publication related to the subject matter

This icon indicates a warning relating to the subject matter. An example warningmight be “When deleting rows, word your WHERE clause carefully.”

Used for a series of instructions that must be followed in sequential order.

Page 24: OCP - SQL&PL_SQL(Vol1)

������ � ������� ��� ��� ������ �� �� �������� �� ������ �

Page 25: OCP - SQL&PL_SQL(Vol1)

�����������

Page 26: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ����

Page 27: OCP - SQL&PL_SQL(Vol1)

����������� ���

����� �� ��� �

At the end of this course, you should be able to

� Describe the relational database approach, concepts, terminology, and operators.

� Create database structures such as tables and views using Structured QueryLanguage (SQL).

� Store, retrieve, and update data in the database.

� Develop PL/SQL blocks of application code using Procedure Builder tomanipulate data.

Page 28: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ����

Page 29: OCP - SQL&PL_SQL(Vol1)

����������� ��

����� ����

The course starts with an overview. The first module ends on Day 3 with anoptional summary covering the SQL and SQL*Plus content. The second moduleends on Day 5 with an optional summary of the PL/SQL section.

DAY 1

Lesson 1 Selecting Rows

Lesson 2 Limiting Selected Rows

Lesson 3 Single Row Functions

Lesson 4 Displaying Data from Multiple Tables

DAY 2

Lesson 5 Group Functions

Lesson 6 Subqueries

Lesson 7 Specifying Variables at Runtime

Lesson 8 Overview of Data Modeling and Database Design

Lesson 9 Creating Tables

Lesson 10 Oracle Data Dictionary

DAY 3

Lesson 11 Manipulating Data

Lesson 12 Altering Tables and Constraints

Lesson 13 Creating Sequences

Lesson 14 Creating Views

Lesson 15 Creating Indexes

Lesson 16 Controlling User Access

Lesson 17 Summary of SQL and SQL*Plus(optional)

Page 30: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���!

Page 31: OCP - SQL&PL_SQL(Vol1)

����������� ��"

����� ���� ���������

DAY 4

Lesson 18 Overview of PL/SQL

Lesson 19 Basics of Procedure Builder

Lesson 20 Modularizing Programming with Subprograms

Lesson 21 Developing a Simple PL/SQL Block

Lesson 22 Interacting with Oracle

DAY 5

Lesson 23 Controlling Flow in PL/SQL Blocks

Lesson 24 Processing Queries by Using Explicit Cursors

Lesson 25 Error Handling

Lesson 26 Summary of PL/SQL(optional)

Page 32: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���#

Page 33: OCP - SQL&PL_SQL(Vol1)

����������� ��$

%& ' ������� (������ ���� )�

The principles of the relational model were first outlined by Dr. E. F. Codd in a June1970 paper called “A Relational Model of Data for Large Shared Data Banks.” In thispaper, Dr. Codd proposed the relational model for database systems.

The more popular models used at that time were hierarchical and network, or evensimple flat file data structures. Relational database management systems (RDBMS)soon became very popular, especially for their ease of use and flexibility in structure.In addition, there were a number of innovative vendors, such as Oracle, whosupplemented the RDBMS with a suite of powerful application development and userproducts, providing a total solution.

���� )�� �* �& ' ������� +�� �

� Collections of objects or relations store the data.

� A set of operators can act on the relations to produce other relations.

� A relational database must possess data integrity so that its data must be accurateand consistent.

An example of a relation is a table. To retrieve data from the tables, use relationaloperation SQL commands.

' ������� (������ ,�������

� Manage the storage of data

� Control access to the data

� Provide a means to retrieve and modify the data

For more information, seeThe Relational Model for Database Management Version 2, E. F. Codd, AddisonWesley.

Page 34: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���-.

Page 35: OCP - SQL&PL_SQL(Vol1)

����������� ��--

%& ' ������� (������ ���� )� ���������

(������ % �/�����0

Concept Description

Table A table is the basic storage structure of an RDBMS, consistingof one or more columns and zero or more rows.

Row A row is a combination of column values in a table; forexample, the information about one department in the tableS_DEPT. A row is sometimes called a “record”.

Column A column represents one kind of data in a table; for example,the department name in the example table S_DEPT. It isdescribed with a column name and holds data of a specific typeand size.

Field At the intersection of a row and a column, you find a field. Thefield can contain data. If there is no data in the field, it is said tocontain a null value.

Primary Key A primary key is the column or set of columns that uniquelyidentifies each row in a table; for example a departmentnumber. It must contain a value.

Foreign Key A foreign key is a column or set of columns that refers to aprimary key in the same table or in another table. You createthem to enforce relational database design rules.

1�� �� �

� No duplicate values are allowed in a primary key.

� Primary keys generally cannot be changed.

� Foreign keys are based on data values and are purely logical, not physicalpointers.

� A foreign key value must match an existing primary key value or else be NULL.

Page 36: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���-�

Page 37: OCP - SQL&PL_SQL(Vol1)

����������� ��-�

%& ' ������� (������ ���� )� ���������

' ������� (������ ���) �� �

A database is a collection of individual, named objects, such as tables. You do notspecify the access route to the tables, and do not need to know how the data isarranged physically.

To access the database, you execute a Structured Query Language (SQL) command,which is the American National Standards Institute (ANSI) standard language foroperating upon relational databases. The language contains a large set of operators forpartitioning and combining relations. The database can be easily modified by usingthe SQL commands. The relational model allows for full data independence.

2���� � ��� �* (������ �� ���

Object Description

Table Basic unit of storage composed of rows and columns.

View Logically represents subsets of data from one or more tables.

Sequence Generates primary key values.

Index Improves the performance of queries.

Synonym Alternate name for an object.

Program unit Procedure, function, or package of SQL and PL/SQL statementsgrouped together.

%��� ���) �� �

A single table is composed of rows and columns. The intersection of the rows andcolumns are the field values. Each row should be identified by a primary key, whichallows no duplicate rows. The order of the rows is insignificant; by default, the data isordered in the order in which it was inserted. Each column is uniquely named.Column order is insignificant when storing data; specify the column order when thedata is retrieved. Field values cannot be broken into smaller components.

Page 38: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���-�

Page 39: OCP - SQL&PL_SQL(Vol1)

����������� ��-

%& ' ������� (������ ���� )� ���������

���� �� (��� ��� ���0

Ensure that users perform only operations that leave the database in a correct andconsistent state with data integrity constraints. All data integrity constraints should beenforced by the database server or the application software.

Integrity Constraint Type Description

Entity No part of a primary key can be NULL and thevalue must be unique.

Referential Foreign key values must match a primary key or beNULL.

Column Values in the column must match the defineddatatype.

User-defined Values must comply with the business rules.

Page 40: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���-!

Page 41: OCP - SQL&PL_SQL(Vol1)

����������� ��-"

�0�� / ( � ��)/ �� �0��

From concept to production, develop a database by using the system developmentcycle. The cycle contains multiple stages of development. This top-down, systematicapproach to database development transforms business information requirements intoan operational database.

���� � �* ( � ��)/ ��

Stage Action

Strategy and Analysis Study and analyze the business requirements. Buildmodels of the system.

Design Build a database design based on the model.

Build and Document Produce the working, tested software. Write userdocumentation, help screens, and operations manual.

Transition Engage in a user acceptance testing phase.

Production Operate the production system.

Page 42: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ���-#

� �� �

É ÉÉ

Page 43: OCP - SQL&PL_SQL(Vol1)

����������� ��-$

3&�� �� ���� 4

Oracle is a database company that offers a comprehensive set of application buildingand end-user products and services aimed at providing complete informationtechnology solutions. Oracle applications are portable across a wide range ofplatforms and operating systems, from personal computers to large parallelprocessors.

2���� �& ���� " � �� �

Oracle provides a flexible RDBMS called the Oracle7 Server. Its features allow youto store and manage information with all the advantages of a relational structure plusPL/SQL, an engine that provides you with the ability to store and execute databaseobjects, such as procedures and triggers. The Server offers users the options ofretrieving data based on optimization techniques. It includes security features thatcontrol how a database is accessed and used. Other features are that it has consistencyand protection of data through locking mechanisms, and a two-phase commit processfor distributed databases across a network.

Oracle applications may run on the same computer as the Oracle7 Server.Alternatively, you can run applications on a system local to the user and run theOracle7 Server on another system (client-server architecture). In this client-serverenvironment, a wide range of computing resources can be used. For example, aform-based airline reservation application can run on a client personal computerwhile accessing flight data that is conveniently managed by an Oracle7 Server on acentral computer.

For more information, seeOracle7 Server Concepts Manual.

Page 44: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ����.

DSS Tools

Page 45: OCP - SQL&PL_SQL(Vol1)

����������� ���-

%& ���� ������� � �

All application development and end-user products available within the Oracleproduct set allow you to access the database, either directly or indirectly, throughSQL commands.

(���� � ���...

A set of products for end users and decision support analysts that supports rapidquerying and reporting, multi-dimensional analysis of Data Warehousing, andpowerful data mining through a low maintenance meta-layer.

( � ��) ���...

A set of application development tools that allow developers to create screen-basedapplications for users, reporting features, and graphical displays of charts, images,and drawings.

( ��� ���...

A family of tools to aid the analysis, design, and generation of Oracle applications.

For more information, seeGuide to Oracle Products and Services.

Page 46: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� �����

��� ���

������

���)��

� �� �

ÉÉÉÉ

Page 47: OCP - SQL&PL_SQL(Vol1)

����������� ����

���5 ���6����5 ��� ������

SQL, SQL*Plus, and PL/SQL commands are used to access and manipulate datastored in an Oracle database.

���6����5 ���5 ��� ������

Language or Tool Description

SQL A command language for communication with theOracle7 Server from any tool or application. OracleSQL contains many extensions.

SQL*Plus An Oracle tool that recognizes and submits SQL andPL/SQL statements to the Server for execution andcontains its own command language.

PL/SQL An Oracle procedural language for writing applicationlogic and manipulating data outside the database.

, ���� � �* ���

� Can be used by a range of users, including those with little or no programmingexperience

� Is a non-procedural language

� Reduces the amount of time required for creating and maintaining systems

� Is an English-like language

, ���� � �* ���6����

� Accepts ad hoc entry of statements

� Accepts SQL and PL/SQL input from files

� Edits SQL statements with a line editor

� Controls environmental settings

� Formats query results into basic reports

� Interacts with end users

� Accesses remote databases

Page 48: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� �����

Page 49: OCP - SQL&PL_SQL(Vol1)

����������� ���

���5 ���6����5 ��� ������ ���������

SQL is the industry standard language for relational databases. The AmericanNational Standards Institute (ANSI) adopted it in 1986. The International StandardsOrganization (ISO) has also adopted it. All major RDBMSs support some form ofSQL and most RDBMS vendors intend to comply with the ANSI standard.

��� ��//����

There are many commands available in SQL. The table below describes thecommands covered in this course.

Command Description

SELECT Retrieves data from the database. Most commonly usedcommand.

INSERTUPDATEDELETE

Enters new rows, changes existing rows, and removes unwantedrows from tables in the database, respectively. Collectivelyknown as Data Manipulation Language (DML) commands.

CREATEALTERDROPRENAMETRUNCATE

Sets up, changes, and removes data structures from tables.Collectively known as Data Definition Language (DDL)commands.

COMMITROLLBACKSAVEPOINT

Manage the changes made by DML statements. Changes to thedata can be grouped together into logical transactions.

GRANTREVOKE

Gives or removes access rights to both the Oracle database andthe structures within it. Collectively known as Data ControlLanguage (DCL) commands.

For more information, seeOracle7 Server SQL Reference, Release 7.3 and Oracle7 SQL Quick ReferenceGuide.

Page 50: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ����!

Page 51: OCP - SQL&PL_SQL(Vol1)

����������� ���"

���5 ���6����5 ��� ������ ���������

���6���� ��//��� ��� ��� �

Category Purpose

Environment Affects the general behavior of SQL statements for thesession.

Format Formats query results.

File manipulation Saves, loads, and runs script files.

Execution Sends SQL or PL/SQL commands from SQL buffer toOracle7 Server.

Edit Modifies SQL commands in the buffer.

Interaction Allows users to create and pass variables to SQLstatements, print variable values, and print messages tothe screen.

Miscellaneous Various commands to connect to the database,manipulate the SQL*Plus environment, and displaycolumn definitions.

������ ����7 ��������

PL/SQL provides a host of programming constructs to manipulate data. Each groupof commands is packaged in a PL/SQL block.

Block Section Description

Header Contains the subprogram name, type, and arguments.Only used for subprograms.

Declarative Contains the local identifiers for the block.

Executable Contains the SQL statements and PL/SQL controlstatements.

Exception Performs actions when errors occur.

Page 52: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ����#

Page 53: OCP - SQL&PL_SQL(Vol1)

����������� ���$

��//� �)����� 1���� ( /��������� %��� �

The course is based on the fictitious Summit Sporting Goods Company. The diagramon the facing page is an entity relationship (ER) model for Summit Sporting GoodsCompany. In an effective business system data is divided into discrete categories orentities. An ER model is an illustration of various entities in a business and therelationships between them. The entity relationship model on the facing pagerepresents the main tables and relationships covered in the course. The businessnarrative describes the company’s database needs.

���� �� 8������

“I’m a manager of a sporting goods wholesale company that operates worldwide tofill orders of retail sporting goods stores. The stores are our customers (some of ourpeople prefer to call them our clients). Right now we have fifteen customersworldwide, but we’re trying to expand our customer base. Our two biggest customersare Big John’s Sports Emporium in San Francisco, CA, USA, and Womansport inSeattle, Washington, USA. For each customer, we must track an identificationnumber and customer name. We may track an address (including the city, state, postalcode, and country) and phone number. We maintain warehouses in different regionsto best fill the orders of our customers. For each order, we must track an ordernumber. We may track the date ordered, date shipped, and payment type when theinformation is available. Right now, we have the world divided into five regions:North America, South America, Africa/Middle East, Asia, and Europe. That’s all wetrack, just the region number and region name. We try to assign each customer to aregion so we’ll generally know the best location from which to fill each order. Eachwarehouse must have a warehouse number. We may track an address (including city,state, postal code, and country) and phone number. We currently have only onewarehouse per region, but we’re hoping to have more soon.”

“I manage the order entry functions for our wholesale sporting goods business. Mydepartment is responsible for placing and tracking the orders when our customerscall. For each department, we must track the department number and name.Sometimes, our customers just mail us the orders when they are not in a rush, butmost often they call us or fax us an order. We are hoping to expand our business byproviding immediate turnaround of order information to our clients. We can promiseto ship by the next day as long as the goods are in stock (or inventory) at one of ourwarehouse locations. When the information is available, we track the amount instock, the reorder point, maximum stock, the reason we are out of stock, and the datewe restocked the item. When the goods are shipped, we intend to fax the shippinginformation automatically through our shipping system. No, I don’t manage that area.

Continued

Page 54: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� ����.

Page 55: OCP - SQL&PL_SQL(Vol1)

����������� ���-

��//� �)����� 1���� ( /��������� %��� � ���������

���� �� 8������ 9������ �

My department just ensures that our customers have the correct billing informationand verifies that their account is in good credit standing. We may also record generalcomments about a customer.”

“We do make sure all the items the customers have requested are in stock. For eachitem, we track an item number. We may also track the item price, quantity, andquantity shipped if the information is available. If they are in stock, we want toprocess the order and tell our clients what the order number is and how much theirorder total is. If the goods are not in stock, the customer tells us whether we shouldhold the entire order for a full shipment, or to process the partial order.”

“The accounting department is responsible for maintaining the customer information,especially for assigning new customer numbers. My department is allowed to updatethe customer information only when a customer places an order and their billing orship to addresses have changed. No, we are not responsible for collections. That’s allhandled by accounts receivable. I also think that the sales representatives get involvedas their commission depends on customers who pay! For each sales representative, oremployee, we must know the employe number and last name. Occasionally, we needto know the first name, user name, start date, title, and monthly salary. We may alsotrack the employee’s commission percent and any comments about the individual.”

“Our order entry personnel are well versed in our product line. We hold frequentmeetings with marketing so they can inform us of new products. This results ingreater customer satisfaction because our order entry operators can answer a lot ofquestions. This is possible because we deal with a few select customers and maintaina specialty product line. For each product, we must know the product number andname. Occasionally, we must also know the description, suggested price, and unit ofsale. We would also like to track very long descriptions of our products and picturesof our products, when necessary.”

Page 56: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� �����

Page 57: OCP - SQL&PL_SQL(Vol1)

����������� ����

��//��0

Relational database management systems are composed of objects. They are managedby operations and governed by data integrity constraints.

Oracle Corporation produces products and services to meet your relational databasemanagement system needs. The main product is the Oracle7 Server. The Serverallows you to store and manage information by using SQL and the PL/SQL enginefor procedural constructs.

���

Oracle7 Server supports ANSI standard SQL and contains extensions. SQL is thelanguage used to communicate with the Server to access, manipulate, and control dataaccess.

���6����

SQL*Plus is an Oracle tool to execute SQL and PL/SQL statements. It also containssupporting commands to format queries, set the environment, and edit SQLcommands in the SQL buffer.

������

The PL/SQL language extends the SQL language by offering block structuredprocedural constructs combined with SQL non-procedural capabilities.

Page 58: OCP - SQL&PL_SQL(Vol1)

����������� �� ���� � ��� ��� ������ ���� ���� ��� ���� �����

Page 59: OCP - SQL&PL_SQL(Vol1)

��������� ��

Page 60: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��

Page 61: OCP - SQL&PL_SQL(Vol1)

��������� �� ��

������� ��

In order to extract data from the database you need to use the Structured QueryLanguage (SQL) SELECT command. You may need to restrict the columns thatare displayed. This lesson explains all of the commands you will use to performthese actions.

You will want to create SELECT statements that can be used time and timeagain. In this lesson you will also see how to save your statements for later use.

At the end of this lesson, you should be able to

� Write a SELECT statement to query the database.

� Perform arithmetic calculations using SQL arithmetic operators.

� Handle null values.

� Specify alternative column headings using aliases.

� Concatenate columns.

� Edit SQL statements in the SQL*Plus buffer and create command files.

Page 62: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �!

Page 63: OCP - SQL&PL_SQL(Vol1)

��������� �� �"

#$� ����� ����% ���&

A SELECT statement retrieves information from the database, implementing allalgebraic operators.

�%���'

SELECT [DISTINCT] {*,column [alias],....} FROM table;

where: SELECT is a list of at least one column.

DISTINCT suppresses duplicates.

* selects all columns.

column selects the named column.

alias gives selected columns a different heading.

FROM table specifies the table containing the columns.

Page 64: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �(

Page 65: OCP - SQL&PL_SQL(Vol1)

��������� �� �)

#$� ����� ����% ���& ���������

*������ ��� +,,����

By following these simple rules and guidelines, you will be able to construct validstatements that are easy both to read and to edit.

� SQL commands may be entered on one or many lines.

� Clauses are usually placed on separate lines for readability and ease of editing.

� Tabs and indents can be used to make code more readable.

� Command words cannot be split across lines or abbreviated.

� Keywords and commands typically are entered in uppercase; all other words,such as table names and columns, are entered in lowercase.

� SQL commands are not case sensitive, unless indicated.

� An SQL command is entered at the SQL prompt, and subsequent lines arenumbered. This is called the SQL buffer.

� Only one statement can be current at any time within the buffer, and thestatement can be executed in a number of ways:

� Place a semicolon (;) at the end of last clause.

� Place a semicolon or slash on the last line in the buffer.

� Place a slash at the SQL prompt.

� Issue a SQL*Plus RUN command at the SQL prompt.

For more information, seeOracle Applications: Coding Standards, Release 10G.

Page 66: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �-

��,.���� �/�/+# �����,��� ������� �$�0������ �� ��������

Page 67: OCP - SQL&PL_SQL(Vol1)

��������� �� �1

#$� ����� ����% ���& ���������

In its simplest form, a SELECT statement must include the following:

� A SELECT clause, which specifies the columns to be displayed.

� A FROM clause, which specifies the table containing the columns listed in theSELECT clause.

��������� 2�� +��,�� ��� ��

The asterisk (*) selects all columns from the table.

/'�,.��

List all columns and all rows from the S_DEPT table.

SQL> SELECT *2 FROM s_dept;

ID NAME REGION_ID------- --------------- --------- 10 Finance 1 31 Sales 1 32 Sales 2 33 Sales 3 34 Sales 4 35 Sales 5 41 Operations 1 42 Operations 2 43 Operations 3 44 Operations 4 45 Operations 5 50 Administration 1

12 rows selected.

Page 68: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� � 3

Page 69: OCP - SQL&PL_SQL(Vol1)

��������� �� �

#$� ����� ����% ���& ���������

��������� �.���0�� +��,��

You restrict the query to display only certain columns by specifying the columnnames, separated by commas, in the SELECT clause.

/'�,.��

Display all department numbers, employee last names, and manager numbers in theS_EMP table.

SQL> SELECT dept_id, last_name, manager_id2 FROM s_emp;

DEPT_ID LAST_NAME MANAGER_ID------- ------------ ---------- 50 Velasquez 41 Ngao 1 31 Nagayama 1 10 Quick-To-See 1 50 Ropeburn 1 41 Urguhart 2 42 Menchu 2 43 Biri 2 44 Catchpole 2...

25 rows selected.

Specify the columns you want to see, in the order in which you want to see them, inthe SELECT clause. Do not forget to use the comma as a column name separator.

+��,� 4������ 5�0�����

Character and date column headings and data are left-justified within a column andnumbers are right-justified. Character and date column headings may be truncated,but number headings may not be truncated. The column labels appear in uppercase bydefault. You can override the column label display with an alias.

Page 70: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� � �

Page 71: OCP - SQL&PL_SQL(Vol1)

��������� �� � �

2���$,���� /'.�������

You may need to modify the way data is displayed, perform calculations, or look atwhat-if scenarios. This is possible using arithmetic expressions.

An arithmetic expression may contain column names, constant numeric values, andthe arithmetic operators.

2���$,���� �.������

These are the arithmetic operators available in SQL. You may use arithmeticoperators in any clause of a SQL statement except the FROM clause.

Operators Description

+ Add

- Subtract

* Multiply

/ Divide

Page 72: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� � !

Page 73: OCP - SQL&PL_SQL(Vol1)

��������� �� � "

2���$,���� /'.������� ���������

/'�,.��

Use the multiplication operator to display annual salary figures and their commissionpercentage for all employees.

SQL> SELECT last_name, salary * 12, commission_pct2 FROM s_emp;

LAST_NAME SALARY*12 COMMISSION_PCT------------ ---------- --------------...Havel 15684Magee 16800 10Giljum 17880 12.5Sedeghi 18180 10Nguyen 18300 15Dumas 17400 17.5Maduro 16800...

Notice that the resultant calculated column SALARY*12 is not a new column in theoriginating table, but is for display only.

Page 74: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� � (

Page 75: OCP - SQL&PL_SQL(Vol1)

��������� �� � )

2���$,���� /'.������� ���������

�.����� ����������

If an arithmetic expression contains more than one operator, multiplication anddivision are evaluated first. If operators within an expression are of the same priority,then evaluation is from left to right.

/'�,.��

Display the last name, salary, and annual compensation of employees. Calculate theannual compensation as 12 multiplied by the monthly salary, plus a one-time bonus of$100.

SQL> SELECT last_name, salary, 12 * salary + 1002 FROM s_emp;

LAST_NAME SALARY 12*SALARY+100------------ ---------- -------------Velasquez 2500 30100Ngao 1450 17500Nagayama 1400 16900Quick-To-See 1450 17500Ropeburn 1550 18700Urguhart 1200 14500...

Note: Use parentheses to reinforce the standard order of precedence and to improveclarity. For example, the expression above can be written as (12 * salary) +100 with no change in the result.

Page 76: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� � -

Page 77: OCP - SQL&PL_SQL(Vol1)

��������� �� � 1

2���$,���� /'.������� ���������

Override the rules of precedence with parentheses to specify the order in whichoperators are executed.

/'�,.��

Display the last name, salary, and annual compensation of employees. Calculate theannual compensation as monthly salary plus a monthly bonus of $100, multiplied by12.

SQL> SELECT last_name, salary, 12 * (salary + 100)2 FROM s_emp;

LAST_NAME SALARY 12*(SALARY+100)------------ ---------- ---------------Velasquez 2500 31200Ngao 1450 18600Nagayama 1400 18000Quick-To-See 1450 18600Ropeburn 1550 19800Urguhart 1200 15600...

Page 78: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��3

Page 79: OCP - SQL&PL_SQL(Vol1)

��������� �� ��

+��,� 2������

When displaying the result of a query, SQL*Plus normally uses the selected column’sname as the heading. In many cases, that heading may be difficult to understand oreven meaningless. You can change a column’s heading by using a column alias.

Specify the alias after the column in the SELECT list using a space as a separator. Bydefault, alias headings will be forced to uppercase and cannot contain blank spaces,unless the alias is enclosed in double quotation marks (“ ”).

/'�,.��

Display the last name, salary, and annual compensation of employees. Calculate theannual compensation as monthly salary plus a monthly bonus of $100, multiplied by12. Name the column ANNUAL_SALARY.

SQL> SELECT last_name, salary,2 12 * (salary + 100) AS ANNUAL_SALARY3 FROM s_emp;

Note: You can include the AS keyword before the alias name to comply with ANSISQL 92 standards.

+��,� 2������ ���$ 5���� ������� 6��&�

If the alias contains spaces, special characters (such as # or $), or is case-sensitive,enclose the alias in double quotation marks (“ ”).

SQL> SELECT last_name, salary,2 12 * (salary + 100) ”Annual Salary”3 FROM s_emp;

Page 80: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ���

Page 81: OCP - SQL&PL_SQL(Vol1)

��������� �� ���

#$� +���������� �.�����

You can link columns to other columns, arithmetic expressions, or constant values tocreate a character expression by using the concatenation operator (||). Columns oneither side of the operator are combined to make one single output column.

/'�,.��

Display the full names of the employees with the heading Employees.

SQL> SELECT first_name||last_name AS ”Employees” 2 FROM s_emp;

Employees--------------------------------------------------CarmenVelasquezLaDorisNgaoMidoriNagayamaMarkQuick-To-SeeAudryRopeburnMollyUrguhart...

The AS keyword before the alias name makes the SELECT clause easier to read.

Page 82: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��!

Page 83: OCP - SQL&PL_SQL(Vol1)

��������� �� ��"

������� +$������� ������

A literal is any character, expression, or number included in the SELECT list that isnot a column name or a column alias. It is printed for each row returned. Literalstrings of free-format text can be included in the query result and are treated like acolumn in the SELECT list.

Date and character literals must be enclosed within single quotation marks (‘ ’);number literals must not.

/'�,.��

Display the full names of the employees and their titles with the heading Employees.Be sure to add punctuation.

SQL> SELECT first_name || ’ ’ || last_name 2 || ’, ’|| title ”Employees”3 FROM s_emp;

Employees---------------------------------Carmen Velasquez, PresidentLaDoris Ngao, VP, OperationsMidori Nagayama, VP, SalesMark Quick-To-See, VP, FinanceAudry Ropeburn, VP, AdministrationMolly Urguhart, Warehouse Manager...

Page 84: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��(

Page 85: OCP - SQL&PL_SQL(Vol1)

��������� �� ��)

6������� 7��� 8�����

If a row lacks a data value for a particular column, that value is said to be null, or tocontain null.

A null value is a value that is unavailable, unassigned, unknown, or inapplicable. Inthe COMMISSION_PCT column, you notice that only Sales Representatives earncommission. Other employees are not entitled to earn commission. A null valuerepresents that fact.

A null value is not the same as zero or a space. Zero is a number, and a space is acharacter.

Columns of any datatype can contain null values, unless the column was defined asNOT NULL or as PRIMARY KEY when the table was created.

7��� 8����� �� 2���$,���� /'.�������

If any column value in an expression is null, the result is null. For example, if youattempt to perform division with zero, you will get an error. However, if you divideby null, the result is null.

/'�,.��

Display the last name, salary, title, and calculated commission.

SQL> SELECT last_name, title,2 salary*commission_pct/100 COMM3 FROM s_emp;

LAST_NAME TITLE COMM------------ --------------------- ----------...Havel Warehouse ManagerMagee Sales Representative 140Giljum Sales Representative 186.25Sedeghi Sales Representative 151.5Nguyen Sales Representative 228.75Dumas Sales Representative 253.75Maduro Stock Clerk...

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Elements of SQL.”

Page 86: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��-

Page 87: OCP - SQL&PL_SQL(Vol1)

��������� �� ��1

6������� 7��� 8����� ���������

78� 9������

In order to convert a null value to an actual value, use the NVL function.

�%���'

NVL (expr1, expr2)

where: expr1 is the source value or expression that maycontain null.

expr2 is the target value for converting null.

Note: You can use the NVL function to convert any datatype, but the return value isalways the same as the datatype of expr1.

/'�,.��

To calculate values for all employees from the previous example, use the NVLfunction to convert null values to zero.

SQL> SELECT last_name, title,2 salary * NVL(commission_pct,0)/100 COMM3 FROM s_emp;

LAST_NAME TITLE COMM------------ --------------------- ----------...Havel Warehouse Manager 0Magee Sales Representative 186.25Giljum Sales Representative 186.25...

78� +� ������ 0� 8����� 5����%.��

Datatype Conversion Example

NUMBER NVL(number_column,9)

DATE NVL(date_column,‘01-JAN-95’)

CHAR or VARCHAR2 NVL(character_column,‘Unavailable’)

Page 88: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��3

SQL> SELECT DISTINCT name 2 FROM s_dept;

Page 89: OCP - SQL&PL_SQL(Vol1)

��������� �� ��

��� ������ �$� �������� 0 5�.������ ��

Unless you indicate otherwise, SQL*Plus displays the results of a query withouteliminating duplicate rows.

/'�,.�� 5��.��%��� 2�� ��

Display all department names in the S_DEPT table.

SQL> SELECT name2 FROM s_dept;

NAME------------------FinanceSalesSalesSalesSalesSalesOperations. . .12 rows selected

#$� 5��#�7+# :�%���

To eliminate duplicate rows in the result, include the DISTINCT keyword in theSELECT clause immediately after the SELECT command word.

/'�,.�� 5��.��%��� ���;�� ��

Display all unique department names in the S_DEPT table.

SQL> SELECT DISTINCT name2 FROM s_dept;

NAME-----------------------AdministrationFinanceOperationsSales

Page 90: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ���

Page 91: OCP - SQL&PL_SQL(Vol1)

��������� �� ���

��� ������ �$� �������� 0 5�.������ �� ���������

5��#�7+# ���$ 6����.�� +��,��

You can specify multiple columns after the DISTINCT qualifier. The DISTINCTqualifier affects all selected columns.

/'�,.��

Display all the different combinations of job titles and department numbers.

SQL> SELECT DISTINCT dept_id, title2 FROM s_emp;

DEPT_ID TITLE------- --------------------- 10 VP, Finance 31 Sales Representative 31 VP, Sales 32 Sales Representative 33 Sales Representative 34 Sales Representative 34 Stock Clerk 35 Sales Representative 41 Stock Clerk 41 VP, Operations 41 Warehouse Manager 42 Stock Clerk 42 Warehouse Manager 43 Stock Clerk 43 Warehouse Manager 44 Stock Clerk 44 Warehouse Manager 45 Stock Clerk 45 Warehouse Manager 50 President 50 VP, Administration

21 rows selected.

Page 92: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��!

Page 93: OCP - SQL&PL_SQL(Vol1)

��������� �� ��"

���<���� +,,����

In this lesson, you saw how SQL commands are executed within a product calledSQL*Plus. SQL*Plus is a SQL and PL/SQL command execution environment withadditional features.

You can use a number of SQL*Plus commands when writing even the most basic ofSQL statements. This section covers some basic SQL*Plus commands to help you to

� Describe the table structure.

� Edit SQL in the buffer.

� Save files containing SQL for editing purposes.

� Execute saved files.

� Load SQL commands from a file into the SQL buffer.

� Obtain online help

For more information, seeSQL*Plus User’s Guide and Reference, Release 3.3.

Page 94: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��(

Page 95: OCP - SQL&PL_SQL(Vol1)

��������� �� ��)

������ �� � ���<����

How you invoke SQL*Plus depends upon which type of operating system orwindows environment you are running.

�� �� #$���$ � *����� /� ���,���

You double-click the SQL*Plus icon in the window manager, then enter theusername, password, and database, if required.

�� �� #$���$ � +,,��� ���� /� ���,���

Once you log on to your machine, at the operating system prompt enter the SQL*Pluscommand.

sqlplus [username [/password [@database]]]

where: username is your database username.

password is your database password. If you enter yourpassword here, it is visible.

@database is the database connect string.

Note: To ensure the integrity of your password, do not enter it at the operatingsystem prompt. Instead, only enter your username. Enter your password at thePassword prompt.

Once you are successfully logged in SQL*Plus, you see the following message:

SQL*Plus: Version 3.1.2 Production on Fri May 12th 15:31:32 1995 Copyright (c) Oracle Corporation 1979, 1992, All rights reserved.

SQL>

Page 96: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� ��-

SQL> DESCRIBE s_dept

Page 97: OCP - SQL&PL_SQL(Vol1)

��������� �� ��1

5��.��%��� #���� ���������

In SQL*Plus, you can display the structure of a table using the DESCRIBEcommand. The result of the command is to see the column names, datatypes, andwhether a column must contain data.

DESC[RIBE] tablename

where: tablename is the name of any existing table, view, orsynonym accessible to the user.

/'�,.��

Display information about the structure of the S_DEPT table.

SQL> DESCRIBE s_dept

Name Null? Type--------------- -------- --------------------ID NOT NULL NUMBER(7)NAME NOT NULL VARCHAR2(25)REGION_ID NUMBER(7)

where: Null? indicates that a column must contain data.

Type displays the datatype for a column.

Datatype Description

NUMBER (p,s) Number value having a maximum number of digits p, andthe number of digits to the right of the decimal point s.

VARCHAR2(s) Variable length character value of maximum size s.

DATE Date and time value between January 1, 4712 B.C. andDecember 31, 4712 A.D.

CHAR(s) Fixed length character value of size s.

For more information, seeOracle 7 Server SQL Reference, Release 7.3.

Page 98: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �!3

Page 99: OCP - SQL&PL_SQL(Vol1)

��������� �� �!

���<���� /������ +,,����

When you enter a SQL command, it is stored in a part of memory called the SQLbuffer and remains there until you enter a new command. SQL*Plus commands areentered one line at a time and are not stored in the SQL buffer.

=���������

� If you press [RETURN] before completing a command, SQL*Plus will promptyou with a line number.

� You terminate the SQL buffer by either entering one of the terminator characters(semicolon or slash), or pressing [RETURN] twice. You will now see the SQLprompt.

���<���� /������ +,,����

Command Description

A[PPEND] text Adds text to the end of the current line.

C[HANGE] / old / new / Changes old text to new in the current line.

C[HANGE] / text / Deletes text from the current line.

CL[EAR] BUFF[ER] Deletes all lines from the SQL buffer.

DEL Deletes current line.

DEL n Deletes one line (specified by n)

DEL m n Deletes a range of lines (m to n)

I[NPUT] Inserts an indefinite number of lines.

I[NPUT] text Inserts a line consisting of text.

L[IST] Lists all lines in the SQL buffer.

L[IST] n Lists one line (specified by n).

L[IST] m n Lists a range of lines (m to n).

R[UN] Displays and runs the current SQL command in thebuffer.

n Specifies the line to make the current line.

n text Replaces line n with text.

0 text Inserts a line before line 1.

Page 100: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �!�

Page 101: OCP - SQL&PL_SQL(Vol1)

��������� �� �!�

���<���� 9��� +,,���� ��� ������ 4��.

SQL commands act as the vehicle to the Oracle Server. SQL*Plus commands areused to control the environment, format query results, and manage files. You can usethe commands identified in the following table.

9��� +,,����

Command Description

SAV[E] filename [.ext][REP[LACE]|APP[END]]

Saves current contents of SQL buffer to a file. UseAPPEND to add to an existing file; use REPLACE tooverwrite an existing file. The default file extension is.sql.

GET filename [.ext] Writes the contents of a previously saved file to theSQL buffer. The default extension for the filename is.sql.

STA[RT] filename [.ext] Runs a previously saved command file.

@ filename Runs a previously saved command file (same asSTART).

EDIT Invokes the editor and saves the buffer contents to afile named afiedt.buf.

ED[IT] [filename[.ext]] Invokes editor to edit contents of a saved file.

SPO[OL] [filename[.ext]|OFF|OUT]

Stores query results in a file, OFF closes the spoolfile. OUT closes the spool file and sends the fileresults to the system printer.

EXIT Leaves SQL*Plus.

Note: You can change the text editor invoked by changing the value of theSQL*Plus variable _EDITOR by using the DEFINE command.

You can enter only one SQL*Plus command per SQL prompt. SQL*Plus commandsare not stored in the buffer. To continue a SQL*Plus command on the next line, endthe current line with a hyphen (-).

Page 102: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �!!

Page 103: OCP - SQL&PL_SQL(Vol1)

��������� �� �!"

+������� � �.��

+���67 +,,���

Control the display of a column in a report by using the COLUMN command. Forexample, you can change the heading, width, and format.

�%���'

COL[UMN] [{column|alias} [option ...]]

+���67 +,,��� �.����

Option Description

CLE[AR] Clears any column formats.

FOR[MAT] format Changes the display of the column data.

HEA[DING] text Sets the column heading. A vertical line (|) will force aline feed in the heading if you do not use justification.

JUS[TIFY] {align} Justifies the column heading (not the data) to be left,center, or right.

NOPRI[NT] Hides the column.

NUL[L] text Specifies text to be displayed for null values.

PRI[NT] Shows the column.

TRU[NCATED] Truncates the string at the end of the first line of display.

WRA[PPED] Wraps the end of the string to the next line.

WOR[D_WRAPPED] Same as WRAPPED, but ensures that words do not split.

Format elements used in the FORMAT option are discussed on the next page.

If you have a lengthy command, you can continue it on the next line by ending thecurrent line with a hyphen (-).

Page 104: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �!(

Page 105: OCP - SQL&PL_SQL(Vol1)

��������� �� �!)

+������� � �.�� ���������

5��.��% � +���� ��������

To show or clear the current COLUMN command settings, use the followingcommands:

Command Description

COL[UMN] column Displays the current settings for the specifiedcolumn.

COL[UMN] Displays the current settings for all columns.

COL[UMN] column CLE[AR] Clears the settings for the specified column.

CLE[AR] COL[UMN] Clears the settings for all columns.

Page 106: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �!-

Page 107: OCP - SQL&PL_SQL(Vol1)

��������� �� �!1

+������� � �.�� ���������

��,.�� +��,� 9�,�� 6��� /��,����

Element Description Example Result

An Sets a display width of n forcharacter and date columns.

N/A N/A

9 Represents a singlezero-suppression digit.

999999 1234

0 Enforces leading zero. 099999 01234

$ Represents a floating dollar sign. $9999 $1234

L Represents local currency. L9999 L1234

. Represents the position of thedecimal point.

9999.99 1234.00

, Represents the thousand separator. 9,999 1,234

The Oracle7 Server displays a string of pound signs (#) in place of a whole numberwhose digits exceed the number of digits provided in the format model. It will alsodisplay pound signs in place of a value whose format model is alphanumeric, butwhose actual value is numeric.

Page 108: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �"3

Page 109: OCP - SQL&PL_SQL(Vol1)

��������� �� �"

��,,��%

In this lesson, you have learned about retrieving information from a database tablewith the SELECT statement.

SELECT [DISTINCT] {*, column [alias], ...}FROM table;

where: SELECT is a list of at least one column.

DISTINCT suppreses duplicates.

* selects all columns.

column selects the named column.

alias gives selected column a different heading.

FROM table specifies the table containing the columns.

���<����

SQL*Plus is an execution environment you can use to send SQL commands to thedatabase server and to edit and to save SQL commands. Commands may be executedfrom the SQL prompt or from a script file.

Page 110: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �"�

Page 111: OCP - SQL&PL_SQL(Vol1)

��������� �� �"�

�������� � �� ���

This is the first of many practices. In most cases, the questions show the output that isrequired. The solutions (if you require them) can be found in Appendix A. Practicesare intended to introduce all topics covered in the lesson. The first six questions arepaper–based.

In any practice, there may be “if you have time” questions. Do these only if you havecompleted all other questions within the allocated time and would like a furtherchallenge to your skills.

�������� +������

� Selecting all data from different tables.

� Describing the structure of tables.

� Performing arithmetic calculations and specifying different column names.

� Editing commands in the buffer.

Please take this practice slowly and precisely. You can experiment with saving andrunning command files. If you have any questions at any time, please attract theinstructor’s attention.

��.��>����� ��������

For questions 1–2 circle either True or False.

Page 112: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �"!

Page 113: OCP - SQL&PL_SQL(Vol1)

��������� �� �""

��������

1. SQL commands are always held in a buffer. True / False

2. SQL*Plus commands assist with querying data. True / False

3. Show the structure of the S_DEPT table. Select all information from theS_DEPT table.

ID NAME REGION_ID--------- ------------------------- --------- 10 Finance 3 31 Sales 1 32 Sales 2 33 Sales 3 34 Sales 4 35 Sales 5 41 Operations 1 42 Operations 2 43 Operations 3 44 Operations 4 45 Operations 5 50 Administration 1

12 rows selected.

4. Show the structure of the S_CUSTOMER table. Using this table, perform thefollowing actions.

a. Retrieve all information from the S_CUSTOMER table.

b. Display the name and phone number for each customer.

Page 114: OCP - SQL&PL_SQL(Vol1)

���������� � ������� ��� ��� ������ ����� �������� ������� �"(

�������� ���������

4.—Continued

c. Display the phone number and name for each customer, with phone numberappearing first.

PHONE NAME-------------------- -------------------------55-2066101 Unisports81-20101 Simms Atheletics91-10351 Delhi Sports1-206-104-0103 Womansport852-3692888 Kam’s Sporting Goods33-2257201 Sportique234-6036201 Sweet Rock Sports49-527454 Muench Sports809-352689 Beisbol Si!52-404562 Futbol Sonora42-111292 Kuhn’s Sports20-1209211 Hamada Sport1-415-555-6281 Big John’s Sports Emporium1-716-555-7171 Ojibway Retail7-3892456 Sporta Russia

15 rows selected.

Page 115: OCP - SQL&PL_SQL(Vol1)

�������� ������ � ��

Page 116: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������

Page 117: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���

������ ��

While retrieving data from the database, you may need to restrict the rows ofdata that are displayed or specify the order in which the rows are displayed.This lesson explains the commands you will use to perform these actions.

At the end of this lesson you should be able to

� Sort row output using the ORDER BY clause.

� Enter search criteria using the WHERE clause.

Page 118: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������!

If the ORDER BY clause is not used, the sort order is undefined, and the Oracle7Server may not fetch rows in the same order for the same query twice. Use theORDER BY clause to display the rows in a specific order.

Page 119: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��"

�������� � �� ���# �#� ��$%� �& '����

The order of rows returned in a query result is undefined. The ORDER BY clausemay be used to sort the rows. If used, you must place the ORDER BY clause last.You can specify an expression or use position to sort.

�(���)

SELECT expr FROM table [ORDER BY {column,expr} [ASC|DESC]];

where: ORDER BY specifies the order in which the retrieved rowsare displayed.

ASC orders the rows in ascending order. This is thedefault order.

DESC orders the rows in descending order.

%)��*�

Query the employee table for employee last name, department number, and the hiredate for all employees. Sort the results by employee last name.

SQL> SELECT last_name, dept_id, start_date2 FROM s_emp3 ORDER BY last_name;

LAST_NAME DEPT_ID START_DAT------------ ------- ---------Biri 43 07-APR-90 Catchpole 44 09-FEB-92 Chang 44 30-NOV-90Dancs 45 17-MAR-91Dumas 35 09-OCT-91Giljum 32 18-JAN-92Havel 45 27-FEB-91...

Page 120: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������+

Page 121: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��,

�������� � �� ���# �#� ��$%� �& '���� ���������

$�-��� �������� - $���

The default sort order is ascending:

� Numeric values are displayed with the lowest values first, for example 1-999.

� Date values are displayed with the earliest value first, for example 01-JAN-92before 01-JAN-95.

� Character values are displayed in alphabetical order, for example A first and Zlast.

� In Oracle7, null values are displayed last for ascending sequences and first fordescending sequences.

�� ������ �#� $�-��� �����

To reverse the order in which rows are displayed, the command word DESC isspecified after the column name in the ORDER BY clause.

%)��*�

Query the employee table for employee last name, department number, and the hiredate for all employees. Sort the results by the most recently hired employee.

SQL> SELECT last_name, dept_id, start_date2 FROM s_emp3 ORDER BY start_date DESC;

LAST_NAME DEPT_ID START_DAT------------ ------- ---------...Urguhart 41 18-JAN-91Chang 44 30-NOV-90Patel 34 17-OCT-90Menchu 42 14-MAY-90...25 rows selected.

�������� ���# ' ��� .�����

You can use a column alias in the ORDER BY clause. This feature was madeavailable in Oracle7 release 7.0.16.

Page 122: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������/

Page 123: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��0

�������� � �� ���# �#� ��$%� �& '���� ���������

�������� �( � ���� �

Another method for sorting query results is to sort by position. This is especiallyuseful when sorting by a long expression. Rather than typing the expression again,you can specify its position in the SELECT list.

SQL> SELECT last_name, salary*122 FROM s_emp3 ORDER BY 2;

�������� �( 1��( ' ����

You can sort query results by more than one column. The sort limit is the number ofcolumns in the table.

In the ORDER BY clause, specify the columns, and separate the column names usingcommas. If you want to reverse the order of a column, specify DESC after its name orposition. You can order by columns that are not in the SELECT list.

%)��*�

Display the last name, department number, and salary of all employees. Order theresult by the department number, then in descending order by salary.

SQL> SELECT last name, dept_id, salary2 FROM s_emp3 ORDER BY dept_id, salary DESC;

LAST_NAME DEPT_ID SALARY------------ ------- ----------Quick-To-See 10 1450Nagayama 31 1400Magee 31 1400Giljum 32 1490Sedeghi 33 1515Nguyen 34 1525Patel 34 795...

Page 124: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������23

Page 125: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��22

�������� ������ � �� ���# �#� 45%�% '����

You can restrict the rows returned from the query by using the WHERE clause. AWHERE clause contains a condition that must be met, and directly follows theFROM clause.

�(���)

SELECT expr FROM table [WHERE condition(s)][ORDER BY expr];

where: WHERE restricts the query to rows that meet a condition.

condition is composed of column names, expressions,constants, and comparison operators.

' �*���� � �*���� ��

Comparison operators are divided into two categories: logical and SQL. They areused in the WHERE clause to compare one expression to another using the followingformat.

�(���)

...WHERE expr operator value

%)��*� 45%�% ����� ��

...WHERE dept_id = 42

Page 126: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������2�

Page 127: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��2�

' �*���� � �*���� ��

'#������ ������� ��� $����

Character strings and dates in the WHERE clause must be enclosed in singlequotation marks (‘ ’). Number constants, however, must not.

%)��*�

Write a query to show the first and last names, and title for the employee named“Magee.”

SQL> SELECT first_name, last_name, title2 FROM s_emp3 WHERE last_name = ’MAGEE’;

no rows selected

All character strings are case sensitive. Therefore, change the last name to be initialcapitals in order to acquire a match.

SQL> SELECT first_name, last_name, title2 FROM s_emp3 WHERE last_name = ’Magee’;

FIRST_NAME LAST_NAME TITLE------------ ------------- ---------------------Colin Magee Sales Representative

Page 128: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������2!

Page 129: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��2"

' �*���� � �*���� �� ���������

' �*���� � �*���� ��

Logical operators test the following conditions:

Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

��� �*���� ��

There are four SQL operators that operate with all datatypes:

Operator Meaning

BETWEEN...AND... Between two values (inclusive)

IN(list) Match any of a list of values

LIKE Match a character pattern

IS NULL Is a null value

� ��� �*���� ��

Operator Meaning

AND If both component conditions return TRUE, then theresult is TRUE.

OR If either component condition returns TRUE, then theresult is TRUE.

NOT Returns the opposite condition.

Page 130: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������2+

Page 131: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��2,

6������� %)*����� ��

You may find that it is easier to find the rows that do not meet a condition, rather thanthose that do. Use the comparison and SQL operators with a negative expression.

6������� � ��� �*���� ��

Operator Description

!= Not equal to (VAX, UNIX, PC)

^ =� =

Not equal to (IBM)

<> Not equal to (all operating systems)

NOT colname = Not equal to

NOT colname > Not greater than

6������� ��� �*���� ��

Operator Description

NOT BETWEEN...AND... Not between two specified values

NOT IN (list) Not in specified list of values

NOT LIKE Not like comparison string

IS NOT NULL Is not a null value

If you want to compare a known value to a null value, use either IS or IS NOT NULLcomparison operators. If you compare null values using the other operators, the resultis always FALSE.

For example, COMMISSION_PCT! = NULL is always FALSE because a null valuemay not be either equal or unequal to any other value, even another null value. Notethat an error is not raised, the result is simply always FALSE.

Page 132: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������2/

SQL> SELECT first_name, last_name, start_date 2 FROM s_emp 3 WHERE start_date BETWEEN ’09-may-91’ 4 AND ’17-jun-91’;

Page 133: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ��20

��� �*���� ��

7#� �%74%%6 �*���� �

You can display rows based on a range of values using the BETWEEN operator. Therange you specify contains a lower range and an upper range.

%)��*�

Display the first name, last name, and start date of employees whose start date isbetween May 9, 1991 and June 17, 1991, inclusive.

SQL> SELECT first_name, last_name, start_date2 FROM s_emp3 WHERE start_date BETWEEN ’09-may-91’ 4 AND ’17-jun-91’;

Values specified with the BETWEEN operator are inclusive. You must specify thelower limit first.

7#� �6 �*���� �

To test for values in a specified list, use the IN operator.

%)��*�

Display the department number, name, and region number of departments in regions1 or 3.

SQL> SELECT id, name, region_id2 FROM s_dept3 WHERE region_id IN (1,3);

If characters or dates are used in the list, they must be enclosed in single quotationmarks (‘ ’).

Page 134: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������3

SQL> SELECT last_name 2 FROM s_emp 3 WHERE last_name LIKE ’M%’;

Page 135: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���2

��� �*���� �� ���������

7#� ��8% �*���� �

You may not always know the exact value to search for. You can select rows thatmatch a character pattern by using the LIKE operator. The character pattern matchingoperation is referred to as a wildcard search. Two symbols can be used to constructthe search string.

Symbol Description

% Represents any sequence of zero or more characters.

_ Represents any single character.

%)��*�

Display all employee last names beginning with “M.”

SQL> SELECT last_name FROM s_empWHERE last_name LIKE ’M%’;

LAST_NAME------------MenchuMageeMaduroMarkarian

%)��*�

Display all employee last names that do not contain an “a” within the name.

SQL> SELECT last_name2 FROM s_emp3 WHERE last_name NOT LIKE ’%a%’;

Page 136: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ����������

Page 137: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ����

��� �*���� �� ���������

The LIKE operator can be used as a shortcut for some BETWEEN comparisons.

%)��*�

Display the last name and start date for employees who started with the company in1991.

SQL> SELECT last_name, start_date2 FROM s_emp3 WHERE start_date LIKE ’%91’;

' ����� 4����� '#�������

The % and _ symbols may be used in any combination with literal characters.

%)��*�

Display the last names of employees whose last name has an “a” as the second letter.

SQL> SELECT last_name2 FROM s_emp3 WHERE last_name LIKE ’_a%’;

7#� %�'.�% �*�� �

When you need to have an exact match for the actual “%” and “_” characters, use theESCAPE option. This option specifies what the ESCAPE character is.

%)��*�

Display the names of companies whose name contains “X_Y.”

SQL> SELECT name2 FROM s_customer3 WHERE name LIKE ’%X\_Y%’ ESCAPE ’\’;

Page 138: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������!

Page 139: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���"

��� �*���� �� ���������

�� 6��� �*���� �

The IS NULL operator tests for values that are null. A null value means the value isunavailable, unassigned, unknown, or inapplicable. Therefore, you cannot test with“=” because a null value cannot be equal or unequal to any value.

%)��*�

Display the customer number, name, and credit rating of all customers who do nothave a sales representative.

SQL> SELECT id, name, credit_rating 2 FROM s_customer3 WHERE sales_rep_id = NULL;

no rows selected

SQL> SELECT id, name, credit_rating 2 FROM s_customer3 WHERE sales_rep_id = ’’;

no rows selected

SQL> SELECT id, name, credit_rating 2 FROM s_customer3 WHERE sales_rep_id IS NULL;

ID NAME CREDIT_RA------- -------------------- --------- 207 Sweet Rock Sports GOOD

%)��*�

Display all employee last names, titles, and commission percentages who make acommission.

SQL> SELECT last_name, title, commission_pct2 FROM s_emp3 WHERE commission_pct IS NOT NULL;

Page 140: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������+

SQL> SELECT last_name, salary, dept_id, title 2 FROM s_emp 3 WHERE dept_id = 41 4 AND title = ’Stock Clerk’;

Page 141: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���,

����(��� $��� ���# 1���*� ' ����� ��

You may need to specify complex criteria by combining several search conditions.The AND and OR operators may be used to make compound logical expressions.

The AND operator returns TRUE if both conditions evaluate to TRUE, whereas theOR operator returns TRUE if either condition is TRUE.

In the following two examples, the conditions are the same, but the operator isdifferent. See how the result is dramatically changed.

%)��*� 2

Display the last name, salary, department number, and title for all stock clerks indepartment 41.

SQL> SELECT last_name, salary, dept_id, title2 FROM s_emp3 WHERE dept_id = 414 AND title = ’Stock Clerk’;

%)��*� �

Display the last name, salary, department number, and title for all employees who areeither stock clerks or who are in department 41.

SQL> SELECT last_name, salary, dept_id, title2 FROM s_emp3 WHERE dept_id = 414 OR title = ’Stock Clerk’;

Note: OR is a less restrictive clause. Consequently, more rows may be returned.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Logical Operators.”

Page 142: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������/

����� % ������ �*���� �

2 . �*���� � *���� ��9

� .6$

� ��

Page 143: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���0

���� - ��������

You may combine AND and OR operators in the same logical expression. The resultsof all of the conditions are combined in the order determined by the precedence of theconnecting operators. Where operators of equal precedence are used next to eachother, they are performed from left to right.

Each AND is performed first then each OR is performed. AND has a higherprecedence than OR.

���� - ��������

Order Evaluated Operator

1 All comparison operators(=, <>, >, >=, <, <=, IN, LIKE, IS NULL, BETWEEN)

2 AND

3 OR

Note: When using a negating expression, comparison operators still evaluate first.

Override precedence rules by placing part of an expression in parentheses; the OracleServer evaluates expressions in parentheses first.

Whenever you are in doubt about which of two operations will be performed firstwhen an expression is evaluated, use parentheses to clarify your statements.

Page 144: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������3

Page 145: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���2

���� - �������� ���������

%)��*� 2

Display the last name, salary, and department number for those employees indepartment 44 who earn 1000 or more, as well as all employees in department 42.

SQL> SELECT last_name, salary, dept_id2 FROM s_emp3 WHERE salary >= 1000 4 AND dept_id = 445 OR dept_id = 42;

LAST_NAME SALARY DEPT_ID------------ ------------ --------Menchu 1250 42Catchpole 1300 44Nozaki 1200 42Patel 795 42

%)��*� �

Display the last name, salary, and department number for those employees indepartment 44 or 42 who earn 1000 or more.

SQL> SELECT last_name, salary, dept_id2 FROM s_emp3 WHERE salary >= 1000 4 AND (dept_id = 445 OR dept_id = 42);

LAST_NAME SALARY DEPT_ID------------ ------------ --------Menchu 1250 42Catchpole 1300 44Nozaki 1200 42

Page 146: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ����������

Page 147: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ����

������(

In this lesson, you have learned about sorting rows and restricting the rows returnedby the SELECT statement. You have also learned how to implement comparisonoperators.

�(���)

SELECT [DISTINCT] {*,column [alias],....} FROM table [WHERE condition(s)][ORDER BY {column,expr} [ASC|DESC]];

where: SELECT is a list of at least one column.

DISTINCT suppresses duplicates.

* selects all columns.

column selects the named column.

alias gives selected columns a different heading.

FROM table specifies the table containing the columns.

WHERE restricts the query to rows that meet a condition.

condition is composed of column names, expressions,constants, and comparison operators.

ORDER BY specifies the order in which the retrieved rowsare displayed.

ASC orders rows in ascending order.

DESC orders the rows in descending order.

Page 148: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������!

Page 149: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���"

������ � �� ���

This practice gives you a variety of exercises using the WHERE clause and theORDER BY clause.

������ ' ������

� Selecting data and changing the order of rows displayed.

� Using the WHERE clause to restrict rows, with a combination of logical andSQL operators.

� Using column aliases.

��*�������� ������ ��

For questions 1–3, circle either True or False.

Page 150: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������+

Page 151: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���,

������ �

1. You cannot order by a column that you have not selected. True / False

2. This SELECT statement will execute successfully. True / False

SQL> Select last_name, title, salary Ann_sal2 From s_emp3 Where last_name = ’Dancs’;

3. This SELECT statement will execute successfully. True / False

SQL> select *2 from s_emp3 where salary*12 = 9600;

4. There are four coding errors in this statement. Can you identify them?

SQL> SELECT id, last_name, 2 salary x 12 ANNUAL SALARY3 FROM s_emp4 WHERE sal > 30005 AND start_date LIKE %84;

Page 152: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ���������/

������ � ���������

5. Use the S_CUSTOMER table and perform the following actions.

a. Create a query to display the name, customer number, and credit rating for allcompanies represented by sales representative 11. Save your SQL statement toa file named p2q5.

b. Run your query in the file p2q5.

c. Load p2q5 into the SQL buffer. Name the column headings Company,Company ID, and Rating. Rerun your query. Re-save your query as p2q5.

Company Company ID Rating--------------------------––––––––––– ––––––––Womansport 204 GOODBeisbol Si! 209 GOODBig John’s Sports Emporium 213 GOODOjibway Retail 214 GOOD

d. Retrieve p2q5 into the SQL buffer. Order the query results in descendingorder by customer number. Run your query.

6. Show the structure of the S_EMP table.

a. Display the user name for employee 23.

b. Display the first name, last name, and department number of the employees indepartments 10 and 50 in alphabetical order of last name. Merge the firstname and last name together, and title the column Employees.

Employees DEPT_ID----------------------------------- ---------Mark Quick-To-See 10Audry Ropeburn 50Carmen Velasquez 50

c. Display all employees whose last names contain an “s.”

d. Display the user names and start date of employees hired between May 14,1990 and May 26, 1991. Order the query results by start date ascending order.

Page 153: OCP - SQL&PL_SQL(Vol1)

�������� ������ � �� ���0

������ � ���������

If you have time, complete the following exercises.

7. Use the S_EMP table to perform the following actions.

a. Write a query to show the last name and salary of all employees who are notmaking between 1000 and 2500 per month.

b. List the last name and salary of employees who earn more than 1350 who arein department 31, 42, or 50. Label the last name column Employee Name, andlabel the salary column Monthly Salary.

c. Display the last name and start date of every employee who was hired in1991.

d. Display the full name of all employees with no manager.

8. Show the structure of S_PRODUCT table.

a. Alphabetically display all products having a name beginning with Pro.

b. Display all product names and short descriptions for all descriptionscontaining the word “bicycle.”

c. Display all short descriptions. Compare the results from Exercise 8b. Did yourresponse in Exercise 8b return all descriptions containing bicycle?

Page 154: OCP - SQL&PL_SQL(Vol1)

���� ���� � � ����� ��� ��� ������ ����� �� ����� ��������!3

Page 155: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ����

Page 156: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������

Page 157: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���

����� � ��

Functions make the basic query block more powerful and are used tomanipulate data values. This is the first of two lessons that explore functions.You will focus on single row character, number, and date functions, as well asthose functions that convert data from one type to another, for example,character data to numeric.

At the end of this lesson, you should be able to

� Explain the various types of functions available in SQL.

� Identify the basic concepts of using functions.

� Use a variety of character, number, and date functions in SELECT statements.

� Explain the conversion functions and how they might be used.

Page 158: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������!

Page 159: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��"

� �� ��

Functions are a very powerful feature of SQL and can be used to

� Perform calculations on data.

� Modify individual data items.

� Manipulate output for groups of rows.

� Alter date formats for display.

� Convert column datatypes.

There are two distinct types of functions:

� Single row functions.

� Multiple row functions.

������ �� ��� ����

These functions operate on single rows only, and return one result per row. There aredifferent types of single row functions. We will cover those listed below.

� Character

� Number

� Date

� Conversion

#�� �$�� �� ��� ����

These functions manipulate groups of rows to give one result per group of rows.

For more information, seeOracle7 Server SQL Reference, Release 7.3 for the complete list of availablefunctions and syntax.

Page 160: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������%

Page 161: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��&

������ �� ��� ����

Single row functions are used to manipulate data items. They accept one or morearguments and return one value for each row returned by the query. An argument maybe one of the following:

� A user-supplied constant

� A variable value

� A column name

� An expression

�� ���� �' ������ �� ��� ����

� They act on each row returned in the query.

� They return one result per row.

� They may return a data value of a different type than that referenced.

� They may expect one or more user arguments.

� You can nest them.

� You can use them in SELECT, WHERE, and ORDER BY clauses.

�(� �)

function_name (column|expression, [arg1, arg2,...])

where: function_name is the name of the function.

column is any named database column.

expression is any character string or calculated expression.

arg1, arg2 is any argument to be used by the function.

Page 162: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������*

Page 163: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��+

,-���� �� ��� ����

Single row character functions accept character data as input and can return bothcharacter and number values.

Function Purpose

LOWER(column|expression) Converts alpha character values to lowercase.

UPPER(column|expression) Converts alpha character values to uppercase.

INITCAP(column|expression) Converts alpha character values to uppercasefor the first letter of each word, all otherletters in lowercase.

CONCAT(column1|expression1,column2|expression2)

Concatenates the first character value to thesecond character value. Equivalent toconcatenation operator (||).

SUBSTR(column|expression,m[,n]) Returns specified characters from charactervalue starting at character position m, ncharacters long. If m is negative, the countstarts from the end of the character value.

LENGTH(column|expression) Returns the number of characters in value.

NVL(column|expression1,column|expression2)

Converts the the first value if null to thesecond value.

Note: This list is a subset of the available character functions.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Character Functions.”

Page 164: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������./

Page 165: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��..

,-���� �� ��� ���� ���������

0)�1$��

Display the first and last name in lowercase, userid in initial capitalization, and title inuppercase for all vice presidents.

SQL> SELECT LOWER(first_name||’ ’||last_name) VP,2 INITCAP(userid) USERID,3 UPPER(title) TITLE4 FROM s_emp5 WHERE title LIKE ’VP%’;

VP USERID TITLE--------------------- -------- -------------------ladoris ngao Lngao VP, OPERATIONSmidori nagayama Mnagayam VP, SALESmark quick-to-see Mquickto VP, FINANCEaudry ropeburn Aropebur VP, ADMINISTRATION

Page 166: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������.�

Page 167: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��.�

,-���� �� ��� ���� ���������

0)�1$��

Display the first name and last name of all employees with the last name of Patel.

SQL> SELECT first_name, last_name2 FROM s_emp3 WHERE last_name = ’PATEL’;

no rows returned

SQL> SELECT first_name, last_name2 FROM s_emp3 WHERE UPPER(last_name) = ’PATEL’;

FIRST_NAME LAST_NAME-------------------- --------------------Vikram PatelRadha Patel

Note: The name is displayed as it was stored in the database. To display the name inuppercase, the UPPER function must be used in the SELECT clause as well.

Page 168: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������.!

Page 169: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��."

,-���� �� ��� ���� ���������

0)�1$��

Display the name and country of all customers with a good credit rating. Concatenatename and country.

SQL> SELECT CONCAT (name, country) CUSTOMER 2 FROM s_customer3 WHERE credit_rating = ’GOOD’;

CUSTOMER-------------------------------------------------Delhi SportsIndiaSweet Rock SportsNigeria

0)�1$��

Display the product name and length of name for all products where the first threecharacters are Ace.

SQL> SELECT name, LENGTH(name)2 FROM s_product3 WHERE SUBSTR(name,1,3) = ’Ace’;

NAME LENGTH(NAME)-------------------- ------------Ace Ski Boot 12Ace Ski Pole 12

Page 170: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������.%

Page 171: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��.&

2�1��� ��� ����

Number functions accept numeric input and return numeric values. This sectiondescribes some of the number functions.

Function Purpose

ROUND(column|expression,n) Rounds the column, expression, or value to ndecimal places. If n is omitted, no decimalplaces. If n is negative, numbers to left of thedecimal point are rounded.

TRUNC(column|expression,n) Truncates the column or value to n decimalplaces, or if n is omitted, no decimal places. If nis negative, numbers left of the decimal pointare truncated to zero.

MOD(m,n) Returns the remainder of m divided by n.

Note: This list is a subset of the available number functions.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Number Functions.”

Page 172: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������.*

Page 173: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��.+

2�1��� ��� ���� ���������

The TRUNC and ROUND functions work with similar arguments. If the secondargument is 0 or is missing, then the value is truncated or rounded to zero decimalplaces. If the second argument is 2, then the value is truncated or rounded to twodecimal places, or to the hundredths. Conversely, if the second argument is -2, thenthe value is truncated or rounded to two decimal places to the left, or to the hundreds.

Note: ROUND and TRUNC may also be used with date functions. You will seeexamples later in this lesson.

0)�1$��

Display the value 45.923 rounded to the hundredth, no, and ten decimal places.

SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),2 ROUND(45.923,-1)3 FROM SYS.DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)--------------- --------------- ---------------- 45.92 46 50

0)�1$��

Display the value 45.923 truncated to the hundredth, no, and ten decimal places.

SQL> SELECT TRUNC(45.923,2), TRUNC(45.923),2 TRUNC(45.923,-1)3 FROM SYS.DUAL;

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)--------------- --------------- ---------------- 45.92 45 40

SYS.DUAL is a dummy table. It will be covered in detail later in this lesson.

Page 174: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������/

Page 175: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���.

2�1��� ��� ���� ���������

0)�1$��

Calculate the remainder of the ratio of salary to commission for all employees whosesalary is more than 1400.

SQL> SELECT last_name, MOD(salary,commission_pct)2 FROM s_emp3 WHERE salary > 1400;

LAST_NAME MOD(SALARY,COMMISSION_PCT)------------ --------------------------VelasquezNgaoQuick-To-SeeRopeburnGiljum 2.5Sedeghi 5Nguyen 10Dumas 15

8 rows selected.

Page 176: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� �����������

Page 177: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ����

������ 3� � ��1�

������ 3� � � �����

Oracle stores dates in an internal numeric format, representing the following:

� Century

� Year

� Month

� Day

� Hours

� Minutes

� Seconds

The default display and input format for any date is DD-MON-YY. Valid Oracle datesare between January 1, 4712 B.C. and December 31, 4712 A.D.

�4�3560

SYSDATE is a date function that returns the current date and time. You can useSYSDATE just as you would use any other column name. For example, you candisplay the current date by selecting SYSDATE from a table. It is customary to selectSYSDATE from a dummy table called DUAL.

3�5�

The DUAL table is owned by the user SYS and may be accessed by all users. Itcontains one column, DUMMY, and one row with the value “X.” The DUAL table isuseful when you want to return a value once only, for instance, the value of aconstant, pseudo-column, or expression that is not derived from a table with userdata.

0)�1$��

Display the current date using the DUAL table.

SQL> SELECT SYSDATE 2 FROM SYS.DUAL;

Page 178: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������!

Page 179: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���"

����� 5�� -1� �� �$��� ��� � - 3� ��

Since the database stores dates as numbers, you can perform calculations usingarithmetic operators such as addition and subtraction. You can add and subtractnumber constants as well as dates.

5�� -1� �� �$��� ���� �� 3� ��

You can perform the following operations:

Operation Result Description

date + number date Adds a number of days to a date.

date - number date Subtracts a number of days from a date.

date - date number of days Subtracts one date from another.

date + number/24 date Adds a number of hours to a date.

0)�1$��

For employees in department 43, display the last name and number of weeksemployed.

SQL> SELECT last_name, (SYSDATE-start_date)/7 WEEKS2 FROM s_emp3 WHERE dept_id = 43;

LAST_NAME WEEKS------------ ----------Biri 297.226498Markarian 238.083641Newman 230.083641

Note: SYSDATE is a SQL function that returns the current date and time. Yourresults may differ from the examples.

Page 180: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������%

Page 181: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���&

3� � ��� ����

Date functions operate on Oracle dates. All date functions return a value of DATEdatatype except MONTHS_BETWEEN, which returns a numeric value.

Function Purpose

MONTHS_BETWEEN(date1, date2) Finds the number of months betweendate1 and date2. The result can bepositive or negative. If date1 is later thandate2, the result is positive; if date1 isearlier than date2, the result is negative.The non-integer part of the resultrepresents a portion of the month.

ADD_MONTHS(date,n) Adds n number of calender months todate. n must be an integer and can benegative

NEXT_DAY(date,‘char’) Finds the date of the next specified dayof the week (‘char’) following date.char may be a number representing aday or a character string.

LAST_DAY(date) Finds the date of the last day of themonth that contains date.

ROUND(date[,‘fmt’]) Finds the date of first day of the monthcontained in date when no format modelfmt is specified. If fmt = YEAR, findsfirst day of year containing date. This isuseful when comparing dates that mayhave different times.

TRUNC(date[,‘fmt’]) Returns date with the time set tomidnight if no format model fmt isspecified. This function is useful whenyou want to remove the time portion ofthe date.

Note: This list is a subset of the available date functions. The format models arecovered later in this chapter. Examples of format models are month or year.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Date Functions.”

Page 182: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������*

Page 183: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���+

3� � ��� ���� ���������

0)�1$��

For all employees employed less than 48 months, display the employee number, startdate, number of months employed, and the 6 month review date.

SQL> SELECT id, start_date, 2 MONTHS_BETWEEN (SYSDATE,start_date) TENURE,3 ADD_MONTHS(start_date,6) REVIEW4 FROM s_emp5 WHERE MONTHS_BETWEEN (SYSDATE,start_date)<48;

ID START_DAT TENURE REVIEW------ --------- ---------- --------- 9 09-FEB-92 44.1163486 09-AUG-92 12 18-JAN-92 44.826026 18-JUL-92 14 22-JAN-92 44.6969937 22-JUL-92 16 07-FEB-92 44.1808647 07-AUG-92

0)�1$��

For inventory items that have been restocked, display in chronological order theproduct number, first Friday after the restock date, and the last day of the month whenit was restocked.

SQL> SELECT product_id,2 NEXT_DAY (restock_date,’FRIDAY’),3 LAST_DAY (restock_date)4 FROM s_inventory5 WHERE restock_date IS NOT NULL6 ORDER BY restock_date;

PRODUCT_ID NEXT_DAY( LAST_DAY(---------- --------- --------- 30433 11-SEP-92 30-SEP-92 40422 12-FEB-93 28-FEB-93 50532 16-APR-93 30-APR-93

Page 184: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������/

Page 185: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���.

3� � ��� ���� ���������

The ROUND and TRUNC functions can be used for number and date values. Whenusing these functions with dates, they round or truncate to the specified format model.Therefore, you can round dates to the nearest year or month.

0)�1$��

Compare the start dates for all employees who started in 1991. Display the employeenumber, start date, and month started using both the ROUND and TRUNC functions.

SQL> SELECT id, start_date, 2 ROUND(start_date, ’MONTH’),3 TRUNC(start_date, ’MONTH’)4 FROM s_emp5 WHERE start_date LIKE ’%91’;

ID START_DAT ROUND(STA TRUNC(STA------ --------- --------- --------- 3 17-JUN-91 01-JUL-91 01-JUN-91 6 18-JAN-91 01-FEB-91 01-JAN-91 10 27-FEB-91 01-MAR-91 01-FEB-91 13 18-FEB-91 01-MAR-91 01-FEB-91 15 09-OCT-91 01-OCT-91 01-OCT-91 18 09-FEB-91 01-FEB-91 01-FEB-91 19 06-AUG-91 01-AUG-91 01-AUG-91 20 21-JUL-91 01-AUG-91 01-JUL-91 21 26-MAY-91 01-JUN-91 01-MAY-91 24 17-MAR-91 01-APR-91 01-MAR-91 25 09-MAY-91 01-MAY-91 01-MAY-91

11 rows selected.

Page 186: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� �����������

Page 187: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ����

,�� ������ ��� ����

SQL provides three functions to convert a value from one datatype to another.

Function Purpose

TO_CHAR(number|date,[‘fmt’]) Converts a number or date value to aVARCHAR2 character string withformat model fmt.

TO_NUMBER(char) Converts a character string containingdigits to a number.

TO_DATE(char,[‘fmt’]) Converts a character string representinga date to a date value according to thefmt specified. If fmt is omitted, format isDD-MON-YY.

Note: This list is a subset of the available conversion functions.

For more information, seeOracle7 Server SQL Reference, Release 7.3, “Conversion Functions.”

Page 188: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������!

Page 189: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���"

6�7,85� ��� ��� � - 3� � ��1� �

3��$��(��� � 3� � �� � �$���'�� ��1�

Previously, all Oracle date values were displayed in the DD-MON-YY format. TheTO_CHAR function allows you to convert a date from this default format to onespecified by you.

9���������

� The format model must be enclosed in single quotation marks and iscase-sensitive.

� The format model can include any valid date format element. Be sure to separatethe date value from the format model by a comma.

� The names of days and months in the output are automatically padded withblanks.

� To remove padded blanks or to suppress leading zeros, use the fill mode fmelement.

� You can resize the display width of the resulting character field with theSQL*Plus COLUMN command.

� The resultant column width is 80 characters by default.

0)�1$��

Display the order number and date ordered for all orders taken by sales representative11. Format the date to display the date as 08/92.

SQL> SELECT ID,TO_CHAR(date_ordered,’MM/YY’) ORDERED2 FROM s_ord3 WHERE sales_rep_id = 11;

ID ORDERED------- ------------------- 100 08/92 105 09/92 109 09/92 110 09/92 111 09/92

Page 190: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������%

Page 191: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���&

6�7,85� ��� ��� � - 3� � ��1� � ���������

��1$�� :���� 3� � ��1� 0��1�� �

Element Description

SCC or CC Century; S prefixes BC date with -.

Years in dates YYYY or SYYYY Year; S prefixes BC date with -.

YYY or YY or Y Last 3, 2, or 1 digit(s) of year.

Y,YYY Year with comma in this position.

IYYY, IYY, IY, I 4, 3, 2, or 1 digit year based on the ISOstandard.

SYEAR or YEAR Year spelled out; S prefixes BC date with -.

BC or AD BC/AD indicator.

B.C. or A.D. BC/AD indicator with periods.

Q Quarter of year.

MM Month, 2-digit value.

MONTH Name of month padded with blanks tolength of 9 characters.

MON Name of month, 3-letter abbreviation.

RM Roman numeral month.

WW or W Week of year or month.

DDD or DD or D Day of year, month, or week.

DAY Name of day padded with blanks to lengthof 9 characters.

DY Name of day; 3-letter abbreviation.

J Julian day; the number of days since 31December 4713 BC.

Page 192: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ����������*

Page 193: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ���+

6�7,85� ��� ��� � - 3� � ��1� � ���������

6�1� ��1� �

Use the formats listed in the following tables to display time information and literals,and to change numerals to spelled numbers.

Element Description

AM or PM Meridian indicator.

A.M. or P.M. Meridian indicator with periods.

HH or HH12 or HH24 Hour of day or hour (1-12) or hour (0-23)

MI Minute (0-59).

SS Second (0-59).

SSSSS Seconds past midnight (0-86399).

� -�� ��1� �

Element Description

/ . , Punctuation is reproduced in the result.

“ of the ” Quoted string is reproduced in the result.

����� -� # ���'�)

The FM prefix suppresses blank padding in month and day names, leaving avariable-length result. It also suppresses leading zeros in numbers. A secondoccurrence of FM turns blank padding on again.

�$���'(��� ��''�)�� � ��'������ 2�1��� 3��$��(

Suffix Description

TH Ordinal number (for example, DDTH for 4TH).

SP Spelled-out number (for example, DDSP for FOUR).

SPTH or THSP Spelled-out ordinal numbers (for example, DDSPTHfor FOURTH).

Page 194: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������!/

Page 195: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��!.

6�7,85� ��� ��� � - 3� � ��1� � ���������

6-� �� 3� � ��1� 0��1��

The RR date format is similar to the YY element, but it allows you to specifydifferent centuries. You can use the RR date format element instead of YY, so that thecentury of the return value varies according to the specified two-digit year and thelast two digits of the current year. The table on the opposite page summarizes thebehavior of the RR element.

Current Year Given Date Interpreted (RR) Interpreted (YY)

1994 27-OCT-95 1995 1995

1994 27-OCT-17 2017 1917

2001 27-OCT-17 2017 2017

Page 196: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������!�

Page 197: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��!�

6�7,85� ��� ��� � - 3� � ��1� � ���������

0)�1$��

Display the names and hire dates for all employees hired in 1991. The hire dateshould look like 7 of February 1991.

SQL> SELECT last_name, TO_CHAR(start_date, 2 ’fmDD ”of” Month YYYY’) HIREDATE3 FROM s_emp4 WHERE start_date LIKE ’%91’;

LAST_NAME HIREDATE------------ --------------------Nagayama 17 of June 1991Urguhart 18 of January 1991Havel 27 of February 1991...

0)�1$��

Modify the above example to display the dates in a format that looks like Seventh ofFebruary 1991 08:00:00 AM.

SQL> SELECT last_name, TO_CHAR(start_date, 2 ’fmDdspth ”of” Month YYYY fmHH:MI:SS AM’)3 HIREDATE4 FROM s_emp5 WHERE start_date LIKE ’%91’;

LAST_NAME HIREDATE------------ ------------------------------------Nagayama Seventeenth of June 1991 12:00:00 AMUrguhart Eighteenth of January 1991 12:00:00 AMHavel Twenty-Seventh of February 1991 12:00:00...

Page 198: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������!!

Page 199: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��!"

6�7,85� ��� ��� � - 2�1��� ��1� �

When working with number values such as character strings, you should convertthose numbers to the character datatype using the TO_CHAR function, whichtranslates a value of NUMBER datatype to VARCHAR2 datatype. This technique isespecially useful with concatenation.

2�1��� ��1� 0��1�� �

If you are converting a character datatype that converts digits into a number, you canuse the elements listed below.

Element Description Example Result

9 Numeric position (number of 9sdetermine display width).

999999 1234

0 Display leading zeros. 099999 001234

$ Floating dollar sign. $999999 $1234

L Floating local currency symbol. L999999 FF1234

. Decimal point in position specified. 999999.99 1234.00

, Comma in position specified. 999,999 1,234

MI Minus signs to right (negative values). 999999MI 1234-

PR Parenthesize negative numbers. 999999PR <1234>

EEEE Scientific notation (format mustspecify four Es).

99.999EEEE 1.234E+03

V Multiply by 10 n times (n=no of 9safter V).

9999V99 123400

B Display zero values as blank, not 0. B9999.99 1234.00

Page 200: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������!%

Page 201: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��!&

6�7,85� ��� ��� � - 2�1��� ��1� � ���������

0)�1$��

Display a message indicating that the order, represented by its number, was filled forall orders shipped on September 21, 1992. Be sure to include the total for the order.

SQL> SELECT ’Order ’||TO_CHAR(id)||2 ’ was filled for a total of ’3 ||TO_CHAR(total,’fm$9,999,999’) 4 FROM s_ord5 WHERE date_shipped = ’21-SEP-92’;

NOTE------------------------------------------------------Order 107 was filled for a total of $142,171Order 110 was filled for a total of $1,539Order 111 was filled for a total of $2,770

9���������

� The Oracle7 Server displays a string of pound signs (#) in place of a wholenumber whose digits exceed the number of digits provided in the format model.

� The Oracle7 Server rounds the stored decimal value to the number of decimalspaces provided in the format model.

Page 202: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������!*

Page 203: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��!+

6�72�#�0� ��� 6�73560 ��� ����

You may want to convert a character string to either a number or a date format. Toaccomplish this task, you use the TO_NUMBER or TO_DATE functions,respectively. The format model you choose will be based on the previouslydemonstrated format elements.

0)�1$��

Show all orders placed on September 7, 1992. Convert the date string you see here tothe date format.

SQL> SELECT id, total, date_ordered2 FROM s_ord3 WHERE date_ordered = 4 TO_DATE(’September 7, 1992’,’Month dd, YYYY’);

ID TOTAL DATE_ORDE------ ---------- --------- 106 15634 07-SEP-92 107 142171 07-SEP-92 108 149570 07-SEP-92

Page 204: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������"/

� �$ . ; ����� .

� �$ � ; ����� �

� �$ � ; ����� �

Page 205: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��".

2�� ��� ������ �� ��� ����

2�� ��� ��� ����

Single row functions can be nested to any depth. Nested functions are evaluated fromthe innermost level to the outermost level. Some examples follow to show you theflexibility of these functions.

0)�1$��

Display the last name in upper case and part of the department name of all vicepresidents as a string under the title Vice Presidents.

SQL> SELECT CONCAT(UPPER(last_name),2 SUBSTR(title,3)) ”Vice Presidents”3 FROM s_emp4 WHERE title LIKE ’VP%’;

Vice Presidents----------------------------------------------------NGAO, OperationsNAGAYAMA, SalesQUICK-TO-SEE, FinanceROPEBURN, Administration

Page 206: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������"�

Page 207: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��"�

2�� ��� ��� ����

0)�1$��

Display the head of the company, who has no manager. Display that there is nomanager number for that name.

SQL> SELECT last_name, 2 NVL(TO_CHAR(manager_id),’No Manager’)3 FROM s_emp4 WHERE manager_id IS NULL;

LAST_NAME NVL(TO_CHAR(MANAGER_ID),’NOMANAGER’)------------ ----------------------------------------Velasquez No Manager

Notice that the entire expression becomes the column heading since no column aliaswas given.

0)�1$��

Display the date of the next Friday that is six months from the order date. Theresultant date should look like Friday, March 12th, 1993.

SQL> SELECT TO_CHAR(NEXT_DAY(ADD_MONTHS2 (date_ordered,6),’FRIDAY’),3 ’fmDay, Month ddth, YYYY’)4 ”New 6 Month Review”5 FROM s_ord6 ORDER BY date_ordered;

New 6 Month Review----------------------------------...Friday, March 5th, 1993Friday, March 5th, 1993Friday, March 12th, 1993...

Page 208: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������"!

Page 209: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��""

��11��(

������ �� ��� ����

Single row functions can be nested to any level. Single row functions can manipulate

� Character data.

� LOWER, UPPER, INITCAP, CONCAT, SUBSTR, LENGTH

� Number data.

� ROUND, TRUNC, MOD

� Date data.

� MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY,ROUND, TRUNC

� Date values can also use arithmetic operators

Conversion functions can convert character, date, and numeric values.

� TO_CHAR, TO_DATE, TO_NUMBER

�4�3560 ��� 3�5�

SYSDATE is a date function that returns the current date and time. It is customary toselect SYSDATE from a dummy table called DUAL.

Page 210: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������"%

Page 211: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��"&

���� ��� � �� ��

This practice is designed to give you a variety of exercises using different functionsavailable for character, number, and date datatypes.

���� ��� ,�� �� �

� Creating queries that require the use of numeric, character, and date functions

� Using concatenation with functions

� Writing case-insensitive queries to test the usefulness of character functions if youare unsure exactly how character date is stored

� Performing calculations of years and months of service for an employee

� Determining the review date for an employee

Remember that for nested functions, the results are evaluated from the innermostfunction to the outermost function.

Page 212: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������"*

Page 213: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��"+

���� ��� �

1. Single row functions work on many rows to produce a single result. True / False

2. You can use all of the arithmetic operators on date values. True / False

3. What is the name of the function that holds the current date?

4. Display the employee number, last name, and salary increased by 15% andexpressed as a whole number.

ID LAST_NAME NEW SALARY------ ------------ ------------------ 1 Velasquez 2875 2 Ngao 1668 3 Nagayama 1610 4 Quick-To-See 1668 5 Ropeburn 1783 6 Urguhart 1380 7 Menchu 1438 8 Biri 1265 9 Catchpole 1495 10 Havel 1503 11 Magee 1610 12 Giljum 1714 13 Sedeghi 1742 14 Nguyen 1754 15 Dumas 1668 16 Maduro 1610 17 Smith 1081 18 Nozaki 1380 19 Patel 914 20 Newman 863 21 Markarian 978 22 Chang 920 23 Patel 914 24 Dancs 989 25 Schwartz 1265

25 rows selected.

Page 214: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������%/

���� ��� � ���������

5. Display the employee last name and title in parentheses for all employees. Thereport should look like the output below.

EMPLOYEE----------------------------------------------------Biri(Warehouse Manager)Catchpole(Warehouse Manager)Chang(Stock Clerk)Dancs(Stock Clerk)Dumas(Sales Representative)Giljum(Sales Representative)Havel(Warehouse Manager)Maduro(Stock Clerk)Magee(Sales Representative)Markarian(Stock Clerk)Menchu(Warehouse Manager)Nagayama(Vp, Sales)Newman(Stock Clerk)Ngao(Vp, Operations)Nguyen(Sales Representative)Nozaki(Stock Clerk)Patel(Stock Clerk)Patel(Stock Clerk)Quick-To-See(Vp, Finance)Ropeburn(Vp, Administration)Schwartz(Stock Clerk)Sedeghi(Sales Representative)Smith(Stock Clerk)Urguhart(Warehouse Manager)Velasquez(President)

25 rows selected.

Page 215: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��%.

���� ��� � ���������

6. Display each employee’s last name, hire date, and salary review date, which is thefirst Monday after six months of service. Format the dates to appear in the formatsimilar to Eighth of May 1992.

LAST_NAME START_DAT REVIEW------------ --------- ------------------------------Velasquez 03-MAR-90 Tenth of September 1990Ngao 08-MAR-90 Tenth of September 1990Nagayama 17-JUN-91 Twenty-Third of December 1991Quick-To-See 07-APR-90 Eighth of October 1990Ropeburn 04-MAR-90 Tenth of September 1990Urguhart 18-JAN-91 Twenty-Second of July 1991Menchu 14-MAY-90 Nineteenth of November 1990Biri 07-APR-90 Eighth of October 1990Catchpole 09-FEB-92 Tenth of August 1992Havel 27-FEB-91 Second of September 1991Magee 14-MAY-90 Nineteenth of November 1990Giljum 18-JAN-92 Twentieth of July 1992Sedeghi 18-FEB-91 Nineteenth of August 1991Nguyen 22-JAN-92 Twenty-Seventh of July 1992Dumas 09-OCT-91 Thirteenth of April 1992Maduro 07-FEB-92 Tenth of August 1992Smith 08-MAR-90 Tenth of September 1990Nozaki 09-FEB-91 Twelfth of August 1991Patel 06-AUG-91 Tenth of February 1992Newman 21-JUL-91 Twenty-Seventh of January 1992Markarian 26-MAY-91 Second of December 1991Chang 30-NOV-90 Third of June 1991Patel 17-OCT-90 Twenty-Second of April 1991Dancs 17-MAR-91 Twenty-Third of September 1991Schwartz 09-MAY-91 Eleventh of November 1991

25 rows selected.

Page 216: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������%�

���� ��� � ���������

7. Display the product name for products that have “ski” in the name.

NAME--------------------Ace Ski BootPro Ski BootBunny Ski PoleAce Ski PolePro Ski Pole

Page 217: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��%�

���� ��� � ���������

If you have time, complete the following exercises.

8. For each employee, calculate the number of months between today and the datethe employee was hired. Order your result by the number of months employed.Round the number of months up to the closest whole number.

LAST_NAME MONTHS_WORKED------------ -------------Catchpole 46Maduro 46Nguyen 47Giljum 47Dumas 50Patel 52Newman 53Nagayama 54Markarian 55Schwartz 55Dancs 57Havel 58Sedeghi 58Nozaki 58Urguhart 59Chang 61Patel 62Menchu 67Magee 67Quick-To-See 68Biri 68Ngao 69Smith 69Ropeburn 69Velasquez 69

25 rows selected.

Note: Your MONTHS_WORKED may differ from the solution because yourSYSDATE may return a different value.

Page 218: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������%!

���� ��� � ���������

9. Display the last name for all employees and the day of the week they started.Order the results by the day of the week starting with Monday.

LAST_NAME START_DAT DAY------------ --------- ----------Nagayama 17-JUN-91 MONDAYMenchu 14-MAY-90 MONDAYSedeghi 18-FEB-91 MONDAYMagee 14-MAY-90 MONDAYPatel 06-AUG-91 TUESDAYHavel 27-FEB-91 WEDNESDAYPatel 17-OCT-90 WEDNESDAYNguyen 22-JAN-92 WEDNESDAYDumas 09-OCT-91 WEDNESDAYNgao 08-MAR-90 THURSDAYSmith 08-MAR-90 THURSDAYSchwartz 09-MAY-91 THURSDAYUrguhart 18-JAN-91 FRIDAYChang 30-NOV-90 FRIDAYMaduro 07-FEB-92 FRIDAYVelasquez 03-MAR-90 SATURDAYQuick-To-See 07-APR-90 SATURDAYBiri 07-APR-90 SATURDAYNozaki 09-FEB-91 SATURDAYGiljum 18-JAN-92 SATURDAYRopeburn 04-MAR-90 SUNDAYNewman 21-JUL-91 SUNDAYDancs 17-MAR-91 SUNDAYMarkarian 26-MAY-91 SUNDAYCatchpole 09-FEB-92 SUNDAY

25 rows selected.

Page 219: OCP - SQL&PL_SQL(Vol1)

������ �� ��� ���� ��%"

���� ��� � ���������

10. Write a query that produces the following for each employee:

<employee name> earns <salary> monthly but wants<3 times salary>.

For example: ALLEN earns $1,100 monthly but wants $3,300.

Dream Salaries---------------------------------------------------VELASQUEZ earns $2,500 monthly but wants $7,500.NGAO earns $1,450 monthly but wants $4,350.NAGAYAMA earns $1,400 monthly but wants $4,200.QUICK-TO-SEE earns $1,450 monthly but wants $4,350.ROPEBURN earns $1,550 monthly but wants $4,650.URGUHART earns $1,200 monthly but wants $3,600.MENCHU earns $1,250 monthly but wants $3,750.BIRI earns $1,100 monthly but wants $3,300.CATCHPOLE earns $1,300 monthly but wants $3,900.HAVEL earns $1,307 monthly but wants $3,921.MAGEE earns $1,400 monthly but wants $4,200.GILJUM earns $1,490 monthly but wants $4,470.SEDEGHI earns $1,515 monthly but wants $4,545.NGUYEN earns $1,525 monthly but wants $4,575.DUMAS earns $1,450 monthly but wants $4,350.MADURO earns $1,400 monthly but wants $4,200.NOZAKI earns $1,200 monthly but wants $3,600.MARKARIAN earns $850 monthly but wants $2,550.PATEL earns $795 monthly but wants $2,385.SMITH earns $1,000 monthly but wants $3,000.PATEL earns $795 monthly but wants $2,385.NEWMAN earns $750 monthly but wants $2,250.CHANG earns $800 monthly but wants $2,400.DANCS earns $860 monthly but wants $2,580.SCHWARTZ earns $1,100 monthly but wants $3,300.

25 rows selected.

Page 220: OCP - SQL&PL_SQL(Vol1)

�� ����� ��� � ������� ��� ��� ������ ����� ��������� ���������%%

Page 221: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � �������

������

Page 222: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!"

Page 223: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!#

��$���%��

This lesson will cover how to obtain data from more than one table, using themany different methods available.

At the end of this lesson, you should be able to

� Write SELECT statements to access data from more than one table using equalityand non-equality joins.

� View data that would not normally meet a join condition by using outer joins.

� Join a table to itself.

Page 224: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!�

Page 225: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!&

�%��%��'

When data from more than one table in the database is required, a join condition isused. Rows in one table may be joined to rows in another table according to commonvalues existing in corresponding columns, that is to say primary and foreign keycolumns.

There are two main types of join conditions:

� Equijoins

� Non-equijoins

Additional join methods include the following:

� Outer joins

� Self joins

� Set operators

For more information about set operators, attend Advanced SQL and SQL*Plus course.

Page 226: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!(

Page 227: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!)

*+� �� � ,������� �� ���-

When a join condition is invalid or omitted completely, the result is a CartesianProduct, in which all combinations of rows will be displayed. All rows in the firsttable are joined to all rows in the second table.

.�� *+� �+ ��� / � ,���-

A Cartesian product tends to generate a large number of rows, and its result is rarelyuseful. You should always include a valid join condition in a WHERE clause, unlessyou have a specific need to combine all rows from all tables.

SQL> SELECT name, last_name2 FROM s_dept, s_emp;

...

300 rows selected.

Page 228: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!0

Page 229: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!1

������ 2 �� �����

To display data from two or more related tables, write a simple join condition in theWHERE clause.

����3

SELECT table.column, table.column...FROM table1, table2WHERE table1.column1 = table2.column2;

where: table.column denotes the table and column from which data isretrieved.

table1.column1 = is the condition that joins (or relates)table2.column2 the tables together.

4���������

� When writing a SELECT statement that joins tables, precede the column namewith the table name for clarity and to enhance database access.

� If the same column name appears in more than one table, then the column namemust be prefixed with the table name.

� To join tables together, you need a minimum of the number of join conditionssummarized as the number of tables minus one. Therefore, to join four tables, aminimum of three joins would be required. This rule may not apply if your tablehas a concatenated primary key, in which case more than one column is requiredto uniquely identify each row.

For more information, seeOracle7 Server SQL Language Reference Manual, “SELECT.”

Page 230: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!56

���%��

ÉÉÉÉ

Page 231: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!55

������ 2 �� ����� ���������

78��$ ��

In order to determine the name of an employee’s department, you compare the valuein the DEPT_ID column in the S_EMP table with the ID values in the S_DEPT table.The relationship between the S_EMP and S_DEPT tables is an equijoin, that isvalues in the DEPT_ID column on both tables must be equal. Frequently, thesecolumns are primary and foreign key complements.

73�����

Join together the employee and department tables to display the employee name,department number, and department name.

SQL> SELECT s_emp.last_name, s_emp.dept_id,2 s_dept.name3 FROM s_emp, s_dept4 WHERE s_emp.dept_id = s_dept.id;

LAST_NAME DEPT_ID NAME------------ ------- --------------------Velasquez 50 AdministrationNgao 41 OperationsNagayama 31 SalesQuick-To-See 10 FinanceRopeburn 50 AdministrationUrguhart 41 OperationsMenchu 42 OperationsBiri 43 OperationsCatchpole 44 OperationsHavel 45 OperationsMagee 31 SalesGiljum 32 SalesSedeghi 33 Sales...

25 rows selected.

Every employee now has their respective department name displayed. The rows ofthe S_EMP table are combined with the rows of the S_DEPT table, and rows are onlyreturned if the values of S_EMP.DEPT_ID and S_DEPT.ID are equal.

Page 232: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!5"

Page 233: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!5#

������ 2 �� ����� ���������

��������� .���� �� , ���� 9����

You need to qualify the names of the columns in the WHERE clause with the tablename to avoid ambiguity. Without the table prefixes, the ID column could be fromeither the S_DEPT or the S_EMP table. It is necessary to add the table prefix toexecute your query.

If there are no names that are the same between the two tables, then there is no needto qualify the columns. However, you will gain improved performance by using thetable prefix.

73�����

Display the department number, region number, and region name for all departments.

SQL> SELECT s_dept.id ”Department ID”,2 s_region.id ”Region ID”,3 s_region.name ”Region Name”4 FROM s_dept, s_region5 WHERE s_dept.region_id = s_region.id;

Department ID Region ID Region Name------------- ---------- --------------------------- 10 3 Africa / Middle East 31 1 North America 32 2 South America 33 3 Africa / Middle East 34 4 Asia 35 5 Europe 41 1 North America 42 2 South America 43 3 Africa / Middle East 44 4 Asia 45 5 Europe 50 1 North America

12 rows selected.

The requirement to qualify ambiguous column names is also applicable to columnsthat may be ambiguous in a SELECT or ORDER BY clause.

Page 234: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!5�

���%��

ÉÉ ÉÉ

Page 235: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!5&

������ 2 �� ����� ���������

.���� ��� �����+ , ���� ��

In addition to the join, you may have additional criteria for your WHERE clause.Since the join is required to obtain the matches, you need to add your additionalconditions by using the AND operator. Table aliases help to keep SQL code smaller,therefore using less memory.

73�����

Display employee Menchu’s last name, department number, and department name.

SQL> SELECT s_emp.last_name, s_emp.dept_id,2 s_dept.name3 FROM s_emp, s_dept 4 WHERE s_emp.dept_id = s_dept.id5 AND INITCAP(s_emp.last_name) = ’Menchu’;

LAST_NAME DEPT_ID NAME------------ ------- --------------------Menchu 42 Operations

Display the last name, region name, and commission percent of all employees whoearn a commission.

SQL> SELECT s_emp.last_name, s_region.name,2 s_emp.commission_pct3 FROM s_emp, s_dept, s_region4 WHERE s_emp.dept_id = s_dept.id5 AND s_dept.region_id = s_region.id6 AND s_emp.commission_pct > 0;

LAST_NAME NAME COMMISSION_PCT------------ -------------------- --------------Magee North America 10Giljum South America 12.5Sedeghi Africa / Middle East 10Nguyen Asia 15Dumas Europe 17.5

Page 236: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!5(

Page 237: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!5)

���� ����� .������

Qualifying column names with table names can be very time consuming, particularlyif table names are lengthy. Use table aliases instead. Like column aliases, tablealiases are a method of giving the table another name for the purpose of the SELECTstatement. Once you use the table alias, you must continue to qualify every columnreference with the table alias.

73�����

Display the customer name, region number, and region name for all customers.Provide column aliases, and use a table alias to shorten the table references.

SQL> SELECT c.name ”Customer Name”,2 c.region_id ”Region ID”,3 r.name ”Region Name”4 FROM s_customer c, s_region r5 WHERE c.region_id = r.id;

4���������

� Table aliases can be up to 30 characters in length, but the shorter they are thebetter.

� If a table alias is used for a particular table name in the FROM clause, then thattable alias must be substituted for the table name throughout the SELECTstatement.

� Table aliases should be meaningful.

� The table alias is only valid for the current SELECT statement.

Page 238: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!50

Page 239: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!51

9 �!78��$ ��

The relationship between the EMP and SALGRADE tables is a non-equijoin, in thatno column in EMP corresponds directly to a column in SALGRADE. Therelationship is obtained using an operator other than equal (=).

73�����

Create a non-equijoin to evaluate an employee’s salary grade. The salary must bebetween any pair of the low and high salary ranges.

SQL> SELECT e.ename, e.job, e.sal, s.grade2 FROM emp e, salgrade s3 WHERE e.sal BETWEEN s.losal AND s.hisal;

ENAME JOB SAL GRADE ---------- --------- ---------- ---------- SMITH CLERK 800.00 1 ADAMS CLERK 1,100.00 1 JAMES CLERK 950.00 1 WARD SALESMAN 1,250.00 2 MARTIN SALESMAN 1,250.00 2 MILLER CLERK 1,300.00 2 ALLEN SALESMAN 1,600.00 3 TURNER SALESMAN 1,500.00 3 JONES MANAGER 2,975.00 4 BLAKE MANAGER 2,850.00 4 CLARK MANAGER 2,450.00 4 SCOTT ANALYST 3,000.00 4 FORD ANALYST 3,000.00 4 KING PRESIDENT 5,000.00 5

14 rows selected.

Other operators such as <= and >= could be used, however BETWEEN is thesimplest. Remember to specify the low value first and the high value last when usingBETWEEN. Table aliases have been specified for performance reasons, not becauseof possible ambiguity.

Page 240: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!"6

Page 241: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!"5

:������ :�� ��� '�+ 9 ����� ���+

If a row does not satisfy a join condition, then the row will not appear in the queryresult. For example, in the equijoin condition of S_EMP and S_CUSTOMER, SweetRock Sports does not appear because there is no sales representative for thatcustomer.

���� 2 ��

The missing row(s) can be returned if an outer join operator is used in the joincondition. The operator is a plus sign enclosed in parentheses (+), and is placed onthe “side” of the join that is deficient in information. The operator has the effect ofcreating one or more NULL rows, to which one or more rows from the non-deficienttable can be joined.

����3

SELECT table.column, table.columnFROM table1, table2WHERE table1.column = table2.column(+);

SELECT table.column, table.columnFROM table1, table2WHERE table1.column(+) = table2.column;

where: table1.column = is the condition that joins (or relates) the tablestable2.column together.

(+) is the outer join symbol; it can be placed oneither side of the WHERE clause condition, butnot on both sides. Place the outer join symbolfollowing the name of the table without thematching rows.

Page 242: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!""

���%��

ÉÉ É

Page 243: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!"#

:������ :�� ��� '�+ 9 ����� ���+ ���������

73�����

Display the sales representative name and employee number and the customer namefor all customers. Include the customer name even if the customer has not beenassigned a sales representative.

SQL> SELECT e.last_name, e.id, c.name2 FROM s_emp e, s_customer c3 WHERE e.id (+) = c.sales_rep_id4 ORDER BY e.id;

LAST_NAME ID NAME–––––––– ––– ––––––––––––––––––––––––––––––––––––Magee 11 WomansportMagee 11 Beisbol Si!Magee 11 Ojibway RetailMagee 11 Big John’s Sports EmporiumGiljum 12 UnisportsGiljum 12 Futbol SonoraSedeghi 13 Hamada SportNguyen 14 Simms AtheleticsNguyen 14 Delhi SportsDumas 15 Kam’s Sporting GoodsDumas 15 SportiqueDumas 15 Muench SportsDumas 15 Sporta RussiaDumas 15 Kuhn’s Sports

Sweet Rock Sports

15 rows selected.

���� 2 �� :������ ��

� The outer join operator can only appear on one side of the expression—the sidethat has information missing. It returns those rows from one table which have nodirect match in the other table.

� A condition involving an outer join may not use the IN operator or be linked toanother condition by the OR operator.

Page 244: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!"�

���%��

ÉÉ É

Page 245: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!"&

2 ���� � ����� �����

You can join a table to itself by using table aliases to simulate as if the table were twoseparate tables. This allows rows in a table to be joined to rows in the same table.

���� 2 ��

In order to simulate two tables in the FROM clause, the example contains an alias forthe same table, S_EMP. This is an example of good naming conventions.

In this example, the WHERE clause contains the join that means “where a worker’smanager number matches the employee number for the manager.”

73�����

Display the names of employees and their respective managers.

SQL> SELECT worker.last_name||’ works for ’||2 manager.last_name3 FROM s_emp worker, s_emp manager4 WHERE worker.manager_id = manager.id;

Ngao works for VelasquezNagayama works for VelasquezQuick-To-See works for VelasquezRopeburn works for VelasquezUrguhart works for NgaoMenchu works for NgaoBiri works for NgaoCatchpole works for NgaoHavel works for NgaoMagee works for NagayamaGiljum works for NagayamaSedeghi works for NagayamaNguyen works for NagayamaDumas works for Nagayama...24 rows selected.

Page 246: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!"(

Page 247: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!")

�������

There are multiple ways to join tables. The common thread, though, is that you wantto link them through a condition in the WHERE clause. The method you choose willbe based on the required result and the data structures you are using.

����3

SELECT table.column, table.column...FROM table1, table2WHERE table1.column1 = table2.column2;

where: table.column denotes a table and column from which data isretrieved.

table1.column1 = is the condition that joins (or relates)table2.column2 the tables together.

����� � 2 ���

� Equijoin

� Non-equijoin

� Outer join

� Self join

,������� �� ����

Omission of the WHERE clause will result in a Cartesian product, in which allcombinations of rows will be displayed.

����� .������

� Table aliases speed up database access. You tell the Oracle Server exactly whereto go to find columns.

� Table aliases can help to keep SQL code smaller, therefore conserving memory.

Page 248: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!"0

Page 249: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!"1

������� �%��%��'

This practice is intended to give you practical experience extracting data from morethan one table. You will be required to join and restrict rows in the WHERE clause.

������� , ����

� Joining tables using an equijoin

� Performing outer and self joins

� Adding additional conditions

Page 250: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!#6

Page 251: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!#5

������� �

Use the S_EMP, S_DEPT, S_CUSTOMER, S_REGION, S_ORD, S_ITEM, andS_PRODUCT tables to complete the following exercises.

1. Write a report containing each employee’s last name, department number, andname of their department.

LAST_NAME DEPT_ID NAME------------ ------- --------------------Velasquez 50 AdministrationNgao 41 OperationsNagayama 31 SalesQuick-To-See 10 FinanceRopeburn 50 AdministrationUrguhart 41 OperationsMenchu 42 OperationsBiri 43 OperationsCatchpole 44 OperationsHavel 45 OperationsMagee 31 SalesGiljum 32 SalesSedeghi 33 SalesNguyen 34 SalesDumas 35 SalesMaduro 41 OperationsSmith 41 OperationsNozaki 42 OperationsPatel 42 OperationsNewman 43 OperationsMarkarian 43 OperationsChang 44 OperationsPatel 34 SalesDancs 45 OperationsSchwartz 45 Operations

25 rows selected.

Page 252: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!#"

������� � ���������

2. Write a query to display the last name, department name, and region name of allemployees who earn a commission.

LAST_NAME NAME NAME------------ -------------- --------------------Magee Sales North AmericaGiljum Sales South AmericaSedeghi Sales Africa / Middle EastNguyen Sales AsiaDumas Sales Europe

3. Display the employee name and department name for Smith.

LAST_NAME NAME------------ ----------------------Smith Operations

4. Display the product name, product number, and quantity ordered of all items inorder number 101. Label the quantity column ORDERED.

NAME ID ORDERED--------------------------------- ----- -------Grand Prix Bicycle Tires 30421 15Pro Curling Bar 40422 30Prostar 10 Pound Weight 41010 20Prostar 100 Pound Weight 41100 35Major League Baseball 50169 40Griffey Glove 50417 27Cabrera Bat 50530 50

7 rows selected.

Page 253: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!##

������� � ���������

5. Display the customer number and the last name of their sales representative.Order the list by last name.

ID LAST_NAME----- --------------- 205 Dumas 206 Dumas 208 Dumas 211 Dumas 215 Dumas 201 Giljum 204 Magee 214 Magee 209 Magee 213 Magee 202 Nguyen 203 Nguyen 212 Sedeghi

13 rows selected.

Page 254: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!#�

������� � ���������

If you have time, complete the following exercises.

6. Display the customer number, customer name, and order number of all customersand their orders. Display the customer number and name, even if they have notplaced an order.

Customer ID Customer Name Order ID----------- ------------------------------ ---------- 201 Unisports 97 202 Simms Atheletics 98 203 Delhi Sports 99 204 Womansport 100 204 Womansport 111 205 Kam’s Sporting Goods 101 206 Sportique 102 207 Sweet Rock Sports 208 Muench Sports 103 208 Muench Sports 104 209 Beisbol Si! 105 210 Futbol Sonora 106 210 Futbol Sonora 112 211 Kuhn’s Sports 107 212 Hamada Sport 108 213 Big John’s Sports Emporium 109 214 Ojibway Retail 110 215 Sporta Russia

18 rows selected.

Page 255: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!#&

������� � ���������

7. Display all employees by last name name and employee number along with theirmanager’s last name and manager number.

EMP_NAME EMP_ID MGR_NAME MGR_ID---------–––––– ––––––– ––––––––––––– –––––––Ngao 2 Velasquez 1Nagayama 3 Velasquez 1Quick-To-See 4 Velasquez 1Ropeburn 5 Velasquez 1Urguhart 6 Ngao 2Menchu 7 Ngao 2Biri 8 Ngao 2Catchpole 9 Ngao 2Havel 1O Ngao 2Magee 11 Nagayama 3Giljum 12 Nagayama 3Sedeghi 13 Nagayama 3Nguyen 14 Nagayama 3Dumas 15 Nagayama 3Maduro 16 Urguhart 6Smith 17 Urguhart 6Nozaki 18 Menchu 7Patel 19 Menchu 7Newman 20 Biri 8Markarian 21 Biri 8Chang 22 Catchpole 9Patel 23 Catchpole 9Dancs 24 Havel 10Schwartz 25 Havel 10

24 rows selected.

Page 256: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!#(

������� � ���������

8. Modify the solution to exercise 7 to also display Velasquez, who has no manager.

Employee Name Employee ID Manager Name Manager_ID---------–––––––––––––––––– ––––––––––––– ––––––––––Velasquez 1Ngao 2 Velasquez 1Nagayama 3 Velasquez 1Quick-To-See 4 Velasquez 1Ropeburn 5 Velasquez 1Urguhart 6 Ngao 2Menchu 7 Ngao 2Biri 8 Ngao 2Catchpole 9 Ngao 2Havel 10 Ngao 2Magee 11 Nagayama 3Giljum 12 Nagayama 3Sedeghi 13 Nagayama 3Nguyen 14 Nagayama 3Dumas 15 Nagayama 3Maduro 16 Urguhart 6Nozaki 18 Menchu 7Markarian 21 Biri 8Patel 23 Catchpole 9Smith 17 Urguhart 6Patel 19 Menchu 7Newman 20 Biri 8Chang 22 Catchpole 9Dancs 24 Havel 10Schwartz 25 Havel 10

25 rows selected.

Page 257: OCP - SQL&PL_SQL(Vol1)

��������� ��� �� � ������� ������ �!#)

������� � ���������

9. Display all customers and the products and quantities they ordered for thosecustomers whose order totaled more than 100,000.

Customer PRODUCT_ID QUANTITY---------------------- –––––––––– ––––––––Womansport 10011 500Womansport 10013 400Womansport 10021 500Womansport 30326 600Womansport 41010 250Womansport 30433 450Womansport 10023 400Kuhn’s Sports 20106 50Kuhn’s Sports 20201 130Kuhn’s Sports 30421 55Kuhn’s Sports 30321 75Kuhn’s Sports 20108 22Hamada Sport 20510 9Hamada Sport 41080 50Hamada Sport 41100 42Hamada Sport 32861 57Hamada Sport 20512 18Hamada Sport 32779 60Hamada Sport 30321 85Big John’s Sports Emporium 10011 150Big John’s Sports Emporium 30426 500Big John’s Sports Emporium 50418 43Big John’s Sports Emporium 32861 50Big John’s Sports Emporium 30326 1500Big John’s Sports Emporium 10012 600Big John’s Sports Emporium 10022 300

26 rows selected.

Page 258: OCP - SQL&PL_SQL(Vol1)

��� ���� � ������� ��� ��� ������ ���� �� ������ �������!#0

Page 259: OCP - SQL&PL_SQL(Vol1)

����� �������

Page 260: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������

Page 261: OCP - SQL&PL_SQL(Vol1)

����� ������� ���

�� ��!��

This lesson further addresses functions. You will focus on obtaining summaryinformation, such as averages, for groups of rows. You will discuss how to grouprows in a table into smaller sets, and how to specify search criteria for groups ofrows.

At the end of this lesson, you should be able to

� Identify the available group functions.

� Explain the use of group functions.

� Use the GROUP BY clause to force statistics to be displayed for different groups.

� Use the HAVING clause to include or exclude grouped rows.

Page 262: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������"

Page 263: OCP - SQL&PL_SQL(Vol1)

����� ������� ���

�!��!�#

Unlike single row functions, group functions operate on sets of rows to give oneresult per group. These sets may be the whole table or the table split into groups.Group functions appear in both SELECT lists and HAVING clauses.

����� �������

� AVG

� COUNT

� MAX

� MIN

� STDDEV

� SUM

� VARIANCE

�$��� �% ��� &'( )� *������ � +� �,�,*- ���.��

By default, all the rows in a table are treated as one group. Use the GROUP BYclause in the SELECT statement to divide rows into smaller groups. Additionally, torestrict the result groups returned, use the HAVING clause.

�/��0

SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

where: group_by_expression specifies columns whose values determine thebasis for grouping rows.

group_condition restricts the groups of rows returned to thosegroups for which the specified condition isTRUE.

Page 264: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������1

Page 265: OCP - SQL&PL_SQL(Vol1)

����� ������� ��2

����� �������

Each of the functions accepts an argument. The following table identifies the optionsyou can use in the syntax.

Function Description

AVG(DISTINCT|ALL|n) Average value of n, ignoring null values.

COUNT(DISTINCT|ALL|expr|*) Number of rows, where expr evaluates tosomething other than null. Count all selectedrows using *, including duplicates and rowswith nulls.

MAX(DISTINCT|ALL|expr) Maximum value of expr.

MIN(DISTINCT|ALL|expr) Minimum value of expr.

STDDEV(DISTINCT|ALL|n) Standard deviation of n, ignoring null values.

SUM(DISTINCT|ALL|n) Sum values of n, ignoring null values.

VARIANCE(DISTINCT|ALL|n) Variance of n, ignoring null values.

��������

� DISTINCT makes the function consider only non-duplicate values; ALL makes itconsider every value including duplicates. The default is ALL and therefore doesnot need to be specified.

� The datatypes for the arguments may be CHAR, VARCHAR2, NUMBER, orDATE where expr is listed.

� All group functions except COUNT(*) ignore null values. To substitute a valuefor null values, use the NVL function.

Page 266: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������3

Page 267: OCP - SQL&PL_SQL(Vol1)

����� ������� ��4

����� ������� ���������

,0�.���

Display the average, highest, lowest, and sum of the monthly salaries for all salesrepresentatives.

SQL> SELECT AVG(salary), MAX(salary), MIN(salary),2 SUM(salary)3 FROM s_emp4 WHERE UPPER(title) LIKE ’SALES%’;

AVG(SALARY) MAX(SALARY) MIN(SALARY) SUM(SALARY)----------- ----------- ----------- -----------

1476 1525 1400 7380

Note: You can use AVG and SUM functions against columns that store numericdata.

,0�.���

Display the employee last name that is the first and the employee last name that is thelast in an alphabetized list of all employees.

SQL> SELECT MIN(last_name), MAX(last_name)2 FROM s_emp;

MIN(LAST_NAME) MAX(LAST_NAME)------------------------- -------------------------Biri Velasquez

Note: You can use MAX and MIN functions for any datatype.

Page 268: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������56

Page 269: OCP - SQL&PL_SQL(Vol1)

����� ������� ��55

����� ������� ���������

*��)- ������

The COUNT function has two formats: COUNT(*) and COUNT(expr). COUNT(*)returns the number of rows in a table, including duplicate rows and rows containingnull values.

,0�.���

Display the number of employees in department 31.

SQL> SELECT COUNT(*)2 FROM s_emp3 WHERE dept_id = 31;

COUNT(*)---------- 2

In contrast, COUNT(expr) returns the number of non-null rows in the columnidentified by expr.

,0�.���

Display the number of employees in department 31 who can earn a commission.

SQL> SELECT COUNT(commission_pct)2 FROM s_emp3 WHERE dept_id = 31;

COUNT(COMMISSION_PCT)--------------------- 1

Page 270: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������5�

Page 271: OCP - SQL&PL_SQL(Vol1)

����� ������� ��5�

-+� �$��� �% *�����

You use the GROUP BY clause to divide the rows in a table into smaller groups. Youcan then use the group functions to return summary information for each group.

�/��0

SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column];

where: group_by_expression specifies columns whose values determine thebasis for grouping rows.

��������

� If you include a group function in a SELECT clause, you cannot select individualresults as well unless the individual column appears in the GROUP BY clause.You will receive an error message if you fail to include the column list.

� Using a WHERE clause, you can pre-exclude rows before dividing them intogroups.

� You must include the columns in the GROUP BY clause.

� You cannot use the positional notation or column alias in the GROUP BY clause.

� By default, rows are sorted by ascending order of the GROUP BY list. You canoverride this by using the ORDER BY clause.

Page 272: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������5"

Page 273: OCP - SQL&PL_SQL(Vol1)

����� ������� ��5�

-+� �$��� �% *����� ���������

,0�.���

Display each possible customer credit rating and the number of customers in eachcredit rating category. Label the column # Cust.

SQL> SELECT credit_rating, COUNT(*) ”# Cust”2 FROM s_customer3 GROUP BY credit_rating;

CREDIT_RA # Cust--------- ----------EXCELLENT 9GOOD 3POOR 3

,0�.���

Display the job titles and total monthly salary for each job title, excluding vicepresidents. Sort the list by the total monthly salary.

SQL> SELECT title, SUM(salary) PAYROLL2 FROM s_emp3 WHERE title NOT LIKE ’VP%’4 GROUP BY title5 ORDER BY SUM(salary);

TITLE PAYROLL --------------------- ----------President 2500Warehouse Manager 6157Sales Representative 7380Stock Clerk 9490

Page 274: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������51

Page 275: OCP - SQL&PL_SQL(Vol1)

����� ������� ��52

-+� �$��� �% *����� ���������

The GROUP BY column does not have to be in the SELECT clause as the followingexamples shows, but the results are not very meaningful. Add the TITLE column sothat the results are more meaningful.

,0�.���

Display the maximum salary for each title group, without displaying the title.

SQL> SELECT MAX(salary)2 FROM s_emp3 GROUP BY title;

MAX(SALARY)----------- 2500 1525 1400...

8 rows selected.

,0�.���

Display the maximum salary for each title group and display the title.

SQL> SELECT title, MAX(salary)2 FROM s_emp3 GROUP BY title;

TITLE MAX(SALARY)--------------------- -----------President 2500Sales Representative 1525Stock Clerk 1400...

8 rows selected.

Page 276: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ��������53

Page 277: OCP - SQL&PL_SQL(Vol1)

����� ������� ��54

������ ������ ���� ����� �������

Whenever you use a mixture of individual items (REGION_ID) and group functions(COUNT) in the same SELECT statement, you must include a GROUP BY clausethat specifies the individual items (in this case, REGION_ID). If the GROUP BYclause is missing, then the error message “not a single-group group function” wouldappear and an asterisk (*) would point to the offending column.

,0�.���

Display each region and the number of departments in that region.

SQL> SELECT region_id, COUNT(name)2 FROM s_dept;

SELECT region_id, COUNT(name) *ERROR at line 1: ORA-00937: not a single-group group function

Correct the above error by adding the GROUP BY clause. Now, REGION_ID is thename of a group.

SQL> SELECT region_id, COUNT(name)2 FROM s_dept3 GROUP BY region_id;

REGION_ID COUNT(NAME)--------- ----------- 1 4 2 2 3 2 4 2 5 2

Any column or expression in the SELECT list that is not an aggregate function mustbe in the GROUP BY clause.

Page 278: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������6

Page 279: OCP - SQL&PL_SQL(Vol1)

����� ������� ���5

������ ������ ���� ����� ������� ���������

The WHERE clause cannot be used to restrict groups.

,0�.���

Display the department number and average salary for those departments that have anaverage salary more than 2000.

SQL> SELECT dept_id, AVG(salary)2 FROM s_emp3 WHERE AVG(salary) > 20004 GROUP BY dept_id;

WHERE AVG(salary) > 2000 *ERROR at line 3: ORA-00934: group function is not allowed here

Instead, use the HAVING clause to limit those rows.

SQL> SELECT dept_id, AVG(salary)2 FROM s_emp3 GROUP BY dept_id4 HAVING AVG(salary) > 2000;

DEPT_ID AVG(SALARY)------- ----------- 50 2025

Page 280: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ����������

Page 281: OCP - SQL&PL_SQL(Vol1)

����� ������� ����

������ 7+� ������

You can return summary results for groups and subgroups by listing more than oneGROUP BY column. In the example, you count the number of people not only withinthe department, but also by the job category. The order in which the columns arelisted in the GROUP BY clause determines the default sort order.

,0�.���

Display the number of employees for each job category within each department.

SQL> SELECT dept_id, title, COUNT(*)2 FROM s_emp3 GROUP BY dept_id, title;

DEPT_ID TITLE COUNT(*)------- --------------------- ----------... 34 Sales Representative 1 34 Stock Clerk 1 35 Sales Representative 1 41 Stock Clerk 2 41 VP, Operations 1...

,0�.���

Display the number of employees for each department within each job category.

SQL> SELECT title, dept_id, COUNT(*)2 FROM s_emp3 GROUP BY title, dept_id;

TITLE DEPT_ID COUNT(*)--------------------- ------- ----------...Sales Representative 34 1Sales Representative 35 1Stock Clerk 34 1...

Page 282: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������"

Page 283: OCP - SQL&PL_SQL(Vol1)

����� ������� ����

-+� &'( )� *�����

You use the HAVING clause to specify which groups are to be displayed. Therefore,you further restrict the groups on the basis of aggregate information.

�/��0

SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

where: group_condition restricts the groups of rows returned to thosegroups for which the specified condition isTRUE.

The Oracle7 Server performs the following steps when you use the HAVING clause:

� Rows are grouped.

� The group function is applied.

� The groups that match the criteria in the HAVING clause are displayed.

The HAVING clause may precede the GROUP BY clause, but it is recommended thatyou place the GROUP BY clause first because it is more logical. Groups are formedand group functions are calculated before the HAVING clause is applied to the groupsin the SELECT list.

Page 284: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������1

Page 285: OCP - SQL&PL_SQL(Vol1)

����� ������� ���2

-+� &'( )� *����� ���������

,0�.���

Display the job titles and total monthly salary for each job title with a total payrollexceeding 5000. Do not include vice presidents, and sort the list by the total monthlysalary.

SQL> SELECT title, SUM(salary) PAYROLL2 FROM s_emp3 WHERE title NOT LIKE ’VP%’4 GROUP BY title5 HAVING SUM(salary) > 50006 ORDER BY SUM(salary);

TITLE PAYROLL --------------------- ----------Warehouse Manager 6157Sales Representative 7380Stock Clerk 9490

Page 286: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������3

Page 287: OCP - SQL&PL_SQL(Vol1)

����� ������� ���4

-+� &'( )� *����� ���������

In the following example, there is no group function in the SELECT list, but there areHAVING and GROUP BY clauses. Since a group function is referenced in theHAVING clause, the GROUP BY clause is required.

,0�.���

Display all department numbers for departments with a total monthly payroll morethan 4000.

SQL> SELECT dept_id2 FROM s_emp3 GROUP BY dept_id4 HAVING SUM(salary) > 4000;

DEPT_ID------- 41 50

Page 288: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������6

Page 289: OCP - SQL&PL_SQL(Vol1)

����� ������� ���5

��..��/

There are seven group functions available in SQL:

� AVG

� COUNT

� MAX

� MIN

� STDDEV

� SUM

� VARIANCE

�/��0

SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];

You can create subgroups by using the GROUP BY clause. Groups can be excludedusing the HAVING clause.

Place the HAVING and GROUP BY clauses after the WHERE clause in a statement.Place the ORDER BY clause last.

Oracle7 Server evaluates the clauses in the following order:

1. If the statement contains a WHERE clause, the server establishes the candidaterows.

2. The server identifies the groups specified in the GROUP BY clause.

3. The HAVING clause further restricts result groups that do not meet the groupcriteria in the HAVING clause.

Page 290: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ����������

Page 291: OCP - SQL&PL_SQL(Vol1)

����� ������� ����

������ �!��!�#

At the end of this practice, you should be familiar with using group functions andselecting groups of data.

������ *�����

� Showing different queries that use all group functions, with the exception ofSTDDEV and VARIANCE

� Grouping by rows to achieve more than one result

� Excluding groups by using the HAVING clause

Note: Column aliases used for the queries.

Page 292: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������"

������ �

1. Determine the validity of the following statements. Circle either True or False.

a. Group functions work across many rows to produce one result. True / False

b. Group functions include nulls in calculations.True / False

c. Use the HAVING clause to exclude rows from a group calculation.True / False

d. Use the HAVING clause to exclude groups of rows from the display.True / False

2. Display the highest and lowest order totals in the S_ORD table. Label thecolumns Highest and Lowest, respectively.

Highest Lowest---------- ---------- 1020935 377

3. Write a query to display the minimum and maximum salary for each job typeordered alphabetically.

JOB MAXIMUM MINIMUM------------------------- ---------- ----------President 2500 2500Sales Representative 1525 1400Stock Clerk 1400 750VP, Administration 1550 1550VP, Finance 1450 1450VP, Operations 1450 1450VP, Sales 1400 1400Warehouse Manager 1307 1100

8 rows selected.

4. Determine the number of managers without listing them.

Number of Managers------------------ 8

Page 293: OCP - SQL&PL_SQL(Vol1)

����� ������� ����

������ � ���������

5. Display the number of line items in each order under each order number, labeledNumber of Items.

ORD_ID NUMBER OF ITEMS---------- --------------- 97 2 98 1 99 4 100 7 101 7 102 2 103 2 104 4 105 3 106 6 107 5 108 7 109 7 110 2 111 2 112 1

16 rows selected.

6. Display the manager number and the salary of the lowest paid employee for thatmanager. Exclude any groups where the minimum salary is less than 1000. Sortthe output by salary.

MANAGER_ID LOWEST PAID EMPLOYEE–––––––––– –––––––––––––––––––––

2 11001 14003 1400

2500

Page 294: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������1

������ � ���������

7. What is the difference between the highest and lowest salaries?

DIFFERENCE---------- 1750

If you have time, complete the following exercises.

8. Display the product number and number of times it was ordered, labeled TimesOrdered. Only show those products that have been ordered at least three times.Order the data by the number of products ordered.

PRODUCT_ID TIMES ORDERED---------- --------------

20106 320108 320201 320510 350273 330421 320512 330321 4

8 rows selected.

9. Retrieve the region number, region name, and the number of departments withineach region.

ID NAME # OF DEPT----- --------------------------- ----------------

1 North America 42 South America 23 Africa / Middle East 24 Asia 25 Europe 2

Page 295: OCP - SQL&PL_SQL(Vol1)

����� ������� ���2

������ � ���������

10. Display the order number and total item count for each order of 100 or moreitems. For example, if order number 99 contains quantity 30 of one item, andquantity 75 of another item, then the total item count for that order is 105.

ORD_ID TOTAL ITEM COUNT---------- -----------------

97 105099 165100 3100101 217102 145106 392107 332108 321109 3143

9 rows selected.

11. Display the customer name and the number of orders for each customer.

NAME NUMBER OF ORDERS-------------------------------- -----------------Beisbol Si! 1Big John’s Sports Emporium 1Delhi Sports 1Futbol Sonora 2Hamada Sport 1Kam’s Sporting Goods 1Kuhn’s Sports 1Muench Sports 2Simms Athletics 1Ojibway Retail 1Sportique 1Unisports 2Womansport 2

13 rows selected.

Page 296: OCP - SQL&PL_SQL(Vol1)

�������� � ������� ��� ��� ������ ���� ��������� ���������3

Page 297: OCP - SQL&PL_SQL(Vol1)

����������

Page 298: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ���������

Page 299: OCP - SQL&PL_SQL(Vol1)

���������� ��

����������

This lesson covers more advanced features of the SELECT statement. You canwrite subqueries in the WHERE clause of another SQL statement to obtainvalues based on an unknown conditional value.

At the end of this lesson, you should be able to

� Write nested subqueries to query data based on unknown criteria.

� Use subqueries in data manipulation statements.

� Order data with subqueries.

Page 300: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������

������

ÉÉÉÉ

ÉÉÉÉ

Page 301: OCP - SQL&PL_SQL(Vol1)

���������� �!

�������"

A subquery is a SELECT statement that is embedded in a clause of another SQLstatement.You can build powerful commands out of simple ones by using subqueries.They can be very useful when you need to select rows from a table with a conditionthat depends on the data in the table itself.

You can place the subquery in a number of SQL command clauses:

� WHERE clause

� HAVING clause

� FROM clause of a SELECT or DELETE statement

Page 302: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������

Page 303: OCP - SQL&PL_SQL(Vol1)

���������� �#

����������

Subqueries are very useful for writing SELECT statements that query values based onan unknown conditional value. You can use the subquery to find out the values of theunknown data.

�$���%

SELECT select_listFROM tableWHERE expr operator

(SELECT select_list FROM table);

where: operator includes a comparison operator such as >, =, orIN.

Note: Comparison operators fall into two classes: single row (>, =, >=, <, <>, <=)and multiple row (IN, NOT IN) operators.

The subquery is often referred to as a nested SELECT, sub-SELECT, or innerSELECT statement. The subquery generally executes first, and its output is used tocomplete the query condition for the main or outer query.

&���������

� Enclose a subquery within parentheses.

� Place the subquery after the comparison operator.

� Do not add an ORDER BY clause to a subquery. You can have only one ORDERBY clause for a SELECT statement, and if specified, it must be the last clause inthe main SELECT statement.

Page 304: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������'

Page 305: OCP - SQL&PL_SQL(Vol1)

���������� �(

) " *�� +����� ���������� �� ������,

A SELECT statement can be considered as a query block. This example consists oftwo query blocks: the main query and the inner query.

-%�./��

Retrieve the last name and title of the employees in the same department as Biri.

SQL> SELECT last_name, title2 FROM s_emp3 WHERE dept_id =4 (SELECT dept_id5 FROM s_emp6 WHERE UPPER(last_name)=’BIRI’);

1. The nested SELECT statement or query block is executed first, producing a queryresult: 43.

SQL> SELECT dept_id2 FROM s_emp3 WHERE UPPER(last_name)=’BIRI’;

2. The main query block is then processed and uses the value returned by the nestedsubquery to complete its search condition.

In fact, the main query would finally look like this to the Oracle7 Server:

SQL> SELECT last_name, title2 FROM s_emp3 WHERE dept_id = 43;

Page 306: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������01

Page 307: OCP - SQL&PL_SQL(Vol1)

���������� �00

������ 2 " ����������

A single row subquery returns only one row from the nested SELECT statement. Thistype of subquery uses a single row operator.

-%�./��

Display the last name of employees who have the same title as Smith.

SQL> SELECT last_name, title2 FROM s_emp3 WHERE title =4 (SELECT title5 FROM s_emp6 WHERE last_name = ’Smith’);

LAST_NAME TITLE----------------------- --------------------Maduro Stock ClerkSmith Stock ClerkNozaki Stock ClerkPatel Stock ClerkNewman Stock ClerkMarkarian Stock ClerkChang Stock ClerkPatel Stock ClerkDancs Stock ClerkSchwartz Stock Clerk

10 rows selected.

Note: The subquery that returned the value of Stock Clerk is called a single rowsubquery. When a subquery returns only one row, you should use a single rowcomparison or logical operator such as:

=, >, <, >=, or <=.

Page 308: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������0�

������

ÉÉÉÉ

Page 309: OCP - SQL&PL_SQL(Vol1)

���������� �0�

������ 2 " ���������� ���������

You can display data from a main query by using a group function in a subquery toreturn a single row. The subquery is in parentheses and is placed after the comparisonoperator.

-%�./��

Display the last name, job title, and salary for all employees who make less than theaverage salary.

SQL> SELECT last_name, title, salary2 FROM s_emp3 WHERE salary <4 (SELECT AVG(salary)5 FROM s_emp);

LAST_NAME TITLE SALARY------------------- --------------------- -----------Urguhart Warehouse Manager 1200Menchu Warehouse Manager 1250Biri Warehouse Manager 1100Smith Stock Clerk 940Nozaki Stock Clerk 1200Patel Stock Clerk 795Newman Stock Clerk 750Markarian Stock Clerk 850Chang Stock Clerk 800Patel Stock Clerk 795Dancs Stock Clerk 860Schwartz Stock Clerk 1100

12 rows selected.

Page 310: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������0

Page 311: OCP - SQL&PL_SQL(Vol1)

���������� �0!

-�� �� "��3 ����������

One common error with subqueries is more than one row returned for a single rowsubquery.

-%�./��

The subquery returns more than one row and uses a single row comparison operator.To correct this error, change the = to IN.

SQL> SELECT last_name, first_name, title2 FROM s_emp3 WHERE dept_in =4 (SELECT ID5 FROM s_dept6 WHERE name = ’Finance’7 OR region_id = 2);

ORA-1427: single-row subquery returns more thanone row

Page 312: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������0

Page 313: OCP - SQL&PL_SQL(Vol1)

���������� �0#

4����/�� 2 " ����������

Subqueries that return more than one row are called multiple row subqueries. Be sureto use a multiple row operator, such as IN, instead of a single row operator. The INoperator expects one or more values.

-%�./��

Find all employees who are in the finance department or in region 2.

SQL> SELECT last_name, first_name, title2 FROM s_emp3 WHERE dept_in IN4 (SELECT ID5 FROM s_dept6 WHERE name = ’Finance’7 OR region_id = 2);

LAST_NAME FIRST_NAME TITLE––––––––––––– ––––––––––– –––––––––––––––––––Quick–To–See Mark VP, FinanceMenchu Roberta Warehouse ManagerGiljum Henry Sales RepresentativeNozaki Akira Stock ClerkPatel Vikram Stock Clerk

You use a multiple row comparison operator, such as IN, because a list of values isreturned from the subquery.

Page 314: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ��������0'

Page 315: OCP - SQL&PL_SQL(Vol1)

���������� �0(

)*5+& 6����� "��3 +����� ����������

You can use subqueries not only in the WHERE clause, but also in the HAVINGclause. The Oracle7 Server executes the subquery, and the results are returned intothe main query’s HAVING clause.

-%�./��

Display all the departments that have an average salary bill greater than that ofdepartment 32.

SQL> SELECT dept_id, AVG(salary)2 FROM s_emp3 GROUP BY dept_id4 HAVING AVG(salary) >5 (SELECT AVG(salary)6 FROM s_emp7 WHERE dept_id = 32);

DEPT_ID AVG(SALARY)------- ----------- 33 1515 50 2025

-%�./��

Find the job with the lowest average salary.

SQL> SELECT title, AVG(salary)2 FROM s_emp3 GROUP BY title4 HAVING AVG(salary) =5 (SELECT MIN(AVG(salary))6 FROM s_emp7 GROUP BY title);

TITLE AVG(SALARY)--------------------- -----------Stock Clerk 955

Page 316: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ���������1

Page 317: OCP - SQL&PL_SQL(Vol1)

���������� ��0

��..��$

Subqueries are useful when a query is based on unknown criteria.

�$���%

SELECT select_listFROM tableWHERE expr operator

(SELECT select_list FROM table);

����������

� Can pass one row of data to a main statement that contains a single row operator,such as =, <>, >, >=, <, or <=.

� Can pass multiple rows of data to a main statement that contains a multiple rowoperator, such as IN.

� Are processed first by the Oracle7 Server, and the WHERE or HAVING clauseuses the results.

� Can contain group functions.

Page 318: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ����������

Page 319: OCP - SQL&PL_SQL(Vol1)

���������� ���

�������� �������"

In this practice, you will write complex queries using nested SELECT statements.

�������� 6 ������

� Creating subqueries to query values based on unknown criteria

� Identifying what values exist in one set of data and not in another by usingsubqueries

You may want to consider creating the inner query first for these questions. Makesure that it runs and produces the data you anticipate before coding the outer query.

Page 320: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ���������

Page 321: OCP - SQL&PL_SQL(Vol1)

���������� ��!

��������

1. Answer the following questions

a. Which query runs first with a subquery?

b. How many times does the first query run?

c. You cannot use the equality (=) operator if the inner query returns more thanone value. True / False

i. If the answer is True, why and what operator should be used?

ii. If the answer is False, why?

These exercises use the S_EMP, S_DEPT, S_ORD, S_ITEM, and S_PRODUCTtables.

2. Display the first name, last name, and start date for all employees in the samedepartment as Magee.

3. Display the employee number, first name, last name, and user name for allemployees with salaries above the average salary.

4. Display last name, department number, and title for all employees assigned toregion 1 or region 2.

5. Display the last name and salary for all employees that report to LaDoris Ngao.

If you have time, complete the following exercises.

6. Display the employee number, first name, and last name for all employees with asalary above the average salary and that work with any employee with a last namethat contains a “t.”

7. Display the customer number, customer name, credit rating, and salesrepresentative last name for all customers who are located in the North Americaregion or have Nguyen as their sales representative.

Page 322: OCP - SQL&PL_SQL(Vol1)

��� ����� � � ������� ��� ��� ������ ����� �� ������ ���������

�������� ���������

If you have time, complete the following exercises.

8. Display the name and short description for any product that did not appear on anorder in the month of September, 1992.

9. Display the customer name and credit rating for all customers of salesrepresentative Andre Dumas.

10. Display each sales representative’s last name in region 1 and region 2, theircustomers’ names and each customer’s total sales orders.


Recommended