SQL Tutorial For Beginners

This SQL tutorial is designed just to serve as antechnical_books from the previous examples. To insert
introduction to the things you can do with SQL (i.e. adddata into the table we would write something like this:
data, remove data, modify data and query your data).INSERT INTO technical_books(book_id, title, format,
It is not designed to be a complete guide to theprice, author)
language and its syntax as that would take a wholeVALUES (1,'Learn SQL From Scratch in 40 Minutes
book! The first thing we need to do in this sql tutorial isFlat', 'Ebook',free,'asktheoracle.net');
to define SQL. SQL (pronounced either seequel orFurthermore we would need one statement like that
esscuell) is the language used to communicate with thefor each book the details of which we wished to add
database and to retrieve/update/delete data stored into the database.
the database as well as maintaining the dataThere are a couple of general points that need to be
structures (tables, indexes, constraints etc). The namementioned before we continue. First, in the insert
SQL is an acronym for Structured Query Language. Itstatement, if we don't specify the column names,
is a non-procedural language designed to allowOracle assumes that all columns are being inserted
end-users to be able to retrieve or modify their dataand will generate an error if a value is not supplied for
(and data structures) in a database without having toevery column in the table. For example if we defined a
worry about how this is achieved. In other words ittable course with the columns course_id, name, tutor,
concentrates on what is being done rather than howand price then the statement:
to it is done. As already hinted at, there are two typesINSERT INTO course VALUES (1,'SQL Tutorial');would
of SQL statements.fail as we only supplied 2 values instead of 4. If we
- DML (data manipulation language) for querying andonly want to insert 2 columns then we have to specify
updating datawhich columns we are providing values for.
- DDL (data definition language) which is used for theBy specifying the names of the columns we can also
maintenance of the data structures.list them in any order we choose, otherwise they have
This introductory SQL tutorial will just cover datato be inserted in the same order as they are in the
manipulation, as this is what SQL is used for most oftable. For example, using the table course as defined
the time.The most common SQL statements areearlier, we can insert one rows with the following
database queries. The simplest form of the syntax forstatement:
queries isINSERT INTO course VALUES (1,'SQL
SELECT columns FROM my_table;Tutorial','ebook',0,'asktheoracle.net');
Where columns represents the list of data items in theThis supplies a value for every column and in the order
table that you are interested in with each columnin which they exist in the table. This statement:
separated from the next by a comma. If all columnshowever:
are required this can be abbreviated with "*".INSERT INTO course(title,format) VALUES ('ebook','sql
Therefore a very simple example would be:- SELECTtutorial');supplies values for just 2 of the columns and in
* FROM customers;a different order to the order in the table. This
This query would retrieve every attribute of everystatement also shows that as long as the data type is
customer whose details are held in the customerscorrect, Oracle has no way of validating whether our
table in our mythical database. The rows selectedcommand makes sense (foreign-key and other types
from the table can be restricted with an optionalof constraints can be used for this but discussion of of
where clause which has the syntax WHEREthose is outside the scope of this introductory tutorial).
conditions.In this case we have specified the title as "ebook" and
The conditions are a comma separated list ofthe format as "sql tutorial" which is unlikely to be what
conditions that a record must meet in order to bewe want.
returned to the user as part of the results. EachWe also need to be aware that if the "where" clause
condition can be defined as value_or_column operatoris not added to the update and delete statements then
value_or_column where operator is one of =,,or andthese statements will affect every row in the table.
value or column is either a value (e.g.. 1 or "1") or theFor example if we run the following statement in our hr
name of a column in the table.database
Therefore the simplest query would be of the formUPDATE employees SET salary = salary*1.1;we'll give
SELECT customer_name FROM customers;every employee a 10% pay rise. That might be popular
Where customers is the name of the table andwith the rest of the organisation but the finance
customer_name is a column in the table. This woulddirector is unlikely to be impressed!
select the customer_name column from every row inThis statement:
the table called customers.DELETE FROM employees;would remove the details
If we only wanted some of the names we couldof every employee from the database which is unlikely
restrict the names selected with a where clause, forto go down well with the HR manager, so we would
example:nearly always specify the conditions for the update or
SELECT customer_name FROM customers WHEREdelete by using the "where" clause. If no rows meet
customer_name > 'Jones';would only retrieve thethe conditions in the "where" clause, then obviously no
department names that would be after Joneschanges are made by the update or delete
alphabetically (e.g. Smith, Weston, Swarbrick, Zachary,statements.
King, Loundes, Munden etc.).Multi-Table Queries
Simple Queries To Retrieve Data From The DatabaseWe still have plenty of ground to cover so let's look at
Having looked at the basic syntax and a couple ofthe alternative syntax of the insert statement which
simple examples so far in this sql tutorial, let's move onuses what's known as a sub-query.
to build up some more complicated and moreINSERT INTO my_table1 (col1,col2,...col) SELECT
interesting queries.col1,col2,...colZ FROM my_table2 WHERE conditions;
We've already seen that the simplest query is of theIn the above example we could again leave out the
form: SELECT * FROM the_table; where the_table isnames of the columns that we are providing values
any table in our database (actually the_table could befor but they do need to be specified in the sub-query
a view or even a sub query but to keep this tutorialor we need to use "*" to indicate all columns. This
simple let's pretend it can only be a table). This queryalternative syntax has the advantage that it can be
would return all the columns in all rows from whateverused to insert multiple rows in one statement. The
table we specify.number of rows that would be inserted is limited only
For example, let us suppose we're a bookseller and inby the number of rows that meet the conditions
our database we have a table called technical_booksspecified in the where clause of the sub query. This
which has the following columns: book_id, title, format,format is often used to create an empty table that
price, authorhas the columns we want by specifying a condition
Let us further suppose that we have the details ofthat is never true such as "1=2". That way the table is
over 10,000 technical books held in our table, so runningcreated but not populated.
the query SELECT * FROM technical_books; wouldLet's look at sub-queries in more detail before looking
return all the details for all 10000 books, but we're onlyat multi-table queries. Sub-queries are exactly what
interested in one book - "Learn SQL From Scratch Inthey say they are - queries embedded in another sql
40 Minutes Flat" !statement. When embedded in another query they
So, how do we restrict our query to just return theallow us to answer multi-part questions. For example
details of that one book? Actually this is very"give me the names of all the employees in all
straightforward. All we need to do is to add somedepartments which had a budget over $120,000 this
conditions to our query, like so:-year". Assuming that budget is a column in the
SELECT * FROM technical_books WHERE title =department table we can answer the question by
'Learn SQL From Scratch In 40 Minutes Flat'breaking it down into two parts: part 1 - "which
This query will now return the details for all coursesdepartments had a budget over $120,000 this year?"
entitled 'Learn SQL From Scratch In 40 Minutes Flat'and part 2 - "which employees are in those
(there may be more than one edition or there may bedepartments?" This is translated into sql as follows:
more than one format). To refine the query further weSELECT employee_id, name FROM employees
would add more conditions.WHERE department_id IN
For example, let's assume that the format of the book( SELECT department_id FROM department WHERE
'Learn SQL From Scratch In 40 Minutes Flat' that webudget > 120000 );
are interested in is "Ebook". In which case we can justNote that the query is written top down, but executed
add that condition to our query like so:form the bottom up ie. the sub query is run first. The
SELECT * FROM technical_booksbeauty of sub-queries is that we can keep nesting
WHERE title = 'Learn SQL From Scratch in 40 Minutesthem almost infinitely to answer more and more
Flat'complex questions. In practice, however, it is unlikely
AND format = 'Ebook';that you would ever nest a query more than 3 levels
Assuming that there is only one ebook with this title indeep because of performance issues (discussion of
our database, this query would return just one row.which is outside the scope of this tutorial) and because
This shows how to restrict the number of rowsthe code becomes hard to understand and therefore
returned by our queries to exactly the ones we'rehard to maintain.
interested in by adding as many conditions to theWe've seen that sub-queries can be used to answer
query (the where clause to be precise) as are needed.multi-part questions, however there is another way of
in this case there are two conditions combined bydoing the same thing and that is to convert the
"and". This means both conditions must be met by asub-query into a join. There may be performance
particular record (row) in our table, for that record toimplications for doing this and these would have to be
be in the results.established by trial and error. To convert a sub query
To make a condition optional we just need to replaceinto a join we just promote the table to the "from"
the "and" with an "or". For example:clause in the first part of the query and add the
SELECT * FROM technical_booksconditions in the inner "where" clause to the outer
WHERE title = 'Learn SQL From Scratch in 40 Minutes"where" clause and specify the join condition between
Flat'the tables.
OR format = 'Ebook';would retrieve details of all theLet's re-work the first example as a join. We started
ebooks we have in our table as well as the details ofwith
all books entitled 'Learn SQL From Scratch in 40SELECT employee_id FROM employees WHERE
Minutes Flat'.department_id IN
How To Modify Data In The Database( SELECT department_id FROM department WHERE
Up 'til now we've learnt how to construct queries tobudget > 120000 );we can change this to:-
retrieve information from our database and this isSELECT employee_id FROM employees,
what 90% of our time is spent on with any applicationdepartments
and is fundamental to our understanding of SQLWHERE budget > 120000
therefore. Queries are also often used in update, insertAND employees.department_id =
and delete statements as we'll see later, so they'redepartments.department_id;
doubly important.Note that in the join condition we had to specify the
Now let's learn how to update data in the database.table names because department_id is a column in
There are three commands to do this: update, deleteboth tables. If we didn't do this, Oracle would raise an
and insert. The basic syntax of each of these is aserror because it wouldn't know to which
follows:department_id we were referring. To answer a three
- UPDATE my_table SET col1 = val1, col2 = val2,... colzpart question we could add more tables to the join or
= valz WHERE conditions;add a sub query as in the following example:-
- DELETE FROM my_table WHERE conditions;SELECT employee_id FROM employees,
- INSERT INTO my_table (col1, col2... colZ) VALUESdepartments
(val1,val2... valz);where my_table is the table name, col1,WHERE budget = (SELECT MAX(budget) FROM
col2, colz are the column names and conditionsdepartments)
determine which rows are deleted or updated in theAND employees.department_id =
same way as they determine rows that are retrieveddepartments.department_id;
in a select statement.This shows the flexibility of sql because the order of
The insert statement is more complicated so it is bestthe conditions does not matter in terms of the final
illustrated by an example. We'll re-use our table calledresult.