SQL Tutotial

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 17

Creating Tables

In this lesson we will cover the topics Learning about Oracle data types. Creating our first Oracle table. Where we will place our tables and Storage characteristics of our tables.

Oracle Data Types. Here are a few of the data types that we will encounter with our tables. It is in no way the complete list but there is no point in overloading you just yet. NUMBER DATE CHAR VARCHAR2 LONG RAW A NUMBER column can contain a number, with or without a decimal point and a sign, and can have from 1 to 105 decimal digits of which only 38 digits are significant. A DATE column may contain a date and time between the 1st of January 4712 BC to the 31st of December 4712 AD. The standard date format is DD-MMM-YY as in 01-JAN-99. A CHAR column is a fixed length column and can contain any printable characters. Fixed length means that if the data entered into the CHAR field is less that, then length of the field then the field is padded with spaces. The maximum length of the CHAR column is 200. A VARCHAR2 column is a variable length column with a fixed length. If the length of the data is less that the maximum length of the field, then the field is not padded with spaces. The maximum length of the column is 2000. A LONG column can contain any printable character and can be up to 2 Gigabytes in size. A RAW column can contain data in any form, including binary.

Creating our first Oracle table


Oracle tables are the basic storage component in the Oracle database. This is where we will store our information. The Oracle database tables are a two dimensional object. They have columns and rows. There are three things that we want to store about our customers, they are: CUST_ID CUST_NAME CUST_PHONE The following script will create a table called CUSTOMERS, containing the following columns:

create table customers ( CUST_ID NUMBER(5) NOT NULL, CUST_NAME VARCHAR(20) NOT NULL, CUST_PHONE VARCHAR2(10) NULL ); What does the 'NOT NULL' mean? The NOT NULL in the create table statement is what is called a 'constraint'. The column must contain data or Oracle will not allow the row to be entered or updated.

Where are our tables stored?


If we enter the above table creation script in SQL*Plus then the table will be created in our 'Default tablespace'. Our default tablespace is assigned when our Oracle account was initially created by the Oracle DBA. To find out where this is type the following command at SQL*Plus: select * from user_users; We will see five columns of data, being our username, user_id, default_tablespace, temporary_tablespace and created. The username is self-explanatory, the userid is the Oracle assigned internal id. The default tablespace is where any objects we created without specifying a location will be created, the temporary_tablespace will be discussed in the Oracle DBA course and the created column is the date the Oracle account was created

Storage Characteristics of Tables


All Oracle tables have storage characteristics. At this point the student only needs to be aware of this as we will discuss this later. As you may have guessed, if there are no storage options specified, then there are defaults. These default can be found in the table user_tablespaces. Enter the command: select * from user_tablespaces; and you will see the storage defaults for the default tablespace for your Oracle user. Go ahead and create the table in this exercise and type the scripts. When you are finished, you can exit SQL*Plus by entering 'exit' or 'quit'

The structure of the SELECT statement.


We are now all aware that to get data out of an Oracle table we need to select it. The SQL statement is in fact very English like. We SELECT the columns that we wish to view, FROM the table that contains the columns. Optionally we can add WHERE it matches a Predetermined criteria and sort it in some fashion. It really is that simple! From our CUSTOMERS table example in lesson 2 we will select the customers name and phone number for the sales staff to follow up with.

select cust_name, cust_phone from customers Finding out the structure of a table
What if we don't know what columns are contained in a table. No problem !, we only need to describe the table. Notice the command is English like. The describe command can be shortened to desc, this is because desc is enough to make the command unique to Oracle. This is the same for many Oracle commands, I will point these out as we come cross them. Entering the command desc customers will produce the following output Name ------------------------------CUST_ID CUST_NAME CUST_PHONE Null? -------NOT NULL NOT NULL Type ---NUMBER(5) VARCHAR2(20) VARCHAR2(10)

As you can see a select is really quite simple and if you don't know what columns are contained in a table then all you need to do is (desc)ribe the table. Please type the examples in this lesson to help build your confidence.

Have to start from here Oracle Relational Operators


There are six relational operators in Oracle, they are = <> < <= > >= Equal or != Not Equal Less than Less than or equal to Greater than Greater than or equal to

The WHERE clause is used to specify which rows of data are to be displayed when using a select statement. Using the table that we created in part 3. Name ------------------------------CUST_ID CUST_NAME CUST_PHONE Null? -------NOT NULL NOT NULL Type ---NUMBER(5) VARCHAR2(20) VARCHAR2(10)

We now want to display all the our customers with a cust_id > 1000. What we do is transfer the natural English sentence that we just wrote into the the required select statement.

select cust_id, cust_name, cust_phone from customers where cust_id > 1000; If you say the above select statement above out loud you see how simple it is writing select statements. All select statements are similar no matter which conditional operator you may use. Conditional operators are not only compared to constants, as is the previous example to '100' but also compared to other columns. Use the next statement as an example. select cust_name, balance, credit_limit from accounts where balance > credit_limit; In the fictitious table above we want to display the customers name, balance and credit limit for customers that have a balance greater than their credit limit.

Compound conditions
Oracle SQL*Plus is a very flexible language. We can combine the conditional operators in the above example using the AND operator and the OR operator. The AND operator means that every condition must be true in order for the data to be displayed. select from where and cust_name, balance, credit_limit accounts balance > credit_limit zip = 4000;

This means that both the credit limit must be exceeded and also the customers zip code must be '4000'. The OR operator joins two or more conditions and returns a row if any of the listed conditions is true. select from where or cust_name, balance, credit_limit accounts balance > credit_limit zip = 4000;

This means that either the credit limit must be exceeded or the customer zip code = '4000'. Now to confuse things further AND and OR can be combined in the one statement. select from where or cust_name, balance, credit_limit accounts balance > credit_limit and cust_type = 'INTERNAL' zip = 4000;

Oracle evaluates the statement above by determining the AND statement then adding the rows returned by the OR statement, displaying the results

WARNING: Even more confusing statement following. select from where or cust_name, balance, credit_limit accounts balance > credit_limit and (cust_type = 'INTERNAL' zip = 4000);

Here we have introduced brackets. The purpose of the brackets is to force Oracle to evaluate the statement in a particular fashion. It will determine the cust_type = 'INTERNAL' or zip = '4000' first, then join the results from the balance > credit_limit statement.

The Oracle LIKE Operator


The LIKE operator is used when we want to select rows to display that are similar to another field or constant. For example select first_name, surname from employees where surname like 'S%'; In the above example we will select all the employees where the surname begins with the letter 'S'. The '%' is referred to as a wildcard. What this means that the is that the remaining characters of the surname can consist of any other characters and the row will be returned in the query. There is a second wildcard character used in SQL*Plus, it is the '_' character. This character is used in LIKE conditions where we want to match on one character only. For example select first_name, surname from employees where surname like 'SM_TH'; In the above example we will select all employees where the first two characters of the surname are 'SM' and the last two characters are 'TH' and the length of the surname is five characters. The sql script may select the employees 'SMITH' and 'SMYTH'. Try using the LIKE operator in your queries with the wildcard characters '%' and '_'.

The IN Operator
The IN operator can be used in some instances instead of the OR operator. For example: select first_name, surname, salary from employees where surname in ('SMITH','ANDREWS','GREEN'); In the above example we will select all the employees with the above surnames, the other option would be to use the following statement. where surname = 'SMITH' or surname = 'GREEN' or surname = 'ANDREWS';

The BETWEEN Operator


The BETWEEN operator can be seen as an extension of the IN operator. For example: select cust_id, cust_name, date_opened from customers where date_opened BETWEEN '01-JAN-90' and '31-DEC-90'; In the above example we have selected the cust_id, cust_name and date_opened from the customers table where the date_opened is during the year '1990'. The BETWEEN operator always takes two augments with an AND operator. The BETWEEN operator can also be used with Number columns and also character columns. When the BETWEEN operator is used with character columns the columns are sorted alphabetically. i.e. using the following example select cust_name from customers where cust_name between 'A%' and 'D%'; the customer names will be selected from the customers table where the customers names start with either 'A', 'B','C' or 'D'.

Inner Joins
Inner joins are other wise know as equi joins. There are the most common joins used in SQL*Plus. They are know as equi joins because the WHERE statement generally compares two columns from two tables with the equivalence operator '='. Please Cut n' Paste the following code to create the following two tables in your Oracle schema (user). create table employees (id varchar2(10), emp_name varchar2(50), emp_phone varchar2(10)); create table customers (cust_id varchar2(10), cust_name varchar2(50), emp_id varchar2(10), last_sale date); We will create the tables with our default storage parameters and tablespace. If we describe the tables we should see. SQL> desc employees; Name Null? ------------------------------- -------ID EMP_NAME EMP_PHONE

Type ---VARCHAR2(10) VARCHAR2(50) VARCHAR2(10)

SQL> desc customers; Name Null? ------------------------------- -------CUST_ID CUST_NAME EMP_ID LAST_SALE

Type ---VARCHAR2(10) VARCHAR2(50) VARCHAR2(10) DATE

We will now add some data to the two tables, as we are yet to cover inserting data into our table just cut'n paste the following code into your SQL*Plus session. insert into employees (id, emp_name, emp_phone) values ('1','Smith','123456789'); insert into employees (id, emp_name, emp_phone) values ('2','Brown','777'); insert into customers (cust_id, cust_name, emp_id ,last_sale) values ('1','Smith','1',sysdate); insert into customers (cust_id, cust_name, emp_id ,last_sale) values ('2','Green',null,null); If we select the data in these tables we should see the following. SQL> select * from employees; ID --1 2 EMP_NAME -------------Smith Brown EMP_PHONE ------------------------123456789 777

SQL> select * from customers; CUST_ID ---------1 2 CUST_NAME EMP_ID LAST_SALE --------- ---------- --------Smith 1 29-JUN-99 Green

Here is the task, we need to select all the customers who are also employees, displaying their names and phone numbers. If we enter the statement. select cust_name, emp_phone from employees, customers where id = emp_id; We will get the result.

SQL> select cust_name, emp_phone 2 from employees, customers 3 where id = emp_id; CUST_NAME EMP_PHONE --------- -----------------Smith 123456789

Outer Joins
Outer joins are similar to inner joins, but they give us a bit move flexibility when selecting data from related tables. If you have not already done so in our previous lessons please create the following two tables in your Oracle schema (user). create table employees (id varchar2(10), emp_name varchar2(50), emp_phone varchar2(10)); create table customers (cust_id varchar2(10), cust_name varchar2(50), emp_id varchar2(10), last_sale date); Please create the tables with your default storage parameters and default tablespace. If we describe the tables we should see. SQL> desc employees; Name Null? ------------------------------- -------ID EMP_NAME EMP_PHONE SQL> desc customers; Name Null? ------------------------------- -------CUST_ID CUST_NAME EMP_ID LAST_SALE

Type ---VARCHAR2(10) VARCHAR2(50) VARCHAR2(10)

Type ---VARCHAR2(10) VARCHAR2(50) VARCHAR2(10) DATE

Populating the sample tables


We will now add some data to the two tables. As we are yet to cover inserting data in our lessons just cut'n paste the following code into your sql*plus session. insert into employees (id, emp_name, emp_phone) values ('1','Smith','123456789'); insert into employees

(id, emp_name, emp_phone) values ('2','Brown','777'); insert into customers (cust_id, cust_name, emp_id ,last_sale) values ('1','Smith','1',sysdate); insert into customers (cust_id, cust_name, emp_id ,last_sale) values ('2','Green',null,null); If we select the data in these tables we should see the following. SQL> select * from employees; ID EMP_NAME EMP_PHONE -------- -------------------- --------1 Smith 123456789 2 Brown 777 SQL> select * from customers; CUST_ID ---------1 2 CUST_NAME EMP_ID LAST_SALE --------- ----------- ---------Smith 1 29-JUN-99 Green

Here is our the task. We need to select all the customers, displaying their names and phone numbers. Notice the difference in our task, the customers do not have to be employees. The important piece of information required is the cust_name the emp_phone is secondary. If we enter the statement. select cust_name, emp_phone from employees, customers where id = emp_id; We get the result. SQL> select cust_name, emp_phone 2 from employees, customers 3 where id = emp_id; CUST_NAME EMP_PHONE --------------------------- ---------Smith 123456789 But if we enter the statement: select cust_name, emp_phone from employees, customers where emp_id = id(+); We get the result

SQL> select cust_name, emp_phone 2 from employees, customers 3 where emp_id = id(+); CUST_NAME EMP_PHONE -------------------------- ---------Smith 123456789 Green Both the cust_name(s) were displayed even if they were not an employee.

Using Aliases
I think most people are familiar of the concept of an alias, especially when we think of people with colorful backgrounds i.e. criminals. An alias is another way of referring to the same database column within a sql*plus script. Please create the following tables in your Oracle schema ( user). You may type the script directly into sql*plus or cut'n paste from this page. create table orders (order_id varchar2(10), cust_id varchar2(10), order_total number(10,2)); create table order_items (order_id varchar2(10), item_no varchar2(10), item_price number(10,2), qty number(10)); Please create the tables with your default storage parameters and tablespace. If we describe the tables we should see. desc orders Name Null? ------------------------------- -------ORDER_ID CUST_ID ORDER_TOTAL desc order_items Name Null? ------------------------------- -------ORDER_ID ITEM_NO ITEM_PRICE QTY Type ---VARCHAR2(10) VARCHAR2(10) NUMBER(10,2) NUMBER(10) Type ---VARCHAR2(10) VARCHAR2(10) NUMBER(10,2)

We will now add some data to the two tables. As we are yet to cover inserting data just cut'n paste the following code into you sql*plus session.

insert into orders (order_id, cust_id, order_total) values ('1','1',20); insert into orders (order_id, cust_id, order_total) values ('2','1',10); insert into order_items (order_id, item_no,item_price,qty) values ('1','20',10,2); insert into order_items (order_id, item_no,item_price,qty) values ('2','77',0.5,20); If we select the data in these tables we should see the following. SQL> select * from orders; ORDER_ID ---------1 2 CUST_ID ---------1 1 ORDER_TOTAL ----------20 10

SQL> select * from order_items; ORDER_ID ---------1 2 ITEM_NO ---------20 77 ITEM_PRICE ---------10 .5 QTY --------2 20

If we are given the task of selecting the cust_id, item_no and qty for a report we would be required to perform a join between these two tables. If we enter the statement. select cust_id, item_no, qty from orders, order_items where order_id = order_id; We get the result. SQL> select cust_id, item_no, qty 2 from orders, order_items 3 where order_id = order_id; where order_id = order_id * ERROR at line 3: ORA-00918: column ambiguously defined What this error means is that the order_id exists in both tables and Oracle is confused, so we need to create an alias for the order_id column. Re-enter the command as follows.

select a.cust_id, b.item_no, b.qty from orders a, order_items b where a.order_id = b.order_id; We get the result. SQL> select a.cust_id, b.item_no, b.qty 2 from orders a, order_items b 3 where a.order_id = b.order_id; CUST_ID ---------1 1 ITEM_NO ---------20 77 QTY --------2 20

Synonyms
Where aliases are another way of referring to database columns, synonyms are another way of referring to database tables, they also deal with many other database objects but we won't deal with them now. Remember back in lesson two we looked at what we thought was a table called user_users, it was in fact a synonym that referred to a view in the SYS schema. Buts lets try and keep things simple. We can create our own synonym for the orders table that we just created. Just consider for a moment that we are lazy typists, difficult for most I agree. If we are sick of typing ORDERS and would like to refer to the table as ORD then we create a synonym as follows. Type the following command into your sql*plus session. create synonym ORD for ORDERS; We should see. SQL> create synonym ORD for ORDERS; Synonym created. If you do not have the required privileges. If you will receive the message. SQL> create synonym ORD for ORDERS; create synonym ORD for ORDERS * ERROR at line 1: ORA-01031: insufficient privileges Inform you DBA and ask to be granted the required privileges. If you have installed Oracle on you own PC and are your own DBA then if you are not using the SYSTEM user then grant your schema Type the following command into you sql*plus session grant create synonym to pat; Replace the username pat with your user name. You should see

SQL> grant create synonym to pat; Grant succeeded. I hope your feeling confident about using synonyms and aliases in your sql*plus statements.

Functions
With sql*plus the mathematical functions can be split into two groups, those that affect each row of data and those that aggregate or group the data before performing some calculation. Please create the following tables in your Oracle schema ( user) if you have not done so already from our earlier lessons. You may type the script directly into sql*plus or cut'n paste from this page. create table orders (order_id varchar2(10), cust_id varchar2(10), order_total number(10,2)); create table order_items (order_id varchar2(10), item_no varchar2(10), item_price number(10,2), qty number(10)); We will create the tables with our default storage parameters and tablespace. If we describe the tables we should see. desc orders Name Null? ------------------------------- -------ORDER_ID CUST_ID ORDER_TOTAL desc order_items Name Null? ------------------------------- -------ORDER_ID ITEM_NO ITEM_PRICE QTY Type ---VARCHAR2(10) VARCHAR2(10) NUMBER(10,2) NUMBER(10) Type ---VARCHAR2(10) VARCHAR2(10) NUMBER(10,2)

Populating the sample tables


We will now add some data to the two tables, as we are yet to cover inserting data just cut'n paste the following code into you sql*plus session.

insert into orders (order_id, cust_id, order_total) values ('1','1',20); insert into orders (order_id, cust_id, order_total) values ('2','1',10); insert into order_items (order_id, item_no,item_price,qty) values ('1','20',10,2); insert into order_items (order_id, item_no,item_price,qty) values ('2','77',0.5,20); Note: We will insert these additional rows of data. insert into orders (order_id, cust_id, order_total) values ('ABC000001','SMITH',20); insert into orders (order_id, cust_id, order_total) values ('ABC000002','JOHNSON',10); insert into order_items (order_id, item_no,item_price,qty) values ('ABC000001','HARLEY',10,2); insert into order_items (order_id, item_no,item_price,qty) values ('ABC000002','WIRTHLESS',0.5,30); If we select the data in these tables we should see the following. SQL> select * from orders; ORDER_ID CUST_ID ORDER_TOTAL ---------- ---------- ----------1 1 20 2 1 10 ABC000001 SMITH 20 ABC000002 JOHNSON 10 SQL> select * from order_items; ORDER_ID ---------1 2 ABC000001 ABC000002 ITEM_NO ---------20 77 77 78765453 ITEM_PRICE ---------10 .5 10 .5 QTY --------2 20 2 30

Grouping functions
Lets looks at performing some queries using mathematical functions. The functions we will use are max min avg floor ceil

This is not a complete list of the mathematical functions, these are the functions that you will need to be able to use and understand. Refer to the Oracle documentation for a complete list of the functions. The first three functions max, min and avg are grouping functions. They only return one row of data when any query using them is executed. Lets enter the following statement. select min(qty) from order_items; We should get the following result. SQL> select min(qty) 2 from order_items; MIN(QTY) --------2 Lets enter the next statement. select max(qty) from order_items; We should get the following result. SQL> select max(qty) 2 from order_items; MAX(QTY) --------30 Lets enter the next statement. select avg(qty) from order_items; We should get the following result. SQL> select avg(qty) 2 from order_items; AVG(QTY) --------13.5 As you have seen only one row was returned for each of the queries. We can also combine these grouping functions in the one statement. select min(qty), max(qty), avg(qty) from order_items; We should get the following result. SQL> ed Wrote file afiedt.buf 1* select min(qty), max(qty), avg(qty) from order_items SQL> /

MIN(QTY) MAX(QTY) AVG(QTY) --------- --------- --------2 30 13.5

Single row functions


The last two of the mathematical functions that we will discuss here are ceil and floor. The best way to visualize the way these functions are used is to think in terms of the floor and ceiling in your house or apartment. The floor and ceiling are whole numbers (these are numbers without decimal fractions). If our number is 1.2 and we use the function floor, the next whole number below it would be 1 and if we used the function ceil the next whole number above it would be 2. Lets try the following statement. select floor(item_price) from order_items; We should get the following result. SQL> select floor(item_price) 2 from order_items; FLOOR(ITEM_PRICE) ----------------10 0 10 0 Lets try the next statement. select ceil(item_price) from order_items; We should get the following result. SQL> select ceil(item_price) 2 from order_items; CEIL(ITEM_PRICE) ---------------10 1 10 1 We can combine both functions in the one statement. select floor(item_price), item_price, ceil(item_price) from order_items; We should get the following result.

SQL> select floor(item_price), item_price, ceil(item_price) 2 from order_items; FLOOR(ITEM_PRICE) ----------------10 0 10 0 ITEM_PRICE ---------10 .5 10 .5 CEIL(ITEM_PRICE) ---------------10 1 10 1

http://www.hot-oracle.com/articles.html?articleId=15&page=4

You might also like