SQL stands for Structured Query Language. It was first introduced by IBM as early as 1973. Since then, SQL has undergone a number of changes and is now formally recognized as the standard relational database query language.
Oracle, on the other hand, is a database management system (DBMS). Users interact with a relational DBMS primarily through SQL. Without a DBMS, it would be very difficult to efficiently organize, store, secure, maintain, and query data, especially when supporting many concurrent users. Thus, a DBMS is a collection of programs to facilitate all of these functions (and more).
Besides Oracle, there are a number of different relational database management systems in the industry, including IBM's DB2, Microsoft's SQL Server, MySQL and others. Microsoft's Access is another relational database system, but it is for smaller-sized applications, and is meant to be used by one user at a time.
We will be using an Oracle product called SQL*Plus where you can enter an SQL statement at the terminal and immediately see the results of the command.
To begin SQL*Plus, we have to first start up Oracle. To do this, we need to set the path and some environment variables. After SSH-ing in to the department's servers, enter the following at the UNIX prompt:
export ORACLE_HOME=/home/o/oracle >> ~/.bashrc
export ORACLE_SID=ug >> ~/.bashrc
export LD_LIBRARY_PATH=/home/o/oracle/lib32 >> ~/.bashrc
export PATH=${PATH}:/home/o/oracle/bin >> ~/.bashrc
If you do not enter these lines, then you will likely encounter errors in accessing the files and directories that you need (e.g., libclntsh.so.8.0). Type source ~/.bashrc for the changes to take place.
Warning: since you can seriously screw up your environment by doing this, make sure you back up the file before you modify it. If you need a fresh copy of .bashrc to work off of, you can find it here:
#
# .bashrc
#
# Department of Computer Science, UBC
# Version 1.0
# September, 2008
# Trevor McLeod
# Anthony Winstanley
#
#
# Since aliases cannot be exported to subshells, this file is sourced to
# make
# the aliases below available to a subshell. Recall that bashrc is
# sourced
# whenever an interactive, non-login shell is opened.
#
# ~/.bash_profile contains the rest of your bash configuration.
#
# Set up aliases for listing information about processes.
alias psa='ps auxw'
if [ -n $CS_SYS5 ]; then
alias psa='ps -eaf'
fi
# Set up aliases to make file operations prompt you before overwriting
# files.
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
# Set up aliases for directory listing shortcuts.
alias ls='ls -F'
if [ -n $CS_SYS5 ]; then
alias ls='ls -aFC'
fi
alias ll='ls -l'
alias l='ls -o'
alias la='ls -la'
# Set up aliases to list paths vertically, element by element, rather than
# horizontally across the screen.
alias path='echo $PATH | tr -s ":" "\n"'
alias manpath='echo $MANPATH | tr -s ":" "\n"'
# Shows how much disk space you are using (and where). Then shows how much
# you are allocated.
alias diskuse='du -k ~/ | sort -n ; echo " " ; quota -v'
# Another shortcut
alias bye='exit'
|
Your Oracle account is not the same as your UNIX account.
To log into the "stu" database with SQL*Plus, SSH into the department's servers and type the following at the prompt: sqlplus ora_<CWL username>@stu. When prompted for a password, type in "a" (without the quotation marks) and then your student number. For example, if you had "platypus" as your CWL username and 12345678 as your student number, your SQL*Plus login credentials would be ora_platypus@stu and a12345678.
In UBC's undergrad environment, only two connections to Oracle are allowed per user per session. Therefore, if you are having problems logging in, check first that you have at most one other connection to Oracle running.
Once Sql*Plus is started, you will see the prompt:
SQL>
which is your cue that you can begin entering SQL statements or SQL*Plus commands.
SQL*Plus accepts pure SQL statements (also called SQL commands, in some of the literature) and special SQL*Plus commands. A SQL*Plus command is a command which only SQL*Plus understands. For example, the SQL*Plus command DESCRIBE <table-name> outputs the schema of a table which was created using SQL statements. SQL*Plus commands are NOT SQL statements. SQL statements are those which have been taught in class, and are understood by any DBMS which uses SQL. SQL*Plus, on the other hand, is a tool which comes with Oracle. Each vendor has its own tools.
The other distinction between SQL*Plus commands and SQL statements is that in SQL*Plus, an SQL statement can span multiple lines, and needs to be followed by a semicolon, whereas an SQL*Plus command does not need to be followed by a semicolon, and can only span multiple lines if each line is ended with the "-" character.
In SQLPlus, commands are case insensitive. Often, you will see us give an example query where keywords like SELECT, FROM, WHERE, etc. are in capitals. You do not have to follow the capitalization when typing these queries into SQLPlus but you may find it helpful to capitalize these words to easily see the various parts of a query.
Below are some important rules for names in SQL statements:
Database object names, such as column and table names, that are not enclosed with double quotation marks:
If database object names are enclosed with double (not single) quotation marks, then database object names:
Oracle interprets database object names that are not enclosed with double quotation marks as having all capital characters. Therefore, branch and BRANCH are the same as "BRANCH", but they are not the same as "branch".
Text and character literals are enclosed with single quotation marks, and they are case sensitive. For example, where branch_name = 'Main' is not the same as where branch_name = 'main'. To specify an apostrophe, use two single quotes e.g. 'Richard''s car'.
Datatypes used in the Oracle database can differ from the datatypes used in your programming language of choice. For a complete discussion of datatypes in Oracle, refer to the Oracle documentation.
DESCRIBE <table_name> outputs the schema of a relation, showing the table name, attribute (also called field or column) names, whether or not the attribute can be left blank (i.e., NOT NULL means the field is required to have a value at all times), and the domain (datatype) for the attribute.
select table_name from user_tables
user_tables is a view in your database's data dictionary that contains a description of all your tables. Oracle stores information on each user database in a data dictionary, which just consists of tables and views.
select 'drop table '||table_name||' cascade constraints;' from user_tables;
This query will generate all the drop table statements you need to drop every single user created table in the database. Once you run this query, you can either save the output to a file or copy and paste the output to run each statement to clear your database. This can be a very dangerous operation so proceed carefully- you cannot recover your tables once you have dropped them.
After running all the delete table statements, the tables will be sent to the recyle bin. In order to truly free up the space, you need to run purge recyclebin after the delete table statements.
SQL*Plus keeps the most recent SQL command in a command buffer. Type / at the prompt.
You should see the results of the last SQL statement which you have typed (the current command in the command buffer). Now, type run at the prompt, and you should see both the SQL command and the results of the query.
Both the / and the run commands re-execute the last SQL statement, with the difference being that run displays the statement before executing it.
Often you may make a mistake when typing in your SQL statement. For example, imagine there was a table called driver in the database and you typed select from driver;.
Oracle will return the error message:
ERROR at line 1:
ORA-00936: missing expression
If we wanted to correct this command, we need SQL*Plus' CHANGE function. Type change /from/* from/ at the prompt.
The format change /something/something else/ replaces the text string something with the text string something else. The effect of the above change, as outputted by Oracle, is:
select * from driver
We can now execute the statement with the run command.
If you have a multi-line SQL statement that needs changing, you need to first type in the line number and press Enter before you can use the change command to correct anything. For example, in the following multi-line query, there is an error in line 5.
select driver.driver_sin, driver_name,
license_no, branch_name, branch_city
from driver, license, branch
where driver.driver_sin = license.driver_sin and
license.branch_id = branches.branch_id and
license_type = 'D';
When we run this command, Oracle should return the following error statement:
ERROR at line 5:
ORA-00904: invalid column name
To correc this, type 5 and press enter. This displays line 5 and makes line 5 current.
We can now apply the correction with the CHANGE command by executing something like change /branches.branch_id/branch.branch_id/.
You can save one or more SQL queries into a file and have SQLPlus run all the queries in that file in one go. To do this, first create a file with the SQL queries you wish to run and save that file with a .sql extension. Then, transfer that file to the undergraduate server. When you log into the undergraduate server, make sure you launch SQLPlus from the directory where your file is located. For example, if I saved my file to a directory called cs304, then I should cd into the cs304 directory before running sqlplus ora_cwl@stu. Once you have logged into SQLPlus, you can run the queries in the file by start <filename>.sql
We can save the most recent SQL statement into a file. Type at the SQL prompt: save somethingelse.sql.
This saves the last statement into a file called somethingelse.sql. To append the statement to an existing file, type save <filename> append. If we wanted to examine the contents of the file, we can use the GET <filename> command. To actually run the file, type @ somethingelse.
To save the output of the current SQL*Plus session in a file, type spool <filename>.
Everything that is displayed on the screen after this command is entered will be saved in the given file. If you do not provide a file extension for the filename, a default extension (on most systems .LST or .LIS) will be added to the filename.
To stop writing to the file, type spool off.
rlwrap sqlplus: rlwrap is a tool that enables you to use the arrow keys in sqlplusquit: exits sqlplus host <host command>: This will allow you to run host operating system commands. For example, typing host ls *.sql executes ls *.sql.edit: Edits the SQL statement in the command buffer using the host operating system's default text editor (for us, it will probably be emacs). You will see the '/' symbol at the end of the file; just leave it there. Note: you cannot have more than one SQL statement in the file. After you save the changes and exit the editor, the new SQL statement will be placed in the command buffer. Use the / or run command to execute it.stty erase ^h: Enter this before getting into SQL*Plus. It is used to enable the backspace/delete key to delete characters that you accidentally typed on the command line.start myQuery or @myQuery: Assuming you have a file called myQuery.sql in the directory you run SQL*Plus from, this command will execute the SQL statements in that file.set pause "Press ENTER to continue ...";: Allows for page breaks in your output (rather than have everything scroll by). Follow this command with set pause on and (later) set pause off.set linesize 200: This will resize your output width to be 200 characters rather than some embarrassingly narrow width for a default.set pagesize 50: This will resize your output page (i.e., how frequently you see the column headings in the output from your SQL query).Here are some other commands that may be useful when examining your account's space usage:
SELECT * FROM user_segments: Shows the specifics of what I'm using on disk — I can see how much space a certain table is usingSELECT SUM(bytes)/1024/1024 Size_MB FROM user_segments: Shows the sum of all segments I'm using in MBSELECT * from USER_TS_QUOTAS: Shows my quotaSELECT * FROM RECYCLEBIN: What's in my recycle bin?PURGE RECYCLEBIN: Clear my recycle binSELECT * from USER_TABLESPACES: How are the tablespaces I have access to configured?