SQL Tutorial
SQL Tutorial
SQL Tutorial
SQL stands for Structured Query Language and is a very powerful and diverse language
used to create and query databases. Its loose syntax makes it easy to learn but mastering
its intricate architecture may take a lifetime.
Advertise on Tizag.com
SQL is the language used to interact with data and databases. Armed with a firm
understanding of its structure and mechanics will allow you to build simple, dynamic
applications for the web or create robust applications for your preferred operating system.
The loose structure and flexibility of this language make it an ideal candidate for the web,
especially since there are more than a handful of database applications available for free
such as MySQL and SQL Server Express.
SQL - Fundamentals
SQL alone can input, modify, and drop data from databases. In this tutorial we use
command line examples to show you just a sample of what SQL is capable of. With the
use of web languages such as HTML and PHP, SQL becomes an even greater tool for
building dynamic web pages.
SQL - Platforms
A SQL platform acts as the stage for building and developing your databases. Several
different platforms exist including:
Advertise on Tizag.com
• IBM's DB2
• MySQL
• PostgreSQL
• Oracle
SQL - Queries
SQL uses commands called queries to execute tasks such as creating a databases (which
we've seen already), updating data inside a table, or selecting data rows that meet specific
criteria. Each query statement begins with a clause such as SELECT, UPDATE,
CREATE, or DELETE and the simplest query is only two words long. It is a query that
uses a built in SQL function called getdate() that will return the current server date.
Execute the following statement to have SQL go and fetch the current SQL server date
and time:
Advertise on Tizag.com
SQL Code:
SELECT getdate();
SQL Results:
2008-08-09 11:56:05.407
As you can see, this statement begins with the SELECT clause and the built in function
getdate() does all the work for you. By executing this query you are essentially telling
your database to "go and fetch" the current date.
This particular query is probably as simple and straight forward as it gets in the SQL
world. Even though you may not know exactly what is happening here or when this may
be useful, you have taken the first step toward understanding the fundamental mechanics
of SQL query statements and the very foundation on which SQL architecture resides.
SQL - Query Structure
Queries are loosely typed into your SQL prompt. Spacing and line breaks are not very
important as excess line breaks and spacing are ignored by the SQL application. We now
know that a query begins with a clause, what comes next depends on the clause.
In order to expand our understanding of queries we will need to create a table and
populate this table with some data which we can then manipulate as we introduce more
Query commands and SQL functions. The next couple of examples should be
overwhelming to newer SQL programmers but we will still take a moment to explain
what's going on and focus on the structure of each query.
SQL - Syntax
SQL follows a general syntax, there are not many quotations or other symbols to throw
into your statements. Generally we follow a Do what To what syntax, meaning first we
decide what we want to do, then we decide what we want to do it to, and finally we end
the whole thing with a semicolon (;).
Advertise on Tizag.com
A statement begins with a clause. Clauses are commands in the SQL world and the
backbone of any script. The first clause of a statement gives a general idea of what type
of action a script is taking. A few basic clauses are SELECT, INSERT, or CREATE. We
will look at each of these clauses a little more in depth on the next few pages but it may
be obvious to you already what each of those clauses does. SQL statements end with a
semicolon as most with most programming languages. A basic statement might look like
this:
SQL Code:
SELECT * FROM table_name;
Above we have a SELECT clause asking for all columns and values (*) from our
database table. As shown above, a good habit is to capitalize your clauses. Later on when
we have larger statements and subqueries it will make life much easier to go back and
debug your code.
Formating your statements in a similar fashion will also aid your debugging efforts. The
common formatting technique is to begin each line with a clause or to break up and list
columns or tables as needed. More on this in a moment.
SQL Code:
SELECT *
FROM table_name;
The advantage of this isn't apparent with this example. Each are fairly easy to read.
However the example below shows an example where this format shines.
SQL Code:
SELECT column_one, column_two
FROM table_name
WHERE (
column_one,
column_two,
column_three,
)
= (SELECT column_one,
column_two
FROM table_two
WHERE table_one.id = 'table_two.id');
As you can see, when subqueries are thrown into the mix things become a little more
complicated. A one line statement will not fit across your screen. Both statements are
neither right nor wrong, each are easier to follow. Parentheses generally depict order of
operations but it is not an exact science. Quotations are not found until the predicate of
the statement.
Numbers:
rate_of_pay
27
26.66
28.40
Boolean Values:
admin
1
1
0
Character Strings:
employee_id
TS_0036
TS_0078
CL_1099
SQL - Commands
SQL commands can be categorized into three distinct groups. Each type of command
plays an essential role while working with your database. One analogy might be to think
of each SQL Command as a possible tool in your tool shed. Certain duties require
specific tools and the more tools you have in your shed, the greater the chances that you
will have the exact tool you need for the appropriate job.
Advertise on Tizag.com
SQL Code:
Count() function
SQL Code:
SELECT * FROM table_one WHERE column_one > 5;
SQL - Operators
Operators are used in expressions or conditional statements. they show equality,
inequality, or a combination of both. Mathematical operators are found in every computer
language and may be familiar to you. SQL operators follow the same rules you may have
learned in a math class or know from previous programming experience.
Advertise on Tizag.com
Operators come in three flavors, mathematical, logical, or range operations. Mathematical
operators add, subtract, multiply, divide, and compare equality of numbers and strings.
There are two logical operators, AND / OR. Range operators include the infamous < and
> symbols used to compare equality. Take note of the following tables for future
reference.
SQL - Expressions
In the programming world an expression is a special statement that returns a value. SQL
is no exception to this standard rule.
Advertise on Tizag.com
SQL Code:
SELECT column_one FROM table_name;
The simplest form of an expression appears as column_one of our table. Select is our
clause telling our database what we want to do, and column_one acts as the defined
expression returning each row of that particular column.
Expressions after the where clause might appear more familiar to programmers.
SQL Code:
SELECT * FROM table_name WHERE column_one = 'some value';
The latter example returns rows of the specified column containing 'some value'. Using
expressions like the one above gives you precise control over what results will be
returned. More information on the where clause is available at SQL Where.
SQL Code:
SELECT * FROM table_name WHERE column_one = 'some value';
The logic behind this query is that each row is being tested for 'some value' to appear in
our column_one. Each time a match is found (testing true), that row is selected and
returned for our viewing pleasure.
SQL Code:
SELECT COUNT(*) FROM table_name;
Our expression above returns a numeric value representing the number of rows that have
been inserted into your table thus far. Please be aware that the AVG(), COUNT(), and
SUM() only return results for integer table columns. Using one of these functions with a
varchar column will result in an error message.
SQL Code:
SELECT * FROM table_name WHERE
column_one LIKE '%string';
Here we have used the percent(%) symbol to signify the start of our string. SQL tests our
expression against column_one and returns all the rows and columns where column_one
contains our string.
This might come across easier if we use a live example. Say we have created a table with
employee information. In this table we have set up a column a last_name column. The
query above will come in handy if we were wanting to pull all the employees with a
last_name that begins with a "T". Now if we plug in our hypothetical situation into our
code, we should have something like the following.
SQL Code:
SELECT * FROM employees WHERE
last_name LIKE '%T';
Keep in mind that SQL is case sensitive, using a lowercase t would not yield results for a
last_name that has been capitalized.
SQL Code:
INSERT INTO table_name(column_one,column_two,)
Values(Current_Date,Current_Timestamp);
This statement inserts a new row into our imaginary table with the current date value for
column one and the current timestamp value for columne_two.
SQL - Create
A database is nothing more than an empty shell, like a vacant warehouse. It offers no real
functionality what so ever, other than holding a name. Tables are the next tier of our tree
offering a wide scope of functionality. If you follow our warehouse example, a SQL table
would be the physical shelving inside our vacant warehouse. Depending on the situation,
your goods may require reorganization, reshelving, or removal. SQL tables can be
manipulated in this same way or in any fashion the situation calls for.
Advertise on Tizag.com
SQL Code:
CREATE DATABASE business;
We will be using this database for the remainder of the tutorial.
Column Types:
Column
Description Syntax
Type
int Accepts integer values only tinyint, int
varchar Accepts any symbol, character, or number varchar(char limit value)
text/blob lots of text including line breaks text, blob
Int, varchar, and text are the 3 most common types of columns. Text and int columns
have 3 flavors tiny, medium, and large. Every SQL program has its unique sizes, but for
this tutorial we will be using medium sized column fields for each exercise. Later on as
you expand the database it will become extremely important not to overdue the size of
your column fields. Using the correct size field will dramatically increase performance
including query speeds.
Now create the table.
SQL Code:
CREATE TABLE employees
(
id INT IDENTITY PRIMARY KEY NOT NULL,
Lastname VARCHAR(50),
Firstname VARCHAR(25),
Title VARCHAR(10) DEFAULT 'crew' NULL
);
Above is our table, the first column is an int column set to automatically count each row,
generally this is a great way to automatically assign a unique id to a record. Our second
line is a varchar meaning it will hold numbers, digits, or symbols, which is perfect for
short names of people. The last column has a specified default value of "crew" so that if
we add a new crew member we can simply place a default value.
We do not always have to specify a default value or state weather each column may have
a NULL value, By default, most table columns will allow null values to be recorded but
certain table columns will not allow a null value to be inserted. We recommend reading
up on each column type available to you from your database manufacturer.
SQL Code:
ALTER TABLE 'employees' DROP PRIMARY KEY,
ADD PRIMARY KEY ('id');
SQL - Indexes
SQL automatically creates some indexes based on column types and attributes. An index
can also be given to a table column to optimize speeds. When a query is executed
searching for a specific column value, SQL will start at the top of the table and search
each and every record until it finds matches. This becomes a performance issue when a
table holds a vast amount of records. By adding an index to columns, SQL will no longer
search the entire table, it will pinpoint your index columns and search those first. The
downside to indexing is that it enlarges the disk space consumed by a table on your web
server. Use indexes when you notice a drop in your query speeds.
SQL Code:
ALTER TABLE 'employees' ADD INDEX ('id');
or
ALTER TABLE `employees` DROP INDEX `Lastname`;
SQL - Insert
SQL tables store data in rows, one row after another. The INSERT command is the
command used to insert new data (a new row) into a table by specifying a list of values to
be inserted. Values are specified in the query statement and must be arranged inside the
code according to the order of the table columns.
Advertise on Tizag.com
To use the INSERT command we must have an understanding of where we would like to
insert data and what types of data we want to insert. Do we plan on inserting numbers?
Strings? Files? Returning to the orders table we created in an earlier lesson. You may
recall a few of the table columns that were created:
• id
• customer
• day_of_order
• product
• quantity
Looking at the column names alone you gain a sense of what type of data is expected by
each column. The "Quantity" column for example, is expecting a number of some sort
(integer) and the "day_of_order" column is looking for a date value. With our new found
understanding of what is to be expected in each table column it doesn't take much to
effort to create an INSERT statement to add new row values to our table.
Verification Query:
use mydatabase;
SELECT *
FROM orders;
SQL Results:
id customer day_of_order product quantity
1 Tizag 2008-08-01 00:00:00.000 Sharpie 4
2 Tizag 2008-08-01 00:00:00.000 Stapler 1
SQL Results:
id customer day_of_order product quantity
1 Tizag 2008-08-01 00:00:00.000 Sharpie 4
2 Tizag 2008-08-01 00:00:00.000 Stapler 1
3 A+Maintenance 2008-08-16 00:00:00.000 Hanging Files 12
Before moving on, let's add some more rows by running the following insert queries. If
you are using SQL Express, you should be able to copy the entire code section below and
execute all the queries at once and track the results.
SELECT *
FROM orders
Final Results:
id customer day_of_order product quantity
1 Tizag 2008-08-01 00:00:00.000 Sharpie 4
2 Tizag 2008-08-01 00:00:00.000 Stapler 1
3 A+Maintenance 2008-08-16 00:00:00.000 Hanging Files 12
4 Gerald Garner 2008-08-15 00:00:00.000 19" LCD Screen 3
5 Tizag 2008-07-25 00:00:00.000 19" LCD Screen 3
6 Tizag 2008-07-25 00:00:00.000 HP Printer 2
SQL - Select
SQL SELECT may be the most commonly used command by any SQL programmer as it
is used to pull data from a database and present the data in a user-friendly table. SELECT
query statements are easily identifiable because each one begins with the "SELECT"
clause.
Advertise on Tizag.com
Select queries require two essential parts, the first part is the "WHAT" which determines
what we want SQL to go and fetch. Earlier we saw a select statement that went and
fetched the current date for us and because we used a SQL built in function to determine
"WHAT" we wanted to select, SQL automatically filled in the second part of our
SELECT query, the "FROM WHERE."
Now we would like SQL to go and fetch table column data for us from the orders table
that we created earlier. How do we translate this request into SQL code so that the
database application does all the work for us? Simple, we just need to tell SQL what we
want to select and from where to select the data.
SELECT *
FROM orders;
SELECT COUNT(*)
FROM orders;
SQL Count Results:
(no column name)
1
Because we enclosed our table column value (*) inside of the COUNT function SQL
interprets that differently than it would the generic query statements we used previously.
Instead of returning column data, we see only a single number representing how many
rows were returned by our SELECT command. More on this later.
SQL - Order By
The order by statement allows for table column assortment. It allows for ascending or
descending lists of your table column values permitting SQL to reorder your table rows
for the purpose of viewing.
Advertise on Tizag.com
SQL Code:
SELECT * FROM employees ORDER BY Lastname;
SQL Table:
ID Lastname Firstname Title
11 Davis Julie manager
10 Harris Joel crew
9 Hicks Freddy crew
2 Hively Jessica crew
1 Johnson David crew
The above example resorts our rows of data alphabetically by lastname. Here is another
example ordering by two different columns First we alphabatize our job titles and again
we order by lastname.
SQL Code:
SELECT * FROM employees ORDER BY Title,Lastname;
SQL Table:
ID Lastname Firstname Title
10 Harris Joel crew
9 Hicks Freddy crew
2 Hively Jessica crew
1 Johnson David crew
11 Davis Julie manager
Hint: It is possible to order by a column you do not wish to display such as an ID field.
Also notice at the bottom of each query display will be the number of rows affected by
your query. This number will also be displayed anytime an insert, select, update, or delete
statement is properly executed by your SQL program
SQL - Distinct Usage
Distinct is used to retrieve rows of your database that have unique values for a given
column. For example say we have a table of employees and in this table of employees we
have several job titles from janitors to CEOs. We would like to know just how many
distinct job titles we have.
Advertise on Tizag.com
SQL Code:
SELECT DISTINCT job_titles FROM employees;
Our statement will return the number of rows with a distinct value for our column
(job_titles).
SQL Code:
SELECT DISTINCT job_titles, salary FROM employees;
SQL has returned all the rows with unique combinations of job titles and salaries. Any
duplicate combinations of job titles and salaries will be ignored. For example if we had
two CEOs in the table making the same salary each year, only one row would be returned
but if we had two CEOs with different salaries, both rows would be returned.
SQL - Where
The where clause sets a conditional statement for your queries. Your server will query the
database searching for rows that meet your specific where condition. A typical query will
have the following syntax.
Advertise on Tizag.com
A conditional statement has 2 parts, the left side is your table column and the right side is
the condition to be met. Example:WHERE table_column(s) = condition.
SQL Code:
SELECT * FROM employees WHERE Title = 'crew' ORDER BY Lastname;
SQL Table:
ID Lastname Firstname Title
10 Harris Joel crew
9 Hicks Freddy crew
2 Hively Jessica crew
1 Johnson David crew
All the known typical operators can be used in the conditional statements, for a complete
list backtrack to SQL Operators
SQL Code:
SELECT employees.Lastname,
employees.Firstname,
employees.Title,
payroll.Hours
FROM employees,payroll
WHERE employees.Lastname = payroll.Lastname
AND payroll.Hours => '36'
ORDER BY employees.Lastname;
As you can see, the where clause is a very powerful tool used to quickly pull rows from
one table or many.
SQL - In
In is a special kind of operator for use in your where clauses. Recall that in a where
expression only one value is allowed to be sent through the query. With the in operator
one can send multiple values in the where clause.
Advertise on Tizag.com
SQL Code:
SELECT * FROM table_name
WHERE some_column IN('value1','value2','value3');
The rows returned will have one of the values listed (value1, value2, or value3) in
brackets as the value for the specified column (column_one).
SQL - In Subqueries
To better understand the power of this function, let's use an example involving a
subquery. Say we have a database with the following tables.
Employees:
user_id last first
0045 Davis Julie
0067 Smith John
0098 Hodgensen Bruce
Logbook:
user_id timestamp
0045 000000002345
0045 000000045666
0098 000000076444
Now above we have an employees table giving us a user_id along with a first and last
name of employees we have working in the office. The second table might be a log type
table that keeps track of who accessed the database and at what time. This a security
check. A standard operating procedure if many people will be accessing the database.
What we want to know is the last name and first name of those that accessed the
database. To do this we may use a subquery like in the example below.
SQL Code:
SELECT first,last FROM employees WHERE user_id IN
(Select user_id FROM logbook);
The subquery highlighted in red selects all the values of user_id in the logbook and
returns those to the previous in statement. The result is a complete listing of the names of
the employees that have accessed the database and have been recorded inside the logbook
table. The good news is that this feat was accomplished without having to know the
user_ids of every employee in the office. This definatly adds some depth to your SQL
knowledge thus far.
SQL - Between
Between is a special operator appearing in a where statement. It allows for the selection
of a range of values between one value and another.
Advertise on Tizag.com
SQL Code:
SELECT * FROM table_name WHERE column_one
BETWEEN value1 AND value2;
Be aware that the values you specify will also return results. For example if we were
looking for values between 5 and 10, all rows would be retrieved where our column value
is 5,6,7,8,9, or 10.
SQL Code:
SELECT * FROM employees WHERE user_id IN
(SELECT user_id FROM logbook WHERE user_id BETWEEN 0040 AND 0049);
SQL will now retrieve exactly what we need. A listing of all the data security employees
(user_id 004X) that have accessed the database thus far.
SQL Code:
ALTER TABLE employees
ADD dob varchar(10);
SQL Table:
id Lastname Firstname Title dob
1 Johnson David crew
Now we will remove the same column from the table.
SQL Code:
ALTER TABLE employees
DROP dob;
SQL Table:
id Lastname Firstname Title
1 Johnson David crew
SQL Code:
ALTER TABLE 'employees' CHANGE 'ID' 'id' TINYINT ( 3 )
NOT NULL AUTO_INCREMENT;
Above we changed 'ID' to 'id' because SQL is case sensative and this will remove a
potential bug issue. After we have selected a new name, we list the new attributes to be
given to the altered column.
SQL - Update
The update clause updates column values of a table. Update requires a conditional
statement to select the row to be updated.
Advertise on Tizag.com
SQL Code:
UPDATE employees
SET Lastname = 'Fletcher', Firstname = 'Ron'
WHERE id = '11';
SQL Table:
ID Lastname Firstname Title
11 Fletcher Ron manager
Here we changed record 11, our manager, to a new manager.
SQL - Updating Multiple Rows
With the use of expressions and operators, update allows for the manipulation of several
rows at once.
SQL Code:
UPDATE employees
SET Title = UPPER(Title);
SQL Table:
ID Lastname Firstname Title
1 Johnson David CREW
2 Hively Jessica CREW
9 Hicks Freddy CREW
10 Harris Joel CREW
11 Davis Julie MANAGER
Using the UPPER expression we changed our Title field to all capital letters. Update also
supports the use of subqueries.
SQL - Delete
Entire rows can be deleted from a table using the delete clause.
Advertise on Tizag.com
SQL Code:
DELETE FROM employees
WHERE id='4';
We could use the above code to delete an employee using their unique employee number
that has been assigned by the auto_increment field.
SQL Code:
DELETE FROM employees
WHERE id <= '999';
The above example would delete every row from our table since we had previously
limited our "id" field when we set up the table. Predicates, expressions, subqueries, and
operators can be used to delete any rows you would like to remove from your table.
SQL - Truncate
We can clear an entire table using a truncate statement. Truncate quickly clears all rows
of a table without deleting the table itself. If you are following along, we don't
recommend that you run this script because you will essentially undo all of your inserts
and have only empty table field to show for it, but it is a handy statement to know and use
when the time is right.
SQL Code:
TRUNCATE TABLE employees;
SQL - Predicates
Predicates follow the where clause. Predicates allow the searching through database
records to recover specific strings and ranges or characters. Rows will be returned if they
match the predicate condition.
Advertise on Tizag.com
SQL Code:
SELECT * FROM employees WHERE Lastname LIKE '%H%';
SQL Table:
ID Lastname Firstname Title
10 Harris Joel crew
9 Hicks Freddy crew
2 Hively Jessica crew
Our example will retrieve any and all rows with a capital letter H in the lastname field.
Case sensitivity is important in this situation.
On a contrary note, use the Not Like predicate to find all rows that do not match the
string.
SQL Code:
SELECT * FROM employees WHERE Lastname NOT LIKE '%H%';
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
11 Davis Julie manager
SQL Code:
Oracle/SQL Server
MySQL
SQL Code:
SELECT * FROM employees WHERE id BETWEEN 1 AND 4;
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
2 Hively Jessica crew
Between is essentially replacing your range operators. Always start your ranges with the
lowest number first.
SQL - Limit
The limit predicate allows you to limit the number of rows selected.
SQL Code:
SELECT * FROM employees LIMIT 2;
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
2 Hively Jessica crew
SQL Code:
SELECT employees.Lastname, employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
INNER JOIN invoices
ON employees.id = invoices.EmployeeID
SQL Table:
Lastname Firstname Sale Price
Johnson David HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
Davis Julie CD SLD 3.99
Davis Julie CD SLD 3.99
We haven't changed or updated any information in either of our tables but we were able
to fashion together a new table using a conditional that matches one table column to
another.
SQL Code:
SELECT employees.Lastname, employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
LEFT JOIN invoices
ON employees.id = invoices.EmployeeID
SQL Table:
Lastname Firstname Sale Price
Johnson David HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
Hicks Freddy
Harris Joel
Davis Julie CD SLD 3.99
Davis Julie CD SLD 3.99
This would be a great way to track sales per person per day if the invoice table had a date
field as well.
SQL Code:
SELECT employees.Lastname, employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
RIGHT JOIN invoices
ON employees.id = invoices.EmployeeID
SQL Table:
Lastname Firstname Sale Price
Davis Julie CD SLD 3.99
Davis Julie CD SLD 3.99
Johnson David HOT DOG 1.99
HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
LG SFT DRK 1.49
This would happen generally if perhaps nobody recieved credit for the sale or the sale
was credited to the store by default.
SQL - Union
The union clause places two serarate queries together forming one table. A union works
best when using two tables with similar columns because each cloumn must have the
same data type.
Advertise on Tizag.com
Say we had another table called employees2 with the names and information of
employees from our second store. With 2 queries, we can combine the tables into a list of
all employees.
SQL Code:
SELECT * FROM employees
UNION
SELECT * FROM employees2;
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
2 Hively Jessica crew
9 Hicks Freddy crew
10 Harris Joel crew
11 Davis Julie manager
101 Yazzow Jim crew
102 Anderson Craig crew
103 Carlson Kevin crew
104 Maines Brad crew
The result is a complete listing every employee from store 1 and 2.
The next example shows a more practical means of using a union clause. Here we will
select all of our employees from both tables, and join them with our invoices table to
generate a complete list of sales from both stores on a given day.
SQL Code:
SELECT employees.Lastname, employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
INNER JOIN invoices
ON employees.id = invoices.EmployeeID
UNION
SELECT employees2.Lastname, employees2.Firstname, invoices.Sale,
invoices.Price
FROM employees2
INNER JOIN invoices
ON employees2.id = invoices.EmployeeID;
SQL Table:
Lastname Firstname Sale Price
Johnson David HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
Davis Julie CK SLD 3.99
Yazzow Jim HOT DOG 1.99
Carlson Kevin LG SFT DRK 1.49
Here we combined a join query with the union clause to create one table.
SQL Code:
SELECT * FROM employees
UNION ALL
SELECT * FROM employees2;
SQL Table:
ID Lastname Firstname Title
1 Johnson David crew
2 Hively Jessica crew
9 Hicks Freddy crew
10 Harris Joel crew
11 Davis Julie manager
101 Yazzow Jim crew
102 Anderson Craig crew
103 Carlson Kevin crew
11 Davis Julie manager
104 Maines Brad crew
SQL Code:
SELECT employees.Lastname, employees.Firstname, invoices.Sale,
invoices.Price
FROM employees
INNER JOIN invoices
ON employees.id = invoices.EmployeeID
UNION ALL
SELECT employees2.Lastname, employees2.Firstname, invoices.Sale,
invoices.Price
FROM employees2
INNER JOIN invoices
ON employees2.id = invoices.EmployeeID;
SQL Table:
Lastname Firstname Sale Price
Johnson David HOT DOG 1.99
Hively Jessica LG SFT DRK 1.49
Davis Julie CK SLD 3.99
11 Davis Julie manager
Yazzow Jim HOT DOG 1.99
Carlson Kevin LG SFT DRK 1.49
11 Davis Julie manager
11 Davis Julie manager
SQL - Subqueries
MySQL offers a very limited support for subqueries, however Oracle and DB2 fully
support them. Subqueries are Select queries placed within an existing SQL statement.
They may exist in any of the following types of SQL statements.
Advertise on Tizag.com
• Select
• Insert
• Update
• Delete
• Set
• Do
Subqueries are great for answering very specific questions regarding your data inside
your database. For instance, as the employer you may notice employee number 101 had a
great day yesterday with sales. Just given this information we can use a subquery to pull
the employee lastname and first name from our database.
SQL Code:
SELECT * FROM employees
WHERE id =
(SELECT EmployeeID FROM invoices WHERE EmployeeID='1');
SQL Table:
id Lastname Firstname Title
11 Davis Julie MANAGER
Here we have pulled our employee information from the employees table by only
knowing the employee number from the invoices table.
SQL Code:
INSERT INTO employees3
(id,Lastname,Firstname,Title)
(SELECT id,Lastname,Firstname,Title
FROM employees WHERE Title='manager');
With complete mastery of a subqueries you can now see the power of the SQL language.
The language is capable of nearly all things imaginable.
SQL - Dates
Unfortunately, every SQL platform has its own version of date functions, the few listed
work in DB2, Oracle, and MySQL. Microsoft SQL Server users should skip to our SQL
Datepart lesson.
Advertise on Tizag.com
SQL - Timestamp
A timestamp servers as the catch all for dates and times. Retrieving a timestamp is very
simple and the result can be converted or manipulated in nearly every way imaginable.
SQL Code:
SELECT CURRENT_TIMESTAMP;
Return a Timestamp:
2004-06-22 10:33:11.840
Keep in mind that each platform of SQL (DB2, Oracle, SQL Server, etc...) may return
dates and times which are formatted differently.
SQL Code:
SELECT MONTH(CURRENT_TIMESTAMP);
Return a Month:
6
SQL Code:
SELECT DAY(CURRENT_TIMESTAMP);
Return a Day:
22
There are many more functions available, including functions to extract milliseconds,
names of the months, names of each week day, etc. Each SQL platform varies in the
actual naming of date functions. Here's a few c\The following is a list of other date
functions available to most platforms of SQL with the exception of MS's SQL Server.
SELECT MONTHNAME(CURRENT_TIMESTAMP);
- returns the month name (January - December
SELECT DAYNAME(CURRENT_TIMESTAMP);
- returns the name of the day (Sunday - Saturday)
SQL Code:
SELECT MONTHNAME('2004-11-27');
SQL Code:
SELECT DAYOFYEAR(column_name) FROM table_name WHERE name = 'Joe';
SQL will return a numeric result from 1 - 365 representing the day of the year that Joe's
record was created/inserted.
We can expand this concept one step further with the use of a subquery. Say we have a
table with a column named timestamp. In this table column are timestamps of when each
record was entered and we would like to know what was the numeric day of the year that
a record was entered.
SQL Code:
SELECT DAYOFYEAR(
(SELECT DATE(timestamp) FROM employees WHERE name = 'James Bond')
);
Above you can see how it is possible to combine several date functions as well as a
subquery to return very specific information about Mr. James Bond.
SQL Code:
ALTER TABLE `orders` ADD `order_date`
TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Now each time an order is placed in our make believe business, a timestamp of that order
is also recorded.
A date or timestamp table column will only allow date data types to be inserted as values
so be sure to convert any strings or numbers to dates and timestamps before trying to
insert them
SQL - Datepart()
Microsoft's SQL Server takes a little different approach to working with dates. It is still
possible to extract individual parts of a timestamp and several other functions also work
as outlined in SQL - Date.
Advertise on Tizag.com
The difference is that SQL Server uses one main function as oppose to several different
functions ie the DATEPART() function. Datepart() requires two parameters, a part
argument and a date argument. By part we mean year, day of the year, day of the week,
etc. Let's look at an example.
SQL Code:
SELECT DATEPART(week, '2005-12-31');
SQL - Case
In SQL case works with either the select or update clauses. It provides when-then-else
functionality (WHEN this_happens THEN do_this) also known as conditional
statements.
Advertise on Tizag.com
SQL Code:
SELECT employee_name
CASE admin
WHEN 1 THEN 'yes'
ELSE 'no'
END 'admin'
FROM employees;
SQL Case:
employee_name admin
Ted no
Terry no
Trish yes
In short all we really did is replace 1's and 0's with the words 'yes' and 'no'.
SQL Code:
UPDATE inventory SET price = price *
CASE
WHEN quantity > 20 THEN 0.75
WHEN quantity BETWEEN 10 AND 20 THEN 0.90
ELSE 0.95
END;
SQL Case:
item quantity price
goldfish 12 .9
guppy 24 0.375
blow fish 1 4.75
Each price has automatically been reduced by the appropriate percentages